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.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1479                                                    EST_None)
1480                  .getTypePtr());
1481       Changed = true;
1482     }
1483 
1484     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1485     // only if the ExtParameterInfo lists of the two function prototypes can be
1486     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1487     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1488     bool CanUseToFPT, CanUseFromFPT;
1489     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1490                                       CanUseFromFPT, NewParamInfos) &&
1491         CanUseToFPT && !CanUseFromFPT) {
1492       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1493       ExtInfo.ExtParameterInfos =
1494           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1495       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1496                                             FromFPT->getParamTypes(), ExtInfo);
1497       FromFn = QT->getAs<FunctionType>();
1498       Changed = true;
1499     }
1500   }
1501 
1502   if (!Changed)
1503     return false;
1504 
1505   assert(QualType(FromFn, 0).isCanonical());
1506   if (QualType(FromFn, 0) != CanTo) return false;
1507 
1508   ResultTy = ToType;
1509   return true;
1510 }
1511 
1512 /// \brief Determine whether the conversion from FromType to ToType is a valid
1513 /// vector conversion.
1514 ///
1515 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1516 /// conversion.
1517 static bool IsVectorConversion(Sema &S, QualType FromType,
1518                                QualType ToType, ImplicitConversionKind &ICK) {
1519   // We need at least one of these types to be a vector type to have a vector
1520   // conversion.
1521   if (!ToType->isVectorType() && !FromType->isVectorType())
1522     return false;
1523 
1524   // Identical types require no conversions.
1525   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1526     return false;
1527 
1528   // There are no conversions between extended vector types, only identity.
1529   if (ToType->isExtVectorType()) {
1530     // There are no conversions between extended vector types other than the
1531     // identity conversion.
1532     if (FromType->isExtVectorType())
1533       return false;
1534 
1535     // Vector splat from any arithmetic type to a vector.
1536     if (FromType->isArithmeticType()) {
1537       ICK = ICK_Vector_Splat;
1538       return true;
1539     }
1540   }
1541 
1542   // We can perform the conversion between vector types in the following cases:
1543   // 1)vector types are equivalent AltiVec and GCC vector types
1544   // 2)lax vector conversions are permitted and the vector types are of the
1545   //   same size
1546   if (ToType->isVectorType() && FromType->isVectorType()) {
1547     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1548         S.isLaxVectorConversion(FromType, ToType)) {
1549       ICK = ICK_Vector_Conversion;
1550       return true;
1551     }
1552   }
1553 
1554   return false;
1555 }
1556 
1557 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1558                                 bool InOverloadResolution,
1559                                 StandardConversionSequence &SCS,
1560                                 bool CStyle);
1561 
1562 /// IsStandardConversion - Determines whether there is a standard
1563 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1564 /// expression From to the type ToType. Standard conversion sequences
1565 /// only consider non-class types; for conversions that involve class
1566 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1567 /// contain the standard conversion sequence required to perform this
1568 /// conversion and this routine will return true. Otherwise, this
1569 /// routine will return false and the value of SCS is unspecified.
1570 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1571                                  bool InOverloadResolution,
1572                                  StandardConversionSequence &SCS,
1573                                  bool CStyle,
1574                                  bool AllowObjCWritebackConversion) {
1575   QualType FromType = From->getType();
1576 
1577   // Standard conversions (C++ [conv])
1578   SCS.setAsIdentityConversion();
1579   SCS.IncompatibleObjC = false;
1580   SCS.setFromType(FromType);
1581   SCS.CopyConstructor = nullptr;
1582 
1583   // There are no standard conversions for class types in C++, so
1584   // abort early. When overloading in C, however, we do permit them.
1585   if (S.getLangOpts().CPlusPlus &&
1586       (FromType->isRecordType() || ToType->isRecordType()))
1587     return false;
1588 
1589   // The first conversion can be an lvalue-to-rvalue conversion,
1590   // array-to-pointer conversion, or function-to-pointer conversion
1591   // (C++ 4p1).
1592 
1593   if (FromType == S.Context.OverloadTy) {
1594     DeclAccessPair AccessPair;
1595     if (FunctionDecl *Fn
1596           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1597                                                  AccessPair)) {
1598       // We were able to resolve the address of the overloaded function,
1599       // so we can convert to the type of that function.
1600       FromType = Fn->getType();
1601       SCS.setFromType(FromType);
1602 
1603       // we can sometimes resolve &foo<int> regardless of ToType, so check
1604       // if the type matches (identity) or we are converting to bool
1605       if (!S.Context.hasSameUnqualifiedType(
1606                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1607         QualType resultTy;
1608         // if the function type matches except for [[noreturn]], it's ok
1609         if (!S.IsFunctionConversion(FromType,
1610               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1611           // otherwise, only a boolean conversion is standard
1612           if (!ToType->isBooleanType())
1613             return false;
1614       }
1615 
1616       // Check if the "from" expression is taking the address of an overloaded
1617       // function and recompute the FromType accordingly. Take advantage of the
1618       // fact that non-static member functions *must* have such an address-of
1619       // expression.
1620       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1621       if (Method && !Method->isStatic()) {
1622         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1623                "Non-unary operator on non-static member address");
1624         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1625                == UO_AddrOf &&
1626                "Non-address-of operator on non-static member address");
1627         const Type *ClassType
1628           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1629         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1630       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1631         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1632                UO_AddrOf &&
1633                "Non-address-of operator for overloaded function expression");
1634         FromType = S.Context.getPointerType(FromType);
1635       }
1636 
1637       // Check that we've computed the proper type after overload resolution.
1638       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1639       // be calling it from within an NDEBUG block.
1640       assert(S.Context.hasSameType(
1641         FromType,
1642         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1643     } else {
1644       return false;
1645     }
1646   }
1647   // Lvalue-to-rvalue conversion (C++11 4.1):
1648   //   A glvalue (3.10) of a non-function, non-array type T can
1649   //   be converted to a prvalue.
1650   bool argIsLValue = From->isGLValue();
1651   if (argIsLValue &&
1652       !FromType->isFunctionType() && !FromType->isArrayType() &&
1653       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1654     SCS.First = ICK_Lvalue_To_Rvalue;
1655 
1656     // C11 6.3.2.1p2:
1657     //   ... if the lvalue has atomic type, the value has the non-atomic version
1658     //   of the type of the lvalue ...
1659     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1660       FromType = Atomic->getValueType();
1661 
1662     // If T is a non-class type, the type of the rvalue is the
1663     // cv-unqualified version of T. Otherwise, the type of the rvalue
1664     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1665     // just strip the qualifiers because they don't matter.
1666     FromType = FromType.getUnqualifiedType();
1667   } else if (FromType->isArrayType()) {
1668     // Array-to-pointer conversion (C++ 4.2)
1669     SCS.First = ICK_Array_To_Pointer;
1670 
1671     // An lvalue or rvalue of type "array of N T" or "array of unknown
1672     // bound of T" can be converted to an rvalue of type "pointer to
1673     // T" (C++ 4.2p1).
1674     FromType = S.Context.getArrayDecayedType(FromType);
1675 
1676     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1677       // This conversion is deprecated in C++03 (D.4)
1678       SCS.DeprecatedStringLiteralToCharPtr = true;
1679 
1680       // For the purpose of ranking in overload resolution
1681       // (13.3.3.1.1), this conversion is considered an
1682       // array-to-pointer conversion followed by a qualification
1683       // conversion (4.4). (C++ 4.2p2)
1684       SCS.Second = ICK_Identity;
1685       SCS.Third = ICK_Qualification;
1686       SCS.QualificationIncludesObjCLifetime = false;
1687       SCS.setAllToTypes(FromType);
1688       return true;
1689     }
1690   } else if (FromType->isFunctionType() && argIsLValue) {
1691     // Function-to-pointer conversion (C++ 4.3).
1692     SCS.First = ICK_Function_To_Pointer;
1693 
1694     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1695       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1696         if (!S.checkAddressOfFunctionIsAvailable(FD))
1697           return false;
1698 
1699     // An lvalue of function type T can be converted to an rvalue of
1700     // type "pointer to T." The result is a pointer to the
1701     // function. (C++ 4.3p1).
1702     FromType = S.Context.getPointerType(FromType);
1703   } else {
1704     // We don't require any conversions for the first step.
1705     SCS.First = ICK_Identity;
1706   }
1707   SCS.setToType(0, FromType);
1708 
1709   // The second conversion can be an integral promotion, floating
1710   // point promotion, integral conversion, floating point conversion,
1711   // floating-integral conversion, pointer conversion,
1712   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1713   // For overloading in C, this can also be a "compatible-type"
1714   // conversion.
1715   bool IncompatibleObjC = false;
1716   ImplicitConversionKind SecondICK = ICK_Identity;
1717   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1718     // The unqualified versions of the types are the same: there's no
1719     // conversion to do.
1720     SCS.Second = ICK_Identity;
1721   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1722     // Integral promotion (C++ 4.5).
1723     SCS.Second = ICK_Integral_Promotion;
1724     FromType = ToType.getUnqualifiedType();
1725   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1726     // Floating point promotion (C++ 4.6).
1727     SCS.Second = ICK_Floating_Promotion;
1728     FromType = ToType.getUnqualifiedType();
1729   } else if (S.IsComplexPromotion(FromType, ToType)) {
1730     // Complex promotion (Clang extension)
1731     SCS.Second = ICK_Complex_Promotion;
1732     FromType = ToType.getUnqualifiedType();
1733   } else if (ToType->isBooleanType() &&
1734              (FromType->isArithmeticType() ||
1735               FromType->isAnyPointerType() ||
1736               FromType->isBlockPointerType() ||
1737               FromType->isMemberPointerType() ||
1738               FromType->isNullPtrType())) {
1739     // Boolean conversions (C++ 4.12).
1740     SCS.Second = ICK_Boolean_Conversion;
1741     FromType = S.Context.BoolTy;
1742   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1743              ToType->isIntegralType(S.Context)) {
1744     // Integral conversions (C++ 4.7).
1745     SCS.Second = ICK_Integral_Conversion;
1746     FromType = ToType.getUnqualifiedType();
1747   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1748     // Complex conversions (C99 6.3.1.6)
1749     SCS.Second = ICK_Complex_Conversion;
1750     FromType = ToType.getUnqualifiedType();
1751   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1752              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1753     // Complex-real conversions (C99 6.3.1.7)
1754     SCS.Second = ICK_Complex_Real;
1755     FromType = ToType.getUnqualifiedType();
1756   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1757     // FIXME: disable conversions between long double and __float128 if
1758     // their representation is different until there is back end support
1759     // We of course allow this conversion if long double is really double.
1760     if (&S.Context.getFloatTypeSemantics(FromType) !=
1761         &S.Context.getFloatTypeSemantics(ToType)) {
1762       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1763                                     ToType == S.Context.LongDoubleTy) ||
1764                                    (FromType == S.Context.LongDoubleTy &&
1765                                     ToType == S.Context.Float128Ty));
1766       if (Float128AndLongDouble &&
1767           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1768            &llvm::APFloat::IEEEdouble()))
1769         return false;
1770     }
1771     // Floating point conversions (C++ 4.8).
1772     SCS.Second = ICK_Floating_Conversion;
1773     FromType = ToType.getUnqualifiedType();
1774   } else if ((FromType->isRealFloatingType() &&
1775               ToType->isIntegralType(S.Context)) ||
1776              (FromType->isIntegralOrUnscopedEnumerationType() &&
1777               ToType->isRealFloatingType())) {
1778     // Floating-integral conversions (C++ 4.9).
1779     SCS.Second = ICK_Floating_Integral;
1780     FromType = ToType.getUnqualifiedType();
1781   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1782     SCS.Second = ICK_Block_Pointer_Conversion;
1783   } else if (AllowObjCWritebackConversion &&
1784              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1785     SCS.Second = ICK_Writeback_Conversion;
1786   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1787                                    FromType, IncompatibleObjC)) {
1788     // Pointer conversions (C++ 4.10).
1789     SCS.Second = ICK_Pointer_Conversion;
1790     SCS.IncompatibleObjC = IncompatibleObjC;
1791     FromType = FromType.getUnqualifiedType();
1792   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1793                                          InOverloadResolution, FromType)) {
1794     // Pointer to member conversions (4.11).
1795     SCS.Second = ICK_Pointer_Member;
1796   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1797     SCS.Second = SecondICK;
1798     FromType = ToType.getUnqualifiedType();
1799   } else if (!S.getLangOpts().CPlusPlus &&
1800              S.Context.typesAreCompatible(ToType, FromType)) {
1801     // Compatible conversions (Clang extension for C function overloading)
1802     SCS.Second = ICK_Compatible_Conversion;
1803     FromType = ToType.getUnqualifiedType();
1804   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1805                                              InOverloadResolution,
1806                                              SCS, CStyle)) {
1807     SCS.Second = ICK_TransparentUnionConversion;
1808     FromType = ToType;
1809   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1810                                  CStyle)) {
1811     // tryAtomicConversion has updated the standard conversion sequence
1812     // appropriately.
1813     return true;
1814   } else if (ToType->isEventT() &&
1815              From->isIntegerConstantExpr(S.getASTContext()) &&
1816              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1817     SCS.Second = ICK_Zero_Event_Conversion;
1818     FromType = ToType;
1819   } else if (ToType->isQueueT() &&
1820              From->isIntegerConstantExpr(S.getASTContext()) &&
1821              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1822     SCS.Second = ICK_Zero_Queue_Conversion;
1823     FromType = ToType;
1824   } else {
1825     // No second conversion required.
1826     SCS.Second = ICK_Identity;
1827   }
1828   SCS.setToType(1, FromType);
1829 
1830   // The third conversion can be a function pointer conversion or a
1831   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1832   bool ObjCLifetimeConversion;
1833   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1834     // Function pointer conversions (removing 'noexcept') including removal of
1835     // 'noreturn' (Clang extension).
1836     SCS.Third = ICK_Function_Conversion;
1837   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1838                                          ObjCLifetimeConversion)) {
1839     SCS.Third = ICK_Qualification;
1840     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1841     FromType = ToType;
1842   } else {
1843     // No conversion required
1844     SCS.Third = ICK_Identity;
1845   }
1846 
1847   // C++ [over.best.ics]p6:
1848   //   [...] Any difference in top-level cv-qualification is
1849   //   subsumed by the initialization itself and does not constitute
1850   //   a conversion. [...]
1851   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1852   QualType CanonTo = S.Context.getCanonicalType(ToType);
1853   if (CanonFrom.getLocalUnqualifiedType()
1854                                      == CanonTo.getLocalUnqualifiedType() &&
1855       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1856     FromType = ToType;
1857     CanonFrom = CanonTo;
1858   }
1859 
1860   SCS.setToType(2, FromType);
1861 
1862   if (CanonFrom == CanonTo)
1863     return true;
1864 
1865   // If we have not converted the argument type to the parameter type,
1866   // this is a bad conversion sequence, unless we're resolving an overload in C.
1867   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1868     return false;
1869 
1870   ExprResult ER = ExprResult{From};
1871   Sema::AssignConvertType Conv =
1872       S.CheckSingleAssignmentConstraints(ToType, ER,
1873                                          /*Diagnose=*/false,
1874                                          /*DiagnoseCFAudited=*/false,
1875                                          /*ConvertRHS=*/false);
1876   ImplicitConversionKind SecondConv;
1877   switch (Conv) {
1878   case Sema::Compatible:
1879     SecondConv = ICK_C_Only_Conversion;
1880     break;
1881   // For our purposes, discarding qualifiers is just as bad as using an
1882   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1883   // qualifiers, as well.
1884   case Sema::CompatiblePointerDiscardsQualifiers:
1885   case Sema::IncompatiblePointer:
1886   case Sema::IncompatiblePointerSign:
1887     SecondConv = ICK_Incompatible_Pointer_Conversion;
1888     break;
1889   default:
1890     return false;
1891   }
1892 
1893   // First can only be an lvalue conversion, so we pretend that this was the
1894   // second conversion. First should already be valid from earlier in the
1895   // function.
1896   SCS.Second = SecondConv;
1897   SCS.setToType(1, ToType);
1898 
1899   // Third is Identity, because Second should rank us worse than any other
1900   // conversion. This could also be ICK_Qualification, but it's simpler to just
1901   // lump everything in with the second conversion, and we don't gain anything
1902   // from making this ICK_Qualification.
1903   SCS.Third = ICK_Identity;
1904   SCS.setToType(2, ToType);
1905   return true;
1906 }
1907 
1908 static bool
1909 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1910                                      QualType &ToType,
1911                                      bool InOverloadResolution,
1912                                      StandardConversionSequence &SCS,
1913                                      bool CStyle) {
1914 
1915   const RecordType *UT = ToType->getAsUnionType();
1916   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1917     return false;
1918   // The field to initialize within the transparent union.
1919   RecordDecl *UD = UT->getDecl();
1920   // It's compatible if the expression matches any of the fields.
1921   for (const auto *it : UD->fields()) {
1922     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1923                              CStyle, /*ObjCWritebackConversion=*/false)) {
1924       ToType = it->getType();
1925       return true;
1926     }
1927   }
1928   return false;
1929 }
1930 
1931 /// IsIntegralPromotion - Determines whether the conversion from the
1932 /// expression From (whose potentially-adjusted type is FromType) to
1933 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1934 /// sets PromotedType to the promoted type.
1935 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1936   const BuiltinType *To = ToType->getAs<BuiltinType>();
1937   // All integers are built-in.
1938   if (!To) {
1939     return false;
1940   }
1941 
1942   // An rvalue of type char, signed char, unsigned char, short int, or
1943   // unsigned short int can be converted to an rvalue of type int if
1944   // int can represent all the values of the source type; otherwise,
1945   // the source rvalue can be converted to an rvalue of type unsigned
1946   // int (C++ 4.5p1).
1947   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1948       !FromType->isEnumeralType()) {
1949     if (// We can promote any signed, promotable integer type to an int
1950         (FromType->isSignedIntegerType() ||
1951          // We can promote any unsigned integer type whose size is
1952          // less than int to an int.
1953          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1954       return To->getKind() == BuiltinType::Int;
1955     }
1956 
1957     return To->getKind() == BuiltinType::UInt;
1958   }
1959 
1960   // C++11 [conv.prom]p3:
1961   //   A prvalue of an unscoped enumeration type whose underlying type is not
1962   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1963   //   following types that can represent all the values of the enumeration
1964   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1965   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1966   //   long long int. If none of the types in that list can represent all the
1967   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1968   //   type can be converted to an rvalue a prvalue of the extended integer type
1969   //   with lowest integer conversion rank (4.13) greater than the rank of long
1970   //   long in which all the values of the enumeration can be represented. If
1971   //   there are two such extended types, the signed one is chosen.
1972   // C++11 [conv.prom]p4:
1973   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1974   //   can be converted to a prvalue of its underlying type. Moreover, if
1975   //   integral promotion can be applied to its underlying type, a prvalue of an
1976   //   unscoped enumeration type whose underlying type is fixed can also be
1977   //   converted to a prvalue of the promoted underlying type.
1978   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1979     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1980     // provided for a scoped enumeration.
1981     if (FromEnumType->getDecl()->isScoped())
1982       return false;
1983 
1984     // We can perform an integral promotion to the underlying type of the enum,
1985     // even if that's not the promoted type. Note that the check for promoting
1986     // the underlying type is based on the type alone, and does not consider
1987     // the bitfield-ness of the actual source expression.
1988     if (FromEnumType->getDecl()->isFixed()) {
1989       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1990       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1991              IsIntegralPromotion(nullptr, Underlying, ToType);
1992     }
1993 
1994     // We have already pre-calculated the promotion type, so this is trivial.
1995     if (ToType->isIntegerType() &&
1996         isCompleteType(From->getLocStart(), FromType))
1997       return Context.hasSameUnqualifiedType(
1998           ToType, FromEnumType->getDecl()->getPromotionType());
1999   }
2000 
2001   // C++0x [conv.prom]p2:
2002   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2003   //   to an rvalue a prvalue of the first of the following types that can
2004   //   represent all the values of its underlying type: int, unsigned int,
2005   //   long int, unsigned long int, long long int, or unsigned long long int.
2006   //   If none of the types in that list can represent all the values of its
2007   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2008   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2009   //   type.
2010   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2011       ToType->isIntegerType()) {
2012     // Determine whether the type we're converting from is signed or
2013     // unsigned.
2014     bool FromIsSigned = FromType->isSignedIntegerType();
2015     uint64_t FromSize = Context.getTypeSize(FromType);
2016 
2017     // The types we'll try to promote to, in the appropriate
2018     // order. Try each of these types.
2019     QualType PromoteTypes[6] = {
2020       Context.IntTy, Context.UnsignedIntTy,
2021       Context.LongTy, Context.UnsignedLongTy ,
2022       Context.LongLongTy, Context.UnsignedLongLongTy
2023     };
2024     for (int Idx = 0; Idx < 6; ++Idx) {
2025       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2026       if (FromSize < ToSize ||
2027           (FromSize == ToSize &&
2028            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2029         // We found the type that we can promote to. If this is the
2030         // type we wanted, we have a promotion. Otherwise, no
2031         // promotion.
2032         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2033       }
2034     }
2035   }
2036 
2037   // An rvalue for an integral bit-field (9.6) can be converted to an
2038   // rvalue of type int if int can represent all the values of the
2039   // bit-field; otherwise, it can be converted to unsigned int if
2040   // unsigned int can represent all the values of the bit-field. If
2041   // the bit-field is larger yet, no integral promotion applies to
2042   // it. If the bit-field has an enumerated type, it is treated as any
2043   // other value of that type for promotion purposes (C++ 4.5p3).
2044   // FIXME: We should delay checking of bit-fields until we actually perform the
2045   // conversion.
2046   if (From) {
2047     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2048       llvm::APSInt BitWidth;
2049       if (FromType->isIntegralType(Context) &&
2050           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2051         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2052         ToSize = Context.getTypeSize(ToType);
2053 
2054         // Are we promoting to an int from a bitfield that fits in an int?
2055         if (BitWidth < ToSize ||
2056             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2057           return To->getKind() == BuiltinType::Int;
2058         }
2059 
2060         // Are we promoting to an unsigned int from an unsigned bitfield
2061         // that fits into an unsigned int?
2062         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2063           return To->getKind() == BuiltinType::UInt;
2064         }
2065 
2066         return false;
2067       }
2068     }
2069   }
2070 
2071   // An rvalue of type bool can be converted to an rvalue of type int,
2072   // with false becoming zero and true becoming one (C++ 4.5p4).
2073   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2074     return true;
2075   }
2076 
2077   return false;
2078 }
2079 
2080 /// IsFloatingPointPromotion - Determines whether the conversion from
2081 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2082 /// returns true and sets PromotedType to the promoted type.
2083 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2084   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2085     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2086       /// An rvalue of type float can be converted to an rvalue of type
2087       /// double. (C++ 4.6p1).
2088       if (FromBuiltin->getKind() == BuiltinType::Float &&
2089           ToBuiltin->getKind() == BuiltinType::Double)
2090         return true;
2091 
2092       // C99 6.3.1.5p1:
2093       //   When a float is promoted to double or long double, or a
2094       //   double is promoted to long double [...].
2095       if (!getLangOpts().CPlusPlus &&
2096           (FromBuiltin->getKind() == BuiltinType::Float ||
2097            FromBuiltin->getKind() == BuiltinType::Double) &&
2098           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2099            ToBuiltin->getKind() == BuiltinType::Float128))
2100         return true;
2101 
2102       // Half can be promoted to float.
2103       if (!getLangOpts().NativeHalfType &&
2104            FromBuiltin->getKind() == BuiltinType::Half &&
2105           ToBuiltin->getKind() == BuiltinType::Float)
2106         return true;
2107     }
2108 
2109   return false;
2110 }
2111 
2112 /// \brief Determine if a conversion is a complex promotion.
2113 ///
2114 /// A complex promotion is defined as a complex -> complex conversion
2115 /// where the conversion between the underlying real types is a
2116 /// floating-point or integral promotion.
2117 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2118   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2119   if (!FromComplex)
2120     return false;
2121 
2122   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2123   if (!ToComplex)
2124     return false;
2125 
2126   return IsFloatingPointPromotion(FromComplex->getElementType(),
2127                                   ToComplex->getElementType()) ||
2128     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2129                         ToComplex->getElementType());
2130 }
2131 
2132 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2133 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2134 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2135 /// if non-empty, will be a pointer to ToType that may or may not have
2136 /// the right set of qualifiers on its pointee.
2137 ///
2138 static QualType
2139 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2140                                    QualType ToPointee, QualType ToType,
2141                                    ASTContext &Context,
2142                                    bool StripObjCLifetime = false) {
2143   assert((FromPtr->getTypeClass() == Type::Pointer ||
2144           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2145          "Invalid similarly-qualified pointer type");
2146 
2147   /// Conversions to 'id' subsume cv-qualifier conversions.
2148   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2149     return ToType.getUnqualifiedType();
2150 
2151   QualType CanonFromPointee
2152     = Context.getCanonicalType(FromPtr->getPointeeType());
2153   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2154   Qualifiers Quals = CanonFromPointee.getQualifiers();
2155 
2156   if (StripObjCLifetime)
2157     Quals.removeObjCLifetime();
2158 
2159   // Exact qualifier match -> return the pointer type we're converting to.
2160   if (CanonToPointee.getLocalQualifiers() == Quals) {
2161     // ToType is exactly what we need. Return it.
2162     if (!ToType.isNull())
2163       return ToType.getUnqualifiedType();
2164 
2165     // Build a pointer to ToPointee. It has the right qualifiers
2166     // already.
2167     if (isa<ObjCObjectPointerType>(ToType))
2168       return Context.getObjCObjectPointerType(ToPointee);
2169     return Context.getPointerType(ToPointee);
2170   }
2171 
2172   // Just build a canonical type that has the right qualifiers.
2173   QualType QualifiedCanonToPointee
2174     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2175 
2176   if (isa<ObjCObjectPointerType>(ToType))
2177     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2178   return Context.getPointerType(QualifiedCanonToPointee);
2179 }
2180 
2181 static bool isNullPointerConstantForConversion(Expr *Expr,
2182                                                bool InOverloadResolution,
2183                                                ASTContext &Context) {
2184   // Handle value-dependent integral null pointer constants correctly.
2185   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2186   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2187       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2188     return !InOverloadResolution;
2189 
2190   return Expr->isNullPointerConstant(Context,
2191                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2192                                         : Expr::NPC_ValueDependentIsNull);
2193 }
2194 
2195 /// IsPointerConversion - Determines whether the conversion of the
2196 /// expression From, which has the (possibly adjusted) type FromType,
2197 /// can be converted to the type ToType via a pointer conversion (C++
2198 /// 4.10). If so, returns true and places the converted type (that
2199 /// might differ from ToType in its cv-qualifiers at some level) into
2200 /// ConvertedType.
2201 ///
2202 /// This routine also supports conversions to and from block pointers
2203 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2204 /// pointers to interfaces. FIXME: Once we've determined the
2205 /// appropriate overloading rules for Objective-C, we may want to
2206 /// split the Objective-C checks into a different routine; however,
2207 /// GCC seems to consider all of these conversions to be pointer
2208 /// conversions, so for now they live here. IncompatibleObjC will be
2209 /// set if the conversion is an allowed Objective-C conversion that
2210 /// should result in a warning.
2211 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2212                                bool InOverloadResolution,
2213                                QualType& ConvertedType,
2214                                bool &IncompatibleObjC) {
2215   IncompatibleObjC = false;
2216   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2217                               IncompatibleObjC))
2218     return true;
2219 
2220   // Conversion from a null pointer constant to any Objective-C pointer type.
2221   if (ToType->isObjCObjectPointerType() &&
2222       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2223     ConvertedType = ToType;
2224     return true;
2225   }
2226 
2227   // Blocks: Block pointers can be converted to void*.
2228   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2229       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2230     ConvertedType = ToType;
2231     return true;
2232   }
2233   // Blocks: A null pointer constant can be converted to a block
2234   // pointer type.
2235   if (ToType->isBlockPointerType() &&
2236       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2237     ConvertedType = ToType;
2238     return true;
2239   }
2240 
2241   // If the left-hand-side is nullptr_t, the right side can be a null
2242   // pointer constant.
2243   if (ToType->isNullPtrType() &&
2244       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2245     ConvertedType = ToType;
2246     return true;
2247   }
2248 
2249   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2250   if (!ToTypePtr)
2251     return false;
2252 
2253   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2254   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258 
2259   // Beyond this point, both types need to be pointers
2260   // , including objective-c pointers.
2261   QualType ToPointeeType = ToTypePtr->getPointeeType();
2262   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2263       !getLangOpts().ObjCAutoRefCount) {
2264     ConvertedType = BuildSimilarlyQualifiedPointerType(
2265                                       FromType->getAs<ObjCObjectPointerType>(),
2266                                                        ToPointeeType,
2267                                                        ToType, Context);
2268     return true;
2269   }
2270   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2271   if (!FromTypePtr)
2272     return false;
2273 
2274   QualType FromPointeeType = FromTypePtr->getPointeeType();
2275 
2276   // If the unqualified pointee types are the same, this can't be a
2277   // pointer conversion, so don't do all of the work below.
2278   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2279     return false;
2280 
2281   // An rvalue of type "pointer to cv T," where T is an object type,
2282   // can be converted to an rvalue of type "pointer to cv void" (C++
2283   // 4.10p2).
2284   if (FromPointeeType->isIncompleteOrObjectType() &&
2285       ToPointeeType->isVoidType()) {
2286     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2287                                                        ToPointeeType,
2288                                                        ToType, Context,
2289                                                    /*StripObjCLifetime=*/true);
2290     return true;
2291   }
2292 
2293   // MSVC allows implicit function to void* type conversion.
2294   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2295       ToPointeeType->isVoidType()) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297                                                        ToPointeeType,
2298                                                        ToType, Context);
2299     return true;
2300   }
2301 
2302   // When we're overloading in C, we allow a special kind of pointer
2303   // conversion for compatible-but-not-identical pointee types.
2304   if (!getLangOpts().CPlusPlus &&
2305       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2306     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2307                                                        ToPointeeType,
2308                                                        ToType, Context);
2309     return true;
2310   }
2311 
2312   // C++ [conv.ptr]p3:
2313   //
2314   //   An rvalue of type "pointer to cv D," where D is a class type,
2315   //   can be converted to an rvalue of type "pointer to cv B," where
2316   //   B is a base class (clause 10) of D. If B is an inaccessible
2317   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2318   //   necessitates this conversion is ill-formed. The result of the
2319   //   conversion is a pointer to the base class sub-object of the
2320   //   derived class object. The null pointer value is converted to
2321   //   the null pointer value of the destination type.
2322   //
2323   // Note that we do not check for ambiguity or inaccessibility
2324   // here. That is handled by CheckPointerConversion.
2325   if (getLangOpts().CPlusPlus &&
2326       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2327       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2328       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2329     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2330                                                        ToPointeeType,
2331                                                        ToType, Context);
2332     return true;
2333   }
2334 
2335   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2336       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2337     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338                                                        ToPointeeType,
2339                                                        ToType, Context);
2340     return true;
2341   }
2342 
2343   return false;
2344 }
2345 
2346 /// \brief Adopt the given qualifiers for the given type.
2347 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2348   Qualifiers TQs = T.getQualifiers();
2349 
2350   // Check whether qualifiers already match.
2351   if (TQs == Qs)
2352     return T;
2353 
2354   if (Qs.compatiblyIncludes(TQs))
2355     return Context.getQualifiedType(T, Qs);
2356 
2357   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2358 }
2359 
2360 /// isObjCPointerConversion - Determines whether this is an
2361 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2362 /// with the same arguments and return values.
2363 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2364                                    QualType& ConvertedType,
2365                                    bool &IncompatibleObjC) {
2366   if (!getLangOpts().ObjC1)
2367     return false;
2368 
2369   // The set of qualifiers on the type we're converting from.
2370   Qualifiers FromQualifiers = FromType.getQualifiers();
2371 
2372   // First, we handle all conversions on ObjC object pointer types.
2373   const ObjCObjectPointerType* ToObjCPtr =
2374     ToType->getAs<ObjCObjectPointerType>();
2375   const ObjCObjectPointerType *FromObjCPtr =
2376     FromType->getAs<ObjCObjectPointerType>();
2377 
2378   if (ToObjCPtr && FromObjCPtr) {
2379     // If the pointee types are the same (ignoring qualifications),
2380     // then this is not a pointer conversion.
2381     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2382                                        FromObjCPtr->getPointeeType()))
2383       return false;
2384 
2385     // Conversion between Objective-C pointers.
2386     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2387       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2388       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2389       if (getLangOpts().CPlusPlus && LHS && RHS &&
2390           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2391                                                 FromObjCPtr->getPointeeType()))
2392         return false;
2393       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2394                                                    ToObjCPtr->getPointeeType(),
2395                                                          ToType, Context);
2396       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2397       return true;
2398     }
2399 
2400     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2401       // Okay: this is some kind of implicit downcast of Objective-C
2402       // interfaces, which is permitted. However, we're going to
2403       // complain about it.
2404       IncompatibleObjC = true;
2405       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2406                                                    ToObjCPtr->getPointeeType(),
2407                                                          ToType, Context);
2408       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2409       return true;
2410     }
2411   }
2412   // Beyond this point, both types need to be C pointers or block pointers.
2413   QualType ToPointeeType;
2414   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2415     ToPointeeType = ToCPtr->getPointeeType();
2416   else if (const BlockPointerType *ToBlockPtr =
2417             ToType->getAs<BlockPointerType>()) {
2418     // Objective C++: We're able to convert from a pointer to any object
2419     // to a block pointer type.
2420     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2421       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2422       return true;
2423     }
2424     ToPointeeType = ToBlockPtr->getPointeeType();
2425   }
2426   else if (FromType->getAs<BlockPointerType>() &&
2427            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2428     // Objective C++: We're able to convert from a block pointer type to a
2429     // pointer to any object.
2430     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2431     return true;
2432   }
2433   else
2434     return false;
2435 
2436   QualType FromPointeeType;
2437   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2438     FromPointeeType = FromCPtr->getPointeeType();
2439   else if (const BlockPointerType *FromBlockPtr =
2440            FromType->getAs<BlockPointerType>())
2441     FromPointeeType = FromBlockPtr->getPointeeType();
2442   else
2443     return false;
2444 
2445   // If we have pointers to pointers, recursively check whether this
2446   // is an Objective-C conversion.
2447   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2448       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2449                               IncompatibleObjC)) {
2450     // We always complain about this conversion.
2451     IncompatibleObjC = true;
2452     ConvertedType = Context.getPointerType(ConvertedType);
2453     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2454     return true;
2455   }
2456   // Allow conversion of pointee being objective-c pointer to another one;
2457   // as in I* to id.
2458   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2459       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2460       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2461                               IncompatibleObjC)) {
2462 
2463     ConvertedType = Context.getPointerType(ConvertedType);
2464     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2465     return true;
2466   }
2467 
2468   // If we have pointers to functions or blocks, check whether the only
2469   // differences in the argument and result types are in Objective-C
2470   // pointer conversions. If so, we permit the conversion (but
2471   // complain about it).
2472   const FunctionProtoType *FromFunctionType
2473     = FromPointeeType->getAs<FunctionProtoType>();
2474   const FunctionProtoType *ToFunctionType
2475     = ToPointeeType->getAs<FunctionProtoType>();
2476   if (FromFunctionType && ToFunctionType) {
2477     // If the function types are exactly the same, this isn't an
2478     // Objective-C pointer conversion.
2479     if (Context.getCanonicalType(FromPointeeType)
2480           == Context.getCanonicalType(ToPointeeType))
2481       return false;
2482 
2483     // Perform the quick checks that will tell us whether these
2484     // function types are obviously different.
2485     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2486         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2487         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2488       return false;
2489 
2490     bool HasObjCConversion = false;
2491     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2492         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2493       // Okay, the types match exactly. Nothing to do.
2494     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2495                                        ToFunctionType->getReturnType(),
2496                                        ConvertedType, IncompatibleObjC)) {
2497       // Okay, we have an Objective-C pointer conversion.
2498       HasObjCConversion = true;
2499     } else {
2500       // Function types are too different. Abort.
2501       return false;
2502     }
2503 
2504     // Check argument types.
2505     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2506          ArgIdx != NumArgs; ++ArgIdx) {
2507       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2508       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2509       if (Context.getCanonicalType(FromArgType)
2510             == Context.getCanonicalType(ToArgType)) {
2511         // Okay, the types match exactly. Nothing to do.
2512       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2513                                          ConvertedType, IncompatibleObjC)) {
2514         // Okay, we have an Objective-C pointer conversion.
2515         HasObjCConversion = true;
2516       } else {
2517         // Argument types are too different. Abort.
2518         return false;
2519       }
2520     }
2521 
2522     if (HasObjCConversion) {
2523       // We had an Objective-C conversion. Allow this pointer
2524       // conversion, but complain about it.
2525       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2526       IncompatibleObjC = true;
2527       return true;
2528     }
2529   }
2530 
2531   return false;
2532 }
2533 
2534 /// \brief Determine whether this is an Objective-C writeback conversion,
2535 /// used for parameter passing when performing automatic reference counting.
2536 ///
2537 /// \param FromType The type we're converting form.
2538 ///
2539 /// \param ToType The type we're converting to.
2540 ///
2541 /// \param ConvertedType The type that will be produced after applying
2542 /// this conversion.
2543 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2544                                      QualType &ConvertedType) {
2545   if (!getLangOpts().ObjCAutoRefCount ||
2546       Context.hasSameUnqualifiedType(FromType, ToType))
2547     return false;
2548 
2549   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2550   QualType ToPointee;
2551   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2552     ToPointee = ToPointer->getPointeeType();
2553   else
2554     return false;
2555 
2556   Qualifiers ToQuals = ToPointee.getQualifiers();
2557   if (!ToPointee->isObjCLifetimeType() ||
2558       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2559       !ToQuals.withoutObjCLifetime().empty())
2560     return false;
2561 
2562   // Argument must be a pointer to __strong to __weak.
2563   QualType FromPointee;
2564   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2565     FromPointee = FromPointer->getPointeeType();
2566   else
2567     return false;
2568 
2569   Qualifiers FromQuals = FromPointee.getQualifiers();
2570   if (!FromPointee->isObjCLifetimeType() ||
2571       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2572        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2573     return false;
2574 
2575   // Make sure that we have compatible qualifiers.
2576   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2577   if (!ToQuals.compatiblyIncludes(FromQuals))
2578     return false;
2579 
2580   // Remove qualifiers from the pointee type we're converting from; they
2581   // aren't used in the compatibility check belong, and we'll be adding back
2582   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2583   FromPointee = FromPointee.getUnqualifiedType();
2584 
2585   // The unqualified form of the pointee types must be compatible.
2586   ToPointee = ToPointee.getUnqualifiedType();
2587   bool IncompatibleObjC;
2588   if (Context.typesAreCompatible(FromPointee, ToPointee))
2589     FromPointee = ToPointee;
2590   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2591                                     IncompatibleObjC))
2592     return false;
2593 
2594   /// \brief Construct the type we're converting to, which is a pointer to
2595   /// __autoreleasing pointee.
2596   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2597   ConvertedType = Context.getPointerType(FromPointee);
2598   return true;
2599 }
2600 
2601 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2602                                     QualType& ConvertedType) {
2603   QualType ToPointeeType;
2604   if (const BlockPointerType *ToBlockPtr =
2605         ToType->getAs<BlockPointerType>())
2606     ToPointeeType = ToBlockPtr->getPointeeType();
2607   else
2608     return false;
2609 
2610   QualType FromPointeeType;
2611   if (const BlockPointerType *FromBlockPtr =
2612       FromType->getAs<BlockPointerType>())
2613     FromPointeeType = FromBlockPtr->getPointeeType();
2614   else
2615     return false;
2616   // We have pointer to blocks, check whether the only
2617   // differences in the argument and result types are in Objective-C
2618   // pointer conversions. If so, we permit the conversion.
2619 
2620   const FunctionProtoType *FromFunctionType
2621     = FromPointeeType->getAs<FunctionProtoType>();
2622   const FunctionProtoType *ToFunctionType
2623     = ToPointeeType->getAs<FunctionProtoType>();
2624 
2625   if (!FromFunctionType || !ToFunctionType)
2626     return false;
2627 
2628   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2629     return true;
2630 
2631   // Perform the quick checks that will tell us whether these
2632   // function types are obviously different.
2633   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2634       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2635     return false;
2636 
2637   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2638   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2639   if (FromEInfo != ToEInfo)
2640     return false;
2641 
2642   bool IncompatibleObjC = false;
2643   if (Context.hasSameType(FromFunctionType->getReturnType(),
2644                           ToFunctionType->getReturnType())) {
2645     // Okay, the types match exactly. Nothing to do.
2646   } else {
2647     QualType RHS = FromFunctionType->getReturnType();
2648     QualType LHS = ToFunctionType->getReturnType();
2649     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2650         !RHS.hasQualifiers() && LHS.hasQualifiers())
2651        LHS = LHS.getUnqualifiedType();
2652 
2653      if (Context.hasSameType(RHS,LHS)) {
2654        // OK exact match.
2655      } else if (isObjCPointerConversion(RHS, LHS,
2656                                         ConvertedType, IncompatibleObjC)) {
2657      if (IncompatibleObjC)
2658        return false;
2659      // Okay, we have an Objective-C pointer conversion.
2660      }
2661      else
2662        return false;
2663    }
2664 
2665    // Check argument types.
2666    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2667         ArgIdx != NumArgs; ++ArgIdx) {
2668      IncompatibleObjC = false;
2669      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2670      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2671      if (Context.hasSameType(FromArgType, ToArgType)) {
2672        // Okay, the types match exactly. Nothing to do.
2673      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2674                                         ConvertedType, IncompatibleObjC)) {
2675        if (IncompatibleObjC)
2676          return false;
2677        // Okay, we have an Objective-C pointer conversion.
2678      } else
2679        // Argument types are too different. Abort.
2680        return false;
2681    }
2682 
2683    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2684    bool CanUseToFPT, CanUseFromFPT;
2685    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2686                                       CanUseToFPT, CanUseFromFPT,
2687                                       NewParamInfos))
2688      return false;
2689 
2690    ConvertedType = ToType;
2691    return true;
2692 }
2693 
2694 enum {
2695   ft_default,
2696   ft_different_class,
2697   ft_parameter_arity,
2698   ft_parameter_mismatch,
2699   ft_return_type,
2700   ft_qualifer_mismatch,
2701   ft_noexcept
2702 };
2703 
2704 /// Attempts to get the FunctionProtoType from a Type. Handles
2705 /// MemberFunctionPointers properly.
2706 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2707   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2708     return FPT;
2709 
2710   if (auto *MPT = FromType->getAs<MemberPointerType>())
2711     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2712 
2713   return nullptr;
2714 }
2715 
2716 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2717 /// function types.  Catches different number of parameter, mismatch in
2718 /// parameter types, and different return types.
2719 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2720                                       QualType FromType, QualType ToType) {
2721   // If either type is not valid, include no extra info.
2722   if (FromType.isNull() || ToType.isNull()) {
2723     PDiag << ft_default;
2724     return;
2725   }
2726 
2727   // Get the function type from the pointers.
2728   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2729     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2730                             *ToMember = ToType->getAs<MemberPointerType>();
2731     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2732       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2733             << QualType(FromMember->getClass(), 0);
2734       return;
2735     }
2736     FromType = FromMember->getPointeeType();
2737     ToType = ToMember->getPointeeType();
2738   }
2739 
2740   if (FromType->isPointerType())
2741     FromType = FromType->getPointeeType();
2742   if (ToType->isPointerType())
2743     ToType = ToType->getPointeeType();
2744 
2745   // Remove references.
2746   FromType = FromType.getNonReferenceType();
2747   ToType = ToType.getNonReferenceType();
2748 
2749   // Don't print extra info for non-specialized template functions.
2750   if (FromType->isInstantiationDependentType() &&
2751       !FromType->getAs<TemplateSpecializationType>()) {
2752     PDiag << ft_default;
2753     return;
2754   }
2755 
2756   // No extra info for same types.
2757   if (Context.hasSameType(FromType, ToType)) {
2758     PDiag << ft_default;
2759     return;
2760   }
2761 
2762   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2763                           *ToFunction = tryGetFunctionProtoType(ToType);
2764 
2765   // Both types need to be function types.
2766   if (!FromFunction || !ToFunction) {
2767     PDiag << ft_default;
2768     return;
2769   }
2770 
2771   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2772     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2773           << FromFunction->getNumParams();
2774     return;
2775   }
2776 
2777   // Handle different parameter types.
2778   unsigned ArgPos;
2779   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2780     PDiag << ft_parameter_mismatch << ArgPos + 1
2781           << ToFunction->getParamType(ArgPos)
2782           << FromFunction->getParamType(ArgPos);
2783     return;
2784   }
2785 
2786   // Handle different return type.
2787   if (!Context.hasSameType(FromFunction->getReturnType(),
2788                            ToFunction->getReturnType())) {
2789     PDiag << ft_return_type << ToFunction->getReturnType()
2790           << FromFunction->getReturnType();
2791     return;
2792   }
2793 
2794   unsigned FromQuals = FromFunction->getTypeQuals(),
2795            ToQuals = ToFunction->getTypeQuals();
2796   if (FromQuals != ToQuals) {
2797     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2798     return;
2799   }
2800 
2801   // Handle exception specification differences on canonical type (in C++17
2802   // onwards).
2803   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2804           ->isNothrow(Context) !=
2805       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2806           ->isNothrow(Context)) {
2807     PDiag << ft_noexcept;
2808     return;
2809   }
2810 
2811   // Unable to find a difference, so add no extra info.
2812   PDiag << ft_default;
2813 }
2814 
2815 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2816 /// for equality of their argument types. Caller has already checked that
2817 /// they have same number of arguments.  If the parameters are different,
2818 /// ArgPos will have the parameter index of the first different parameter.
2819 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2820                                       const FunctionProtoType *NewType,
2821                                       unsigned *ArgPos) {
2822   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2823                                               N = NewType->param_type_begin(),
2824                                               E = OldType->param_type_end();
2825        O && (O != E); ++O, ++N) {
2826     if (!Context.hasSameType(O->getUnqualifiedType(),
2827                              N->getUnqualifiedType())) {
2828       if (ArgPos)
2829         *ArgPos = O - OldType->param_type_begin();
2830       return false;
2831     }
2832   }
2833   return true;
2834 }
2835 
2836 /// CheckPointerConversion - Check the pointer conversion from the
2837 /// expression From to the type ToType. This routine checks for
2838 /// ambiguous or inaccessible derived-to-base pointer
2839 /// conversions for which IsPointerConversion has already returned
2840 /// true. It returns true and produces a diagnostic if there was an
2841 /// error, or returns false otherwise.
2842 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2843                                   CastKind &Kind,
2844                                   CXXCastPath& BasePath,
2845                                   bool IgnoreBaseAccess,
2846                                   bool Diagnose) {
2847   QualType FromType = From->getType();
2848   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2849 
2850   Kind = CK_BitCast;
2851 
2852   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2853       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2854           Expr::NPCK_ZeroExpression) {
2855     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2856       DiagRuntimeBehavior(From->getExprLoc(), From,
2857                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2858                             << ToType << From->getSourceRange());
2859     else if (!isUnevaluatedContext())
2860       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2861         << ToType << From->getSourceRange();
2862   }
2863   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2864     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2865       QualType FromPointeeType = FromPtrType->getPointeeType(),
2866                ToPointeeType   = ToPtrType->getPointeeType();
2867 
2868       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2869           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2870         // We must have a derived-to-base conversion. Check an
2871         // ambiguous or inaccessible conversion.
2872         unsigned InaccessibleID = 0;
2873         unsigned AmbigiousID = 0;
2874         if (Diagnose) {
2875           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2876           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2877         }
2878         if (CheckDerivedToBaseConversion(
2879                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2880                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2881                 &BasePath, IgnoreBaseAccess))
2882           return true;
2883 
2884         // The conversion was successful.
2885         Kind = CK_DerivedToBase;
2886       }
2887 
2888       if (Diagnose && !IsCStyleOrFunctionalCast &&
2889           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2890         assert(getLangOpts().MSVCCompat &&
2891                "this should only be possible with MSVCCompat!");
2892         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2893             << From->getSourceRange();
2894       }
2895     }
2896   } else if (const ObjCObjectPointerType *ToPtrType =
2897                ToType->getAs<ObjCObjectPointerType>()) {
2898     if (const ObjCObjectPointerType *FromPtrType =
2899           FromType->getAs<ObjCObjectPointerType>()) {
2900       // Objective-C++ conversions are always okay.
2901       // FIXME: We should have a different class of conversions for the
2902       // Objective-C++ implicit conversions.
2903       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2904         return false;
2905     } else if (FromType->isBlockPointerType()) {
2906       Kind = CK_BlockPointerToObjCPointerCast;
2907     } else {
2908       Kind = CK_CPointerToObjCPointerCast;
2909     }
2910   } else if (ToType->isBlockPointerType()) {
2911     if (!FromType->isBlockPointerType())
2912       Kind = CK_AnyPointerToBlockPointerCast;
2913   }
2914 
2915   // We shouldn't fall into this case unless it's valid for other
2916   // reasons.
2917   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2918     Kind = CK_NullToPointer;
2919 
2920   return false;
2921 }
2922 
2923 /// IsMemberPointerConversion - Determines whether the conversion of the
2924 /// expression From, which has the (possibly adjusted) type FromType, can be
2925 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2926 /// If so, returns true and places the converted type (that might differ from
2927 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2928 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2929                                      QualType ToType,
2930                                      bool InOverloadResolution,
2931                                      QualType &ConvertedType) {
2932   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2933   if (!ToTypePtr)
2934     return false;
2935 
2936   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2937   if (From->isNullPointerConstant(Context,
2938                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2939                                         : Expr::NPC_ValueDependentIsNull)) {
2940     ConvertedType = ToType;
2941     return true;
2942   }
2943 
2944   // Otherwise, both types have to be member pointers.
2945   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2946   if (!FromTypePtr)
2947     return false;
2948 
2949   // A pointer to member of B can be converted to a pointer to member of D,
2950   // where D is derived from B (C++ 4.11p2).
2951   QualType FromClass(FromTypePtr->getClass(), 0);
2952   QualType ToClass(ToTypePtr->getClass(), 0);
2953 
2954   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2955       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2956     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2957                                                  ToClass.getTypePtr());
2958     return true;
2959   }
2960 
2961   return false;
2962 }
2963 
2964 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2965 /// expression From to the type ToType. This routine checks for ambiguous or
2966 /// virtual or inaccessible base-to-derived member pointer conversions
2967 /// for which IsMemberPointerConversion has already returned true. It returns
2968 /// true and produces a diagnostic if there was an error, or returns false
2969 /// otherwise.
2970 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2971                                         CastKind &Kind,
2972                                         CXXCastPath &BasePath,
2973                                         bool IgnoreBaseAccess) {
2974   QualType FromType = From->getType();
2975   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2976   if (!FromPtrType) {
2977     // This must be a null pointer to member pointer conversion
2978     assert(From->isNullPointerConstant(Context,
2979                                        Expr::NPC_ValueDependentIsNull) &&
2980            "Expr must be null pointer constant!");
2981     Kind = CK_NullToMemberPointer;
2982     return false;
2983   }
2984 
2985   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2986   assert(ToPtrType && "No member pointer cast has a target type "
2987                       "that is not a member pointer.");
2988 
2989   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2990   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2991 
2992   // FIXME: What about dependent types?
2993   assert(FromClass->isRecordType() && "Pointer into non-class.");
2994   assert(ToClass->isRecordType() && "Pointer into non-class.");
2995 
2996   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2997                      /*DetectVirtual=*/true);
2998   bool DerivationOkay =
2999       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3000   assert(DerivationOkay &&
3001          "Should not have been called if derivation isn't OK.");
3002   (void)DerivationOkay;
3003 
3004   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3005                                   getUnqualifiedType())) {
3006     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3007     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3008       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3009     return true;
3010   }
3011 
3012   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3013     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3014       << FromClass << ToClass << QualType(VBase, 0)
3015       << From->getSourceRange();
3016     return true;
3017   }
3018 
3019   if (!IgnoreBaseAccess)
3020     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3021                          Paths.front(),
3022                          diag::err_downcast_from_inaccessible_base);
3023 
3024   // Must be a base to derived member conversion.
3025   BuildBasePathArray(Paths, BasePath);
3026   Kind = CK_BaseToDerivedMemberPointer;
3027   return false;
3028 }
3029 
3030 /// Determine whether the lifetime conversion between the two given
3031 /// qualifiers sets is nontrivial.
3032 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3033                                                Qualifiers ToQuals) {
3034   // Converting anything to const __unsafe_unretained is trivial.
3035   if (ToQuals.hasConst() &&
3036       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3037     return false;
3038 
3039   return true;
3040 }
3041 
3042 /// IsQualificationConversion - Determines whether the conversion from
3043 /// an rvalue of type FromType to ToType is a qualification conversion
3044 /// (C++ 4.4).
3045 ///
3046 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3047 /// when the qualification conversion involves a change in the Objective-C
3048 /// object lifetime.
3049 bool
3050 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3051                                 bool CStyle, bool &ObjCLifetimeConversion) {
3052   FromType = Context.getCanonicalType(FromType);
3053   ToType = Context.getCanonicalType(ToType);
3054   ObjCLifetimeConversion = false;
3055 
3056   // If FromType and ToType are the same type, this is not a
3057   // qualification conversion.
3058   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3059     return false;
3060 
3061   // (C++ 4.4p4):
3062   //   A conversion can add cv-qualifiers at levels other than the first
3063   //   in multi-level pointers, subject to the following rules: [...]
3064   bool PreviousToQualsIncludeConst = true;
3065   bool UnwrappedAnyPointer = false;
3066   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3067     // Within each iteration of the loop, we check the qualifiers to
3068     // determine if this still looks like a qualification
3069     // conversion. Then, if all is well, we unwrap one more level of
3070     // pointers or pointers-to-members and do it all again
3071     // until there are no more pointers or pointers-to-members left to
3072     // unwrap.
3073     UnwrappedAnyPointer = true;
3074 
3075     Qualifiers FromQuals = FromType.getQualifiers();
3076     Qualifiers ToQuals = ToType.getQualifiers();
3077 
3078     // Ignore __unaligned qualifier if this type is void.
3079     if (ToType.getUnqualifiedType()->isVoidType())
3080       FromQuals.removeUnaligned();
3081 
3082     // Objective-C ARC:
3083     //   Check Objective-C lifetime conversions.
3084     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3085         UnwrappedAnyPointer) {
3086       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3087         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3088           ObjCLifetimeConversion = true;
3089         FromQuals.removeObjCLifetime();
3090         ToQuals.removeObjCLifetime();
3091       } else {
3092         // Qualification conversions cannot cast between different
3093         // Objective-C lifetime qualifiers.
3094         return false;
3095       }
3096     }
3097 
3098     // Allow addition/removal of GC attributes but not changing GC attributes.
3099     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3100         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3101       FromQuals.removeObjCGCAttr();
3102       ToQuals.removeObjCGCAttr();
3103     }
3104 
3105     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3106     //      2,j, and similarly for volatile.
3107     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3108       return false;
3109 
3110     //   -- if the cv 1,j and cv 2,j are different, then const is in
3111     //      every cv for 0 < k < j.
3112     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3113         && !PreviousToQualsIncludeConst)
3114       return false;
3115 
3116     // Keep track of whether all prior cv-qualifiers in the "to" type
3117     // include const.
3118     PreviousToQualsIncludeConst
3119       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3120   }
3121 
3122   // We are left with FromType and ToType being the pointee types
3123   // after unwrapping the original FromType and ToType the same number
3124   // of types. If we unwrapped any pointers, and if FromType and
3125   // ToType have the same unqualified type (since we checked
3126   // qualifiers above), then this is a qualification conversion.
3127   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3128 }
3129 
3130 /// \brief - Determine whether this is a conversion from a scalar type to an
3131 /// atomic type.
3132 ///
3133 /// If successful, updates \c SCS's second and third steps in the conversion
3134 /// sequence to finish the conversion.
3135 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3136                                 bool InOverloadResolution,
3137                                 StandardConversionSequence &SCS,
3138                                 bool CStyle) {
3139   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3140   if (!ToAtomic)
3141     return false;
3142 
3143   StandardConversionSequence InnerSCS;
3144   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3145                             InOverloadResolution, InnerSCS,
3146                             CStyle, /*AllowObjCWritebackConversion=*/false))
3147     return false;
3148 
3149   SCS.Second = InnerSCS.Second;
3150   SCS.setToType(1, InnerSCS.getToType(1));
3151   SCS.Third = InnerSCS.Third;
3152   SCS.QualificationIncludesObjCLifetime
3153     = InnerSCS.QualificationIncludesObjCLifetime;
3154   SCS.setToType(2, InnerSCS.getToType(2));
3155   return true;
3156 }
3157 
3158 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3159                                               CXXConstructorDecl *Constructor,
3160                                               QualType Type) {
3161   const FunctionProtoType *CtorType =
3162       Constructor->getType()->getAs<FunctionProtoType>();
3163   if (CtorType->getNumParams() > 0) {
3164     QualType FirstArg = CtorType->getParamType(0);
3165     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3166       return true;
3167   }
3168   return false;
3169 }
3170 
3171 static OverloadingResult
3172 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3173                                        CXXRecordDecl *To,
3174                                        UserDefinedConversionSequence &User,
3175                                        OverloadCandidateSet &CandidateSet,
3176                                        bool AllowExplicit) {
3177   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3178   for (auto *D : S.LookupConstructors(To)) {
3179     auto Info = getConstructorInfo(D);
3180     if (!Info)
3181       continue;
3182 
3183     bool Usable = !Info.Constructor->isInvalidDecl() &&
3184                   S.isInitListConstructor(Info.Constructor) &&
3185                   (AllowExplicit || !Info.Constructor->isExplicit());
3186     if (Usable) {
3187       // If the first argument is (a reference to) the target type,
3188       // suppress conversions.
3189       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190           S.Context, Info.Constructor, ToType);
3191       if (Info.ConstructorTmpl)
3192         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3193                                        /*ExplicitArgs*/ nullptr, From,
3194                                        CandidateSet, SuppressUserConversions);
3195       else
3196         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3197                                CandidateSet, SuppressUserConversions);
3198     }
3199   }
3200 
3201   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3202 
3203   OverloadCandidateSet::iterator Best;
3204   switch (auto Result =
3205             CandidateSet.BestViableFunction(S, From->getLocStart(),
3206                                             Best)) {
3207   case OR_Deleted:
3208   case OR_Success: {
3209     // Record the standard conversion we used and the conversion function.
3210     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3211     QualType ThisType = Constructor->getThisType(S.Context);
3212     // Initializer lists don't have conversions as such.
3213     User.Before.setAsIdentityConversion();
3214     User.HadMultipleCandidates = HadMultipleCandidates;
3215     User.ConversionFunction = Constructor;
3216     User.FoundConversionFunction = Best->FoundDecl;
3217     User.After.setAsIdentityConversion();
3218     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3219     User.After.setAllToTypes(ToType);
3220     return Result;
3221   }
3222 
3223   case OR_No_Viable_Function:
3224     return OR_No_Viable_Function;
3225   case OR_Ambiguous:
3226     return OR_Ambiguous;
3227   }
3228 
3229   llvm_unreachable("Invalid OverloadResult!");
3230 }
3231 
3232 /// Determines whether there is a user-defined conversion sequence
3233 /// (C++ [over.ics.user]) that converts expression From to the type
3234 /// ToType. If such a conversion exists, User will contain the
3235 /// user-defined conversion sequence that performs such a conversion
3236 /// and this routine will return true. Otherwise, this routine returns
3237 /// false and User is unspecified.
3238 ///
3239 /// \param AllowExplicit  true if the conversion should consider C++0x
3240 /// "explicit" conversion functions as well as non-explicit conversion
3241 /// functions (C++0x [class.conv.fct]p2).
3242 ///
3243 /// \param AllowObjCConversionOnExplicit true if the conversion should
3244 /// allow an extra Objective-C pointer conversion on uses of explicit
3245 /// constructors. Requires \c AllowExplicit to also be set.
3246 static OverloadingResult
3247 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3248                         UserDefinedConversionSequence &User,
3249                         OverloadCandidateSet &CandidateSet,
3250                         bool AllowExplicit,
3251                         bool AllowObjCConversionOnExplicit) {
3252   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3253   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3254 
3255   // Whether we will only visit constructors.
3256   bool ConstructorsOnly = false;
3257 
3258   // If the type we are conversion to is a class type, enumerate its
3259   // constructors.
3260   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3261     // C++ [over.match.ctor]p1:
3262     //   When objects of class type are direct-initialized (8.5), or
3263     //   copy-initialized from an expression of the same or a
3264     //   derived class type (8.5), overload resolution selects the
3265     //   constructor. [...] For copy-initialization, the candidate
3266     //   functions are all the converting constructors (12.3.1) of
3267     //   that class. The argument list is the expression-list within
3268     //   the parentheses of the initializer.
3269     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3270         (From->getType()->getAs<RecordType>() &&
3271          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3272       ConstructorsOnly = true;
3273 
3274     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3275       // We're not going to find any constructors.
3276     } else if (CXXRecordDecl *ToRecordDecl
3277                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3278 
3279       Expr **Args = &From;
3280       unsigned NumArgs = 1;
3281       bool ListInitializing = false;
3282       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3283         // But first, see if there is an init-list-constructor that will work.
3284         OverloadingResult Result = IsInitializerListConstructorConversion(
3285             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3286         if (Result != OR_No_Viable_Function)
3287           return Result;
3288         // Never mind.
3289         CandidateSet.clear(
3290             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3291 
3292         // If we're list-initializing, we pass the individual elements as
3293         // arguments, not the entire list.
3294         Args = InitList->getInits();
3295         NumArgs = InitList->getNumInits();
3296         ListInitializing = true;
3297       }
3298 
3299       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3300         auto Info = getConstructorInfo(D);
3301         if (!Info)
3302           continue;
3303 
3304         bool Usable = !Info.Constructor->isInvalidDecl();
3305         if (ListInitializing)
3306           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3307         else
3308           Usable = Usable &&
3309                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3310         if (Usable) {
3311           bool SuppressUserConversions = !ConstructorsOnly;
3312           if (SuppressUserConversions && ListInitializing) {
3313             SuppressUserConversions = false;
3314             if (NumArgs == 1) {
3315               // If the first argument is (a reference to) the target type,
3316               // suppress conversions.
3317               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3318                   S.Context, Info.Constructor, ToType);
3319             }
3320           }
3321           if (Info.ConstructorTmpl)
3322             S.AddTemplateOverloadCandidate(
3323                 Info.ConstructorTmpl, Info.FoundDecl,
3324                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3325                 CandidateSet, SuppressUserConversions);
3326           else
3327             // Allow one user-defined conversion when user specifies a
3328             // From->ToType conversion via an static cast (c-style, etc).
3329             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3330                                    llvm::makeArrayRef(Args, NumArgs),
3331                                    CandidateSet, SuppressUserConversions);
3332         }
3333       }
3334     }
3335   }
3336 
3337   // Enumerate conversion functions, if we're allowed to.
3338   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3339   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3340     // No conversion functions from incomplete types.
3341   } else if (const RecordType *FromRecordType
3342                                    = From->getType()->getAs<RecordType>()) {
3343     if (CXXRecordDecl *FromRecordDecl
3344          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3345       // Add all of the conversion functions as candidates.
3346       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3347       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3348         DeclAccessPair FoundDecl = I.getPair();
3349         NamedDecl *D = FoundDecl.getDecl();
3350         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3351         if (isa<UsingShadowDecl>(D))
3352           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3353 
3354         CXXConversionDecl *Conv;
3355         FunctionTemplateDecl *ConvTemplate;
3356         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3357           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3358         else
3359           Conv = cast<CXXConversionDecl>(D);
3360 
3361         if (AllowExplicit || !Conv->isExplicit()) {
3362           if (ConvTemplate)
3363             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3364                                              ActingContext, From, ToType,
3365                                              CandidateSet,
3366                                              AllowObjCConversionOnExplicit);
3367           else
3368             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3369                                      From, ToType, CandidateSet,
3370                                      AllowObjCConversionOnExplicit);
3371         }
3372       }
3373     }
3374   }
3375 
3376   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3377 
3378   OverloadCandidateSet::iterator Best;
3379   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3380                                                         Best)) {
3381   case OR_Success:
3382   case OR_Deleted:
3383     // Record the standard conversion we used and the conversion function.
3384     if (CXXConstructorDecl *Constructor
3385           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3386       // C++ [over.ics.user]p1:
3387       //   If the user-defined conversion is specified by a
3388       //   constructor (12.3.1), the initial standard conversion
3389       //   sequence converts the source type to the type required by
3390       //   the argument of the constructor.
3391       //
3392       QualType ThisType = Constructor->getThisType(S.Context);
3393       if (isa<InitListExpr>(From)) {
3394         // Initializer lists don't have conversions as such.
3395         User.Before.setAsIdentityConversion();
3396       } else {
3397         if (Best->Conversions[0].isEllipsis())
3398           User.EllipsisConversion = true;
3399         else {
3400           User.Before = Best->Conversions[0].Standard;
3401           User.EllipsisConversion = false;
3402         }
3403       }
3404       User.HadMultipleCandidates = HadMultipleCandidates;
3405       User.ConversionFunction = Constructor;
3406       User.FoundConversionFunction = Best->FoundDecl;
3407       User.After.setAsIdentityConversion();
3408       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3409       User.After.setAllToTypes(ToType);
3410       return Result;
3411     }
3412     if (CXXConversionDecl *Conversion
3413                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3414       // C++ [over.ics.user]p1:
3415       //
3416       //   [...] If the user-defined conversion is specified by a
3417       //   conversion function (12.3.2), the initial standard
3418       //   conversion sequence converts the source type to the
3419       //   implicit object parameter of the conversion function.
3420       User.Before = Best->Conversions[0].Standard;
3421       User.HadMultipleCandidates = HadMultipleCandidates;
3422       User.ConversionFunction = Conversion;
3423       User.FoundConversionFunction = Best->FoundDecl;
3424       User.EllipsisConversion = false;
3425 
3426       // C++ [over.ics.user]p2:
3427       //   The second standard conversion sequence converts the
3428       //   result of the user-defined conversion to the target type
3429       //   for the sequence. Since an implicit conversion sequence
3430       //   is an initialization, the special rules for
3431       //   initialization by user-defined conversion apply when
3432       //   selecting the best user-defined conversion for a
3433       //   user-defined conversion sequence (see 13.3.3 and
3434       //   13.3.3.1).
3435       User.After = Best->FinalConversion;
3436       return Result;
3437     }
3438     llvm_unreachable("Not a constructor or conversion function?");
3439 
3440   case OR_No_Viable_Function:
3441     return OR_No_Viable_Function;
3442 
3443   case OR_Ambiguous:
3444     return OR_Ambiguous;
3445   }
3446 
3447   llvm_unreachable("Invalid OverloadResult!");
3448 }
3449 
3450 bool
3451 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3452   ImplicitConversionSequence ICS;
3453   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3454                                     OverloadCandidateSet::CSK_Normal);
3455   OverloadingResult OvResult =
3456     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3457                             CandidateSet, false, false);
3458   if (OvResult == OR_Ambiguous)
3459     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3460         << From->getType() << ToType << From->getSourceRange();
3461   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3462     if (!RequireCompleteType(From->getLocStart(), ToType,
3463                              diag::err_typecheck_nonviable_condition_incomplete,
3464                              From->getType(), From->getSourceRange()))
3465       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3466           << false << From->getType() << From->getSourceRange() << ToType;
3467   } else
3468     return false;
3469   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3470   return true;
3471 }
3472 
3473 /// \brief Compare the user-defined conversion functions or constructors
3474 /// of two user-defined conversion sequences to determine whether any ordering
3475 /// is possible.
3476 static ImplicitConversionSequence::CompareKind
3477 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3478                            FunctionDecl *Function2) {
3479   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3480     return ImplicitConversionSequence::Indistinguishable;
3481 
3482   // Objective-C++:
3483   //   If both conversion functions are implicitly-declared conversions from
3484   //   a lambda closure type to a function pointer and a block pointer,
3485   //   respectively, always prefer the conversion to a function pointer,
3486   //   because the function pointer is more lightweight and is more likely
3487   //   to keep code working.
3488   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3489   if (!Conv1)
3490     return ImplicitConversionSequence::Indistinguishable;
3491 
3492   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3493   if (!Conv2)
3494     return ImplicitConversionSequence::Indistinguishable;
3495 
3496   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3497     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3498     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3499     if (Block1 != Block2)
3500       return Block1 ? ImplicitConversionSequence::Worse
3501                     : ImplicitConversionSequence::Better;
3502   }
3503 
3504   return ImplicitConversionSequence::Indistinguishable;
3505 }
3506 
3507 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3508     const ImplicitConversionSequence &ICS) {
3509   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3510          (ICS.isUserDefined() &&
3511           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3512 }
3513 
3514 /// CompareImplicitConversionSequences - Compare two implicit
3515 /// conversion sequences to determine whether one is better than the
3516 /// other or if they are indistinguishable (C++ 13.3.3.2).
3517 static ImplicitConversionSequence::CompareKind
3518 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3519                                    const ImplicitConversionSequence& ICS1,
3520                                    const ImplicitConversionSequence& ICS2)
3521 {
3522   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3523   // conversion sequences (as defined in 13.3.3.1)
3524   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3525   //      conversion sequence than a user-defined conversion sequence or
3526   //      an ellipsis conversion sequence, and
3527   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3528   //      conversion sequence than an ellipsis conversion sequence
3529   //      (13.3.3.1.3).
3530   //
3531   // C++0x [over.best.ics]p10:
3532   //   For the purpose of ranking implicit conversion sequences as
3533   //   described in 13.3.3.2, the ambiguous conversion sequence is
3534   //   treated as a user-defined sequence that is indistinguishable
3535   //   from any other user-defined conversion sequence.
3536 
3537   // String literal to 'char *' conversion has been deprecated in C++03. It has
3538   // been removed from C++11. We still accept this conversion, if it happens at
3539   // the best viable function. Otherwise, this conversion is considered worse
3540   // than ellipsis conversion. Consider this as an extension; this is not in the
3541   // standard. For example:
3542   //
3543   // int &f(...);    // #1
3544   // void f(char*);  // #2
3545   // void g() { int &r = f("foo"); }
3546   //
3547   // In C++03, we pick #2 as the best viable function.
3548   // In C++11, we pick #1 as the best viable function, because ellipsis
3549   // conversion is better than string-literal to char* conversion (since there
3550   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3551   // convert arguments, #2 would be the best viable function in C++11.
3552   // If the best viable function has this conversion, a warning will be issued
3553   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3554 
3555   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3556       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3557       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3558     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3559                ? ImplicitConversionSequence::Worse
3560                : ImplicitConversionSequence::Better;
3561 
3562   if (ICS1.getKindRank() < ICS2.getKindRank())
3563     return ImplicitConversionSequence::Better;
3564   if (ICS2.getKindRank() < ICS1.getKindRank())
3565     return ImplicitConversionSequence::Worse;
3566 
3567   // The following checks require both conversion sequences to be of
3568   // the same kind.
3569   if (ICS1.getKind() != ICS2.getKind())
3570     return ImplicitConversionSequence::Indistinguishable;
3571 
3572   ImplicitConversionSequence::CompareKind Result =
3573       ImplicitConversionSequence::Indistinguishable;
3574 
3575   // Two implicit conversion sequences of the same form are
3576   // indistinguishable conversion sequences unless one of the
3577   // following rules apply: (C++ 13.3.3.2p3):
3578 
3579   // List-initialization sequence L1 is a better conversion sequence than
3580   // list-initialization sequence L2 if:
3581   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3582   //   if not that,
3583   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3584   //   and N1 is smaller than N2.,
3585   // even if one of the other rules in this paragraph would otherwise apply.
3586   if (!ICS1.isBad()) {
3587     if (ICS1.isStdInitializerListElement() &&
3588         !ICS2.isStdInitializerListElement())
3589       return ImplicitConversionSequence::Better;
3590     if (!ICS1.isStdInitializerListElement() &&
3591         ICS2.isStdInitializerListElement())
3592       return ImplicitConversionSequence::Worse;
3593   }
3594 
3595   if (ICS1.isStandard())
3596     // Standard conversion sequence S1 is a better conversion sequence than
3597     // standard conversion sequence S2 if [...]
3598     Result = CompareStandardConversionSequences(S, Loc,
3599                                                 ICS1.Standard, ICS2.Standard);
3600   else if (ICS1.isUserDefined()) {
3601     // User-defined conversion sequence U1 is a better conversion
3602     // sequence than another user-defined conversion sequence U2 if
3603     // they contain the same user-defined conversion function or
3604     // constructor and if the second standard conversion sequence of
3605     // U1 is better than the second standard conversion sequence of
3606     // U2 (C++ 13.3.3.2p3).
3607     if (ICS1.UserDefined.ConversionFunction ==
3608           ICS2.UserDefined.ConversionFunction)
3609       Result = CompareStandardConversionSequences(S, Loc,
3610                                                   ICS1.UserDefined.After,
3611                                                   ICS2.UserDefined.After);
3612     else
3613       Result = compareConversionFunctions(S,
3614                                           ICS1.UserDefined.ConversionFunction,
3615                                           ICS2.UserDefined.ConversionFunction);
3616   }
3617 
3618   return Result;
3619 }
3620 
3621 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3622   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3623     Qualifiers Quals;
3624     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3625     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3626   }
3627 
3628   return Context.hasSameUnqualifiedType(T1, T2);
3629 }
3630 
3631 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3632 // determine if one is a proper subset of the other.
3633 static ImplicitConversionSequence::CompareKind
3634 compareStandardConversionSubsets(ASTContext &Context,
3635                                  const StandardConversionSequence& SCS1,
3636                                  const StandardConversionSequence& SCS2) {
3637   ImplicitConversionSequence::CompareKind Result
3638     = ImplicitConversionSequence::Indistinguishable;
3639 
3640   // the identity conversion sequence is considered to be a subsequence of
3641   // any non-identity conversion sequence
3642   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3643     return ImplicitConversionSequence::Better;
3644   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3645     return ImplicitConversionSequence::Worse;
3646 
3647   if (SCS1.Second != SCS2.Second) {
3648     if (SCS1.Second == ICK_Identity)
3649       Result = ImplicitConversionSequence::Better;
3650     else if (SCS2.Second == ICK_Identity)
3651       Result = ImplicitConversionSequence::Worse;
3652     else
3653       return ImplicitConversionSequence::Indistinguishable;
3654   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   if (SCS1.Third == SCS2.Third) {
3658     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3659                              : ImplicitConversionSequence::Indistinguishable;
3660   }
3661 
3662   if (SCS1.Third == ICK_Identity)
3663     return Result == ImplicitConversionSequence::Worse
3664              ? ImplicitConversionSequence::Indistinguishable
3665              : ImplicitConversionSequence::Better;
3666 
3667   if (SCS2.Third == ICK_Identity)
3668     return Result == ImplicitConversionSequence::Better
3669              ? ImplicitConversionSequence::Indistinguishable
3670              : ImplicitConversionSequence::Worse;
3671 
3672   return ImplicitConversionSequence::Indistinguishable;
3673 }
3674 
3675 /// \brief Determine whether one of the given reference bindings is better
3676 /// than the other based on what kind of bindings they are.
3677 static bool
3678 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3679                              const StandardConversionSequence &SCS2) {
3680   // C++0x [over.ics.rank]p3b4:
3681   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3682   //      implicit object parameter of a non-static member function declared
3683   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3684   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3685   //      lvalue reference to a function lvalue and S2 binds an rvalue
3686   //      reference*.
3687   //
3688   // FIXME: Rvalue references. We're going rogue with the above edits,
3689   // because the semantics in the current C++0x working paper (N3225 at the
3690   // time of this writing) break the standard definition of std::forward
3691   // and std::reference_wrapper when dealing with references to functions.
3692   // Proposed wording changes submitted to CWG for consideration.
3693   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3694       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3695     return false;
3696 
3697   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3698           SCS2.IsLvalueReference) ||
3699          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3700           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3701 }
3702 
3703 /// CompareStandardConversionSequences - Compare two standard
3704 /// conversion sequences to determine whether one is better than the
3705 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3706 static ImplicitConversionSequence::CompareKind
3707 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3708                                    const StandardConversionSequence& SCS1,
3709                                    const StandardConversionSequence& SCS2)
3710 {
3711   // Standard conversion sequence S1 is a better conversion sequence
3712   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3713 
3714   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3715   //     sequences in the canonical form defined by 13.3.3.1.1,
3716   //     excluding any Lvalue Transformation; the identity conversion
3717   //     sequence is considered to be a subsequence of any
3718   //     non-identity conversion sequence) or, if not that,
3719   if (ImplicitConversionSequence::CompareKind CK
3720         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3721     return CK;
3722 
3723   //  -- the rank of S1 is better than the rank of S2 (by the rules
3724   //     defined below), or, if not that,
3725   ImplicitConversionRank Rank1 = SCS1.getRank();
3726   ImplicitConversionRank Rank2 = SCS2.getRank();
3727   if (Rank1 < Rank2)
3728     return ImplicitConversionSequence::Better;
3729   else if (Rank2 < Rank1)
3730     return ImplicitConversionSequence::Worse;
3731 
3732   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3733   // are indistinguishable unless one of the following rules
3734   // applies:
3735 
3736   //   A conversion that is not a conversion of a pointer, or
3737   //   pointer to member, to bool is better than another conversion
3738   //   that is such a conversion.
3739   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3740     return SCS2.isPointerConversionToBool()
3741              ? ImplicitConversionSequence::Better
3742              : ImplicitConversionSequence::Worse;
3743 
3744   // C++ [over.ics.rank]p4b2:
3745   //
3746   //   If class B is derived directly or indirectly from class A,
3747   //   conversion of B* to A* is better than conversion of B* to
3748   //   void*, and conversion of A* to void* is better than conversion
3749   //   of B* to void*.
3750   bool SCS1ConvertsToVoid
3751     = SCS1.isPointerConversionToVoidPointer(S.Context);
3752   bool SCS2ConvertsToVoid
3753     = SCS2.isPointerConversionToVoidPointer(S.Context);
3754   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3755     // Exactly one of the conversion sequences is a conversion to
3756     // a void pointer; it's the worse conversion.
3757     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3758                               : ImplicitConversionSequence::Worse;
3759   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3760     // Neither conversion sequence converts to a void pointer; compare
3761     // their derived-to-base conversions.
3762     if (ImplicitConversionSequence::CompareKind DerivedCK
3763           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3764       return DerivedCK;
3765   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3766              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3767     // Both conversion sequences are conversions to void
3768     // pointers. Compare the source types to determine if there's an
3769     // inheritance relationship in their sources.
3770     QualType FromType1 = SCS1.getFromType();
3771     QualType FromType2 = SCS2.getFromType();
3772 
3773     // Adjust the types we're converting from via the array-to-pointer
3774     // conversion, if we need to.
3775     if (SCS1.First == ICK_Array_To_Pointer)
3776       FromType1 = S.Context.getArrayDecayedType(FromType1);
3777     if (SCS2.First == ICK_Array_To_Pointer)
3778       FromType2 = S.Context.getArrayDecayedType(FromType2);
3779 
3780     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3781     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3782 
3783     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3784       return ImplicitConversionSequence::Better;
3785     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3786       return ImplicitConversionSequence::Worse;
3787 
3788     // Objective-C++: If one interface is more specific than the
3789     // other, it is the better one.
3790     const ObjCObjectPointerType* FromObjCPtr1
3791       = FromType1->getAs<ObjCObjectPointerType>();
3792     const ObjCObjectPointerType* FromObjCPtr2
3793       = FromType2->getAs<ObjCObjectPointerType>();
3794     if (FromObjCPtr1 && FromObjCPtr2) {
3795       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3796                                                           FromObjCPtr2);
3797       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3798                                                            FromObjCPtr1);
3799       if (AssignLeft != AssignRight) {
3800         return AssignLeft? ImplicitConversionSequence::Better
3801                          : ImplicitConversionSequence::Worse;
3802       }
3803     }
3804   }
3805 
3806   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3807   // bullet 3).
3808   if (ImplicitConversionSequence::CompareKind QualCK
3809         = CompareQualificationConversions(S, SCS1, SCS2))
3810     return QualCK;
3811 
3812   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3813     // Check for a better reference binding based on the kind of bindings.
3814     if (isBetterReferenceBindingKind(SCS1, SCS2))
3815       return ImplicitConversionSequence::Better;
3816     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3817       return ImplicitConversionSequence::Worse;
3818 
3819     // C++ [over.ics.rank]p3b4:
3820     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3821     //      which the references refer are the same type except for
3822     //      top-level cv-qualifiers, and the type to which the reference
3823     //      initialized by S2 refers is more cv-qualified than the type
3824     //      to which the reference initialized by S1 refers.
3825     QualType T1 = SCS1.getToType(2);
3826     QualType T2 = SCS2.getToType(2);
3827     T1 = S.Context.getCanonicalType(T1);
3828     T2 = S.Context.getCanonicalType(T2);
3829     Qualifiers T1Quals, T2Quals;
3830     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3831     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3832     if (UnqualT1 == UnqualT2) {
3833       // Objective-C++ ARC: If the references refer to objects with different
3834       // lifetimes, prefer bindings that don't change lifetime.
3835       if (SCS1.ObjCLifetimeConversionBinding !=
3836                                           SCS2.ObjCLifetimeConversionBinding) {
3837         return SCS1.ObjCLifetimeConversionBinding
3838                                            ? ImplicitConversionSequence::Worse
3839                                            : ImplicitConversionSequence::Better;
3840       }
3841 
3842       // If the type is an array type, promote the element qualifiers to the
3843       // type for comparison.
3844       if (isa<ArrayType>(T1) && T1Quals)
3845         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3846       if (isa<ArrayType>(T2) && T2Quals)
3847         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3848       if (T2.isMoreQualifiedThan(T1))
3849         return ImplicitConversionSequence::Better;
3850       else if (T1.isMoreQualifiedThan(T2))
3851         return ImplicitConversionSequence::Worse;
3852     }
3853   }
3854 
3855   // In Microsoft mode, prefer an integral conversion to a
3856   // floating-to-integral conversion if the integral conversion
3857   // is between types of the same size.
3858   // For example:
3859   // void f(float);
3860   // void f(int);
3861   // int main {
3862   //    long a;
3863   //    f(a);
3864   // }
3865   // Here, MSVC will call f(int) instead of generating a compile error
3866   // as clang will do in standard mode.
3867   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3868       SCS2.Second == ICK_Floating_Integral &&
3869       S.Context.getTypeSize(SCS1.getFromType()) ==
3870           S.Context.getTypeSize(SCS1.getToType(2)))
3871     return ImplicitConversionSequence::Better;
3872 
3873   return ImplicitConversionSequence::Indistinguishable;
3874 }
3875 
3876 /// CompareQualificationConversions - Compares two standard conversion
3877 /// sequences to determine whether they can be ranked based on their
3878 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3879 static ImplicitConversionSequence::CompareKind
3880 CompareQualificationConversions(Sema &S,
3881                                 const StandardConversionSequence& SCS1,
3882                                 const StandardConversionSequence& SCS2) {
3883   // C++ 13.3.3.2p3:
3884   //  -- S1 and S2 differ only in their qualification conversion and
3885   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3886   //     cv-qualification signature of type T1 is a proper subset of
3887   //     the cv-qualification signature of type T2, and S1 is not the
3888   //     deprecated string literal array-to-pointer conversion (4.2).
3889   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3890       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3891     return ImplicitConversionSequence::Indistinguishable;
3892 
3893   // FIXME: the example in the standard doesn't use a qualification
3894   // conversion (!)
3895   QualType T1 = SCS1.getToType(2);
3896   QualType T2 = SCS2.getToType(2);
3897   T1 = S.Context.getCanonicalType(T1);
3898   T2 = S.Context.getCanonicalType(T2);
3899   Qualifiers T1Quals, T2Quals;
3900   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3901   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3902 
3903   // If the types are the same, we won't learn anything by unwrapped
3904   // them.
3905   if (UnqualT1 == UnqualT2)
3906     return ImplicitConversionSequence::Indistinguishable;
3907 
3908   // If the type is an array type, promote the element qualifiers to the type
3909   // for comparison.
3910   if (isa<ArrayType>(T1) && T1Quals)
3911     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3912   if (isa<ArrayType>(T2) && T2Quals)
3913     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3914 
3915   ImplicitConversionSequence::CompareKind Result
3916     = ImplicitConversionSequence::Indistinguishable;
3917 
3918   // Objective-C++ ARC:
3919   //   Prefer qualification conversions not involving a change in lifetime
3920   //   to qualification conversions that do not change lifetime.
3921   if (SCS1.QualificationIncludesObjCLifetime !=
3922                                       SCS2.QualificationIncludesObjCLifetime) {
3923     Result = SCS1.QualificationIncludesObjCLifetime
3924                ? ImplicitConversionSequence::Worse
3925                : ImplicitConversionSequence::Better;
3926   }
3927 
3928   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3929     // Within each iteration of the loop, we check the qualifiers to
3930     // determine if this still looks like a qualification
3931     // conversion. Then, if all is well, we unwrap one more level of
3932     // pointers or pointers-to-members and do it all again
3933     // until there are no more pointers or pointers-to-members left
3934     // to unwrap. This essentially mimics what
3935     // IsQualificationConversion does, but here we're checking for a
3936     // strict subset of qualifiers.
3937     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3938       // The qualifiers are the same, so this doesn't tell us anything
3939       // about how the sequences rank.
3940       ;
3941     else if (T2.isMoreQualifiedThan(T1)) {
3942       // T1 has fewer qualifiers, so it could be the better sequence.
3943       if (Result == ImplicitConversionSequence::Worse)
3944         // Neither has qualifiers that are a subset of the other's
3945         // qualifiers.
3946         return ImplicitConversionSequence::Indistinguishable;
3947 
3948       Result = ImplicitConversionSequence::Better;
3949     } else if (T1.isMoreQualifiedThan(T2)) {
3950       // T2 has fewer qualifiers, so it could be the better sequence.
3951       if (Result == ImplicitConversionSequence::Better)
3952         // Neither has qualifiers that are a subset of the other's
3953         // qualifiers.
3954         return ImplicitConversionSequence::Indistinguishable;
3955 
3956       Result = ImplicitConversionSequence::Worse;
3957     } else {
3958       // Qualifiers are disjoint.
3959       return ImplicitConversionSequence::Indistinguishable;
3960     }
3961 
3962     // If the types after this point are equivalent, we're done.
3963     if (S.Context.hasSameUnqualifiedType(T1, T2))
3964       break;
3965   }
3966 
3967   // Check that the winning standard conversion sequence isn't using
3968   // the deprecated string literal array to pointer conversion.
3969   switch (Result) {
3970   case ImplicitConversionSequence::Better:
3971     if (SCS1.DeprecatedStringLiteralToCharPtr)
3972       Result = ImplicitConversionSequence::Indistinguishable;
3973     break;
3974 
3975   case ImplicitConversionSequence::Indistinguishable:
3976     break;
3977 
3978   case ImplicitConversionSequence::Worse:
3979     if (SCS2.DeprecatedStringLiteralToCharPtr)
3980       Result = ImplicitConversionSequence::Indistinguishable;
3981     break;
3982   }
3983 
3984   return Result;
3985 }
3986 
3987 /// CompareDerivedToBaseConversions - Compares two standard conversion
3988 /// sequences to determine whether they can be ranked based on their
3989 /// various kinds of derived-to-base conversions (C++
3990 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3991 /// conversions between Objective-C interface types.
3992 static ImplicitConversionSequence::CompareKind
3993 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3994                                 const StandardConversionSequence& SCS1,
3995                                 const StandardConversionSequence& SCS2) {
3996   QualType FromType1 = SCS1.getFromType();
3997   QualType ToType1 = SCS1.getToType(1);
3998   QualType FromType2 = SCS2.getFromType();
3999   QualType ToType2 = SCS2.getToType(1);
4000 
4001   // Adjust the types we're converting from via the array-to-pointer
4002   // conversion, if we need to.
4003   if (SCS1.First == ICK_Array_To_Pointer)
4004     FromType1 = S.Context.getArrayDecayedType(FromType1);
4005   if (SCS2.First == ICK_Array_To_Pointer)
4006     FromType2 = S.Context.getArrayDecayedType(FromType2);
4007 
4008   // Canonicalize all of the types.
4009   FromType1 = S.Context.getCanonicalType(FromType1);
4010   ToType1 = S.Context.getCanonicalType(ToType1);
4011   FromType2 = S.Context.getCanonicalType(FromType2);
4012   ToType2 = S.Context.getCanonicalType(ToType2);
4013 
4014   // C++ [over.ics.rank]p4b3:
4015   //
4016   //   If class B is derived directly or indirectly from class A and
4017   //   class C is derived directly or indirectly from B,
4018   //
4019   // Compare based on pointer conversions.
4020   if (SCS1.Second == ICK_Pointer_Conversion &&
4021       SCS2.Second == ICK_Pointer_Conversion &&
4022       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4023       FromType1->isPointerType() && FromType2->isPointerType() &&
4024       ToType1->isPointerType() && ToType2->isPointerType()) {
4025     QualType FromPointee1
4026       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4027     QualType ToPointee1
4028       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4029     QualType FromPointee2
4030       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031     QualType ToPointee2
4032       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4033 
4034     //   -- conversion of C* to B* is better than conversion of C* to A*,
4035     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4036       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4037         return ImplicitConversionSequence::Better;
4038       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4039         return ImplicitConversionSequence::Worse;
4040     }
4041 
4042     //   -- conversion of B* to A* is better than conversion of C* to A*,
4043     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4044       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4045         return ImplicitConversionSequence::Better;
4046       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4047         return ImplicitConversionSequence::Worse;
4048     }
4049   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4050              SCS2.Second == ICK_Pointer_Conversion) {
4051     const ObjCObjectPointerType *FromPtr1
4052       = FromType1->getAs<ObjCObjectPointerType>();
4053     const ObjCObjectPointerType *FromPtr2
4054       = FromType2->getAs<ObjCObjectPointerType>();
4055     const ObjCObjectPointerType *ToPtr1
4056       = ToType1->getAs<ObjCObjectPointerType>();
4057     const ObjCObjectPointerType *ToPtr2
4058       = ToType2->getAs<ObjCObjectPointerType>();
4059 
4060     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4061       // Apply the same conversion ranking rules for Objective-C pointer types
4062       // that we do for C++ pointers to class types. However, we employ the
4063       // Objective-C pseudo-subtyping relationship used for assignment of
4064       // Objective-C pointer types.
4065       bool FromAssignLeft
4066         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4067       bool FromAssignRight
4068         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4069       bool ToAssignLeft
4070         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4071       bool ToAssignRight
4072         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4073 
4074       // A conversion to an a non-id object pointer type or qualified 'id'
4075       // type is better than a conversion to 'id'.
4076       if (ToPtr1->isObjCIdType() &&
4077           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4078         return ImplicitConversionSequence::Worse;
4079       if (ToPtr2->isObjCIdType() &&
4080           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4081         return ImplicitConversionSequence::Better;
4082 
4083       // A conversion to a non-id object pointer type is better than a
4084       // conversion to a qualified 'id' type
4085       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4086         return ImplicitConversionSequence::Worse;
4087       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4088         return ImplicitConversionSequence::Better;
4089 
4090       // A conversion to an a non-Class object pointer type or qualified 'Class'
4091       // type is better than a conversion to 'Class'.
4092       if (ToPtr1->isObjCClassType() &&
4093           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4094         return ImplicitConversionSequence::Worse;
4095       if (ToPtr2->isObjCClassType() &&
4096           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4097         return ImplicitConversionSequence::Better;
4098 
4099       // A conversion to a non-Class object pointer type is better than a
4100       // conversion to a qualified 'Class' type.
4101       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4102         return ImplicitConversionSequence::Worse;
4103       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4104         return ImplicitConversionSequence::Better;
4105 
4106       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4107       if (S.Context.hasSameType(FromType1, FromType2) &&
4108           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4109           (ToAssignLeft != ToAssignRight)) {
4110         if (FromPtr1->isSpecialized()) {
4111           // "conversion of B<A> * to B * is better than conversion of B * to
4112           // C *.
4113           bool IsFirstSame =
4114               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4115           bool IsSecondSame =
4116               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4117           if (IsFirstSame) {
4118             if (!IsSecondSame)
4119               return ImplicitConversionSequence::Better;
4120           } else if (IsSecondSame)
4121             return ImplicitConversionSequence::Worse;
4122         }
4123         return ToAssignLeft? ImplicitConversionSequence::Worse
4124                            : ImplicitConversionSequence::Better;
4125       }
4126 
4127       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4128       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4129           (FromAssignLeft != FromAssignRight))
4130         return FromAssignLeft? ImplicitConversionSequence::Better
4131         : ImplicitConversionSequence::Worse;
4132     }
4133   }
4134 
4135   // Ranking of member-pointer types.
4136   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4137       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4138       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4139     const MemberPointerType * FromMemPointer1 =
4140                                         FromType1->getAs<MemberPointerType>();
4141     const MemberPointerType * ToMemPointer1 =
4142                                           ToType1->getAs<MemberPointerType>();
4143     const MemberPointerType * FromMemPointer2 =
4144                                           FromType2->getAs<MemberPointerType>();
4145     const MemberPointerType * ToMemPointer2 =
4146                                           ToType2->getAs<MemberPointerType>();
4147     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4148     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4149     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4150     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4151     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4152     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4153     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4154     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4155     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4156     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4157       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4158         return ImplicitConversionSequence::Worse;
4159       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4160         return ImplicitConversionSequence::Better;
4161     }
4162     // conversion of B::* to C::* is better than conversion of A::* to C::*
4163     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4164       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4165         return ImplicitConversionSequence::Better;
4166       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4167         return ImplicitConversionSequence::Worse;
4168     }
4169   }
4170 
4171   if (SCS1.Second == ICK_Derived_To_Base) {
4172     //   -- conversion of C to B is better than conversion of C to A,
4173     //   -- binding of an expression of type C to a reference of type
4174     //      B& is better than binding an expression of type C to a
4175     //      reference of type A&,
4176     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4177         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4178       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4179         return ImplicitConversionSequence::Better;
4180       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4181         return ImplicitConversionSequence::Worse;
4182     }
4183 
4184     //   -- conversion of B to A is better than conversion of C to A.
4185     //   -- binding of an expression of type B to a reference of type
4186     //      A& is better than binding an expression of type C to a
4187     //      reference of type A&,
4188     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4189         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4190       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4191         return ImplicitConversionSequence::Better;
4192       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4193         return ImplicitConversionSequence::Worse;
4194     }
4195   }
4196 
4197   return ImplicitConversionSequence::Indistinguishable;
4198 }
4199 
4200 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4201 /// C++ class.
4202 static bool isTypeValid(QualType T) {
4203   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4204     return !Record->isInvalidDecl();
4205 
4206   return true;
4207 }
4208 
4209 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4210 /// determine whether they are reference-related,
4211 /// reference-compatible, reference-compatible with added
4212 /// qualification, or incompatible, for use in C++ initialization by
4213 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4214 /// type, and the first type (T1) is the pointee type of the reference
4215 /// type being initialized.
4216 Sema::ReferenceCompareResult
4217 Sema::CompareReferenceRelationship(SourceLocation Loc,
4218                                    QualType OrigT1, QualType OrigT2,
4219                                    bool &DerivedToBase,
4220                                    bool &ObjCConversion,
4221                                    bool &ObjCLifetimeConversion) {
4222   assert(!OrigT1->isReferenceType() &&
4223     "T1 must be the pointee type of the reference type");
4224   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4225 
4226   QualType T1 = Context.getCanonicalType(OrigT1);
4227   QualType T2 = Context.getCanonicalType(OrigT2);
4228   Qualifiers T1Quals, T2Quals;
4229   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4230   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4231 
4232   // C++ [dcl.init.ref]p4:
4233   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4234   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4235   //   T1 is a base class of T2.
4236   DerivedToBase = false;
4237   ObjCConversion = false;
4238   ObjCLifetimeConversion = false;
4239   QualType ConvertedT2;
4240   if (UnqualT1 == UnqualT2) {
4241     // Nothing to do.
4242   } else if (isCompleteType(Loc, OrigT2) &&
4243              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4244              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4245     DerivedToBase = true;
4246   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4247            UnqualT2->isObjCObjectOrInterfaceType() &&
4248            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4249     ObjCConversion = true;
4250   else if (UnqualT2->isFunctionType() &&
4251            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4252     // C++1z [dcl.init.ref]p4:
4253     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4254     //   function" and T1 is "function"
4255     //
4256     // We extend this to also apply to 'noreturn', so allow any function
4257     // conversion between function types.
4258     return Ref_Compatible;
4259   else
4260     return Ref_Incompatible;
4261 
4262   // At this point, we know that T1 and T2 are reference-related (at
4263   // least).
4264 
4265   // If the type is an array type, promote the element qualifiers to the type
4266   // for comparison.
4267   if (isa<ArrayType>(T1) && T1Quals)
4268     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4269   if (isa<ArrayType>(T2) && T2Quals)
4270     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4271 
4272   // C++ [dcl.init.ref]p4:
4273   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4274   //   reference-related to T2 and cv1 is the same cv-qualification
4275   //   as, or greater cv-qualification than, cv2. For purposes of
4276   //   overload resolution, cases for which cv1 is greater
4277   //   cv-qualification than cv2 are identified as
4278   //   reference-compatible with added qualification (see 13.3.3.2).
4279   //
4280   // Note that we also require equivalence of Objective-C GC and address-space
4281   // qualifiers when performing these computations, so that e.g., an int in
4282   // address space 1 is not reference-compatible with an int in address
4283   // space 2.
4284   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4285       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4286     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4287       ObjCLifetimeConversion = true;
4288 
4289     T1Quals.removeObjCLifetime();
4290     T2Quals.removeObjCLifetime();
4291   }
4292 
4293   // MS compiler ignores __unaligned qualifier for references; do the same.
4294   T1Quals.removeUnaligned();
4295   T2Quals.removeUnaligned();
4296 
4297   if (T1Quals.compatiblyIncludes(T2Quals))
4298     return Ref_Compatible;
4299   else
4300     return Ref_Related;
4301 }
4302 
4303 /// \brief Look for a user-defined conversion to a value reference-compatible
4304 ///        with DeclType. Return true if something definite is found.
4305 static bool
4306 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4307                          QualType DeclType, SourceLocation DeclLoc,
4308                          Expr *Init, QualType T2, bool AllowRvalues,
4309                          bool AllowExplicit) {
4310   assert(T2->isRecordType() && "Can only find conversions of record types.");
4311   CXXRecordDecl *T2RecordDecl
4312     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4313 
4314   OverloadCandidateSet CandidateSet(
4315       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4316   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4317   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4318     NamedDecl *D = *I;
4319     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4320     if (isa<UsingShadowDecl>(D))
4321       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4322 
4323     FunctionTemplateDecl *ConvTemplate
4324       = dyn_cast<FunctionTemplateDecl>(D);
4325     CXXConversionDecl *Conv;
4326     if (ConvTemplate)
4327       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4328     else
4329       Conv = cast<CXXConversionDecl>(D);
4330 
4331     // If this is an explicit conversion, and we're not allowed to consider
4332     // explicit conversions, skip it.
4333     if (!AllowExplicit && Conv->isExplicit())
4334       continue;
4335 
4336     if (AllowRvalues) {
4337       bool DerivedToBase = false;
4338       bool ObjCConversion = false;
4339       bool ObjCLifetimeConversion = false;
4340 
4341       // If we are initializing an rvalue reference, don't permit conversion
4342       // functions that return lvalues.
4343       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4344         const ReferenceType *RefType
4345           = Conv->getConversionType()->getAs<LValueReferenceType>();
4346         if (RefType && !RefType->getPointeeType()->isFunctionType())
4347           continue;
4348       }
4349 
4350       if (!ConvTemplate &&
4351           S.CompareReferenceRelationship(
4352             DeclLoc,
4353             Conv->getConversionType().getNonReferenceType()
4354               .getUnqualifiedType(),
4355             DeclType.getNonReferenceType().getUnqualifiedType(),
4356             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4357           Sema::Ref_Incompatible)
4358         continue;
4359     } else {
4360       // If the conversion function doesn't return a reference type,
4361       // it can't be considered for this conversion. An rvalue reference
4362       // is only acceptable if its referencee is a function type.
4363 
4364       const ReferenceType *RefType =
4365         Conv->getConversionType()->getAs<ReferenceType>();
4366       if (!RefType ||
4367           (!RefType->isLValueReferenceType() &&
4368            !RefType->getPointeeType()->isFunctionType()))
4369         continue;
4370     }
4371 
4372     if (ConvTemplate)
4373       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4374                                        Init, DeclType, CandidateSet,
4375                                        /*AllowObjCConversionOnExplicit=*/false);
4376     else
4377       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4378                                DeclType, CandidateSet,
4379                                /*AllowObjCConversionOnExplicit=*/false);
4380   }
4381 
4382   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4383 
4384   OverloadCandidateSet::iterator Best;
4385   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4386   case OR_Success:
4387     // C++ [over.ics.ref]p1:
4388     //
4389     //   [...] If the parameter binds directly to the result of
4390     //   applying a conversion function to the argument
4391     //   expression, the implicit conversion sequence is a
4392     //   user-defined conversion sequence (13.3.3.1.2), with the
4393     //   second standard conversion sequence either an identity
4394     //   conversion or, if the conversion function returns an
4395     //   entity of a type that is a derived class of the parameter
4396     //   type, a derived-to-base Conversion.
4397     if (!Best->FinalConversion.DirectBinding)
4398       return false;
4399 
4400     ICS.setUserDefined();
4401     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4402     ICS.UserDefined.After = Best->FinalConversion;
4403     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4404     ICS.UserDefined.ConversionFunction = Best->Function;
4405     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4406     ICS.UserDefined.EllipsisConversion = false;
4407     assert(ICS.UserDefined.After.ReferenceBinding &&
4408            ICS.UserDefined.After.DirectBinding &&
4409            "Expected a direct reference binding!");
4410     return true;
4411 
4412   case OR_Ambiguous:
4413     ICS.setAmbiguous();
4414     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4415          Cand != CandidateSet.end(); ++Cand)
4416       if (Cand->Viable)
4417         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4418     return true;
4419 
4420   case OR_No_Viable_Function:
4421   case OR_Deleted:
4422     // There was no suitable conversion, or we found a deleted
4423     // conversion; continue with other checks.
4424     return false;
4425   }
4426 
4427   llvm_unreachable("Invalid OverloadResult!");
4428 }
4429 
4430 /// \brief Compute an implicit conversion sequence for reference
4431 /// initialization.
4432 static ImplicitConversionSequence
4433 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4434                  SourceLocation DeclLoc,
4435                  bool SuppressUserConversions,
4436                  bool AllowExplicit) {
4437   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4438 
4439   // Most paths end in a failed conversion.
4440   ImplicitConversionSequence ICS;
4441   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4442 
4443   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4444   QualType T2 = Init->getType();
4445 
4446   // If the initializer is the address of an overloaded function, try
4447   // to resolve the overloaded function. If all goes well, T2 is the
4448   // type of the resulting function.
4449   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4450     DeclAccessPair Found;
4451     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4452                                                                 false, Found))
4453       T2 = Fn->getType();
4454   }
4455 
4456   // Compute some basic properties of the types and the initializer.
4457   bool isRValRef = DeclType->isRValueReferenceType();
4458   bool DerivedToBase = false;
4459   bool ObjCConversion = false;
4460   bool ObjCLifetimeConversion = false;
4461   Expr::Classification InitCategory = Init->Classify(S.Context);
4462   Sema::ReferenceCompareResult RefRelationship
4463     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4464                                      ObjCConversion, ObjCLifetimeConversion);
4465 
4466 
4467   // C++0x [dcl.init.ref]p5:
4468   //   A reference to type "cv1 T1" is initialized by an expression
4469   //   of type "cv2 T2" as follows:
4470 
4471   //     -- If reference is an lvalue reference and the initializer expression
4472   if (!isRValRef) {
4473     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4474     //        reference-compatible with "cv2 T2," or
4475     //
4476     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4477     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4478       // C++ [over.ics.ref]p1:
4479       //   When a parameter of reference type binds directly (8.5.3)
4480       //   to an argument expression, the implicit conversion sequence
4481       //   is the identity conversion, unless the argument expression
4482       //   has a type that is a derived class of the parameter type,
4483       //   in which case the implicit conversion sequence is a
4484       //   derived-to-base Conversion (13.3.3.1).
4485       ICS.setStandard();
4486       ICS.Standard.First = ICK_Identity;
4487       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4488                          : ObjCConversion? ICK_Compatible_Conversion
4489                          : ICK_Identity;
4490       ICS.Standard.Third = ICK_Identity;
4491       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4492       ICS.Standard.setToType(0, T2);
4493       ICS.Standard.setToType(1, T1);
4494       ICS.Standard.setToType(2, T1);
4495       ICS.Standard.ReferenceBinding = true;
4496       ICS.Standard.DirectBinding = true;
4497       ICS.Standard.IsLvalueReference = !isRValRef;
4498       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4499       ICS.Standard.BindsToRvalue = false;
4500       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4501       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4502       ICS.Standard.CopyConstructor = nullptr;
4503       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4504 
4505       // Nothing more to do: the inaccessibility/ambiguity check for
4506       // derived-to-base conversions is suppressed when we're
4507       // computing the implicit conversion sequence (C++
4508       // [over.best.ics]p2).
4509       return ICS;
4510     }
4511 
4512     //       -- has a class type (i.e., T2 is a class type), where T1 is
4513     //          not reference-related to T2, and can be implicitly
4514     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4515     //          is reference-compatible with "cv3 T3" 92) (this
4516     //          conversion is selected by enumerating the applicable
4517     //          conversion functions (13.3.1.6) and choosing the best
4518     //          one through overload resolution (13.3)),
4519     if (!SuppressUserConversions && T2->isRecordType() &&
4520         S.isCompleteType(DeclLoc, T2) &&
4521         RefRelationship == Sema::Ref_Incompatible) {
4522       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4523                                    Init, T2, /*AllowRvalues=*/false,
4524                                    AllowExplicit))
4525         return ICS;
4526     }
4527   }
4528 
4529   //     -- Otherwise, the reference shall be an lvalue reference to a
4530   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4531   //        shall be an rvalue reference.
4532   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4533     return ICS;
4534 
4535   //       -- If the initializer expression
4536   //
4537   //            -- is an xvalue, class prvalue, array prvalue or function
4538   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4539   if (RefRelationship == Sema::Ref_Compatible &&
4540       (InitCategory.isXValue() ||
4541        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4542        (InitCategory.isLValue() && T2->isFunctionType()))) {
4543     ICS.setStandard();
4544     ICS.Standard.First = ICK_Identity;
4545     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4546                       : ObjCConversion? ICK_Compatible_Conversion
4547                       : ICK_Identity;
4548     ICS.Standard.Third = ICK_Identity;
4549     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4550     ICS.Standard.setToType(0, T2);
4551     ICS.Standard.setToType(1, T1);
4552     ICS.Standard.setToType(2, T1);
4553     ICS.Standard.ReferenceBinding = true;
4554     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4555     // binding unless we're binding to a class prvalue.
4556     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4557     // allow the use of rvalue references in C++98/03 for the benefit of
4558     // standard library implementors; therefore, we need the xvalue check here.
4559     ICS.Standard.DirectBinding =
4560       S.getLangOpts().CPlusPlus11 ||
4561       !(InitCategory.isPRValue() || T2->isRecordType());
4562     ICS.Standard.IsLvalueReference = !isRValRef;
4563     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4564     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4565     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4566     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4567     ICS.Standard.CopyConstructor = nullptr;
4568     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4569     return ICS;
4570   }
4571 
4572   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4573   //               reference-related to T2, and can be implicitly converted to
4574   //               an xvalue, class prvalue, or function lvalue of type
4575   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4576   //               "cv3 T3",
4577   //
4578   //          then the reference is bound to the value of the initializer
4579   //          expression in the first case and to the result of the conversion
4580   //          in the second case (or, in either case, to an appropriate base
4581   //          class subobject).
4582   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4583       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4584       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4585                                Init, T2, /*AllowRvalues=*/true,
4586                                AllowExplicit)) {
4587     // In the second case, if the reference is an rvalue reference
4588     // and the second standard conversion sequence of the
4589     // user-defined conversion sequence includes an lvalue-to-rvalue
4590     // conversion, the program is ill-formed.
4591     if (ICS.isUserDefined() && isRValRef &&
4592         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4593       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4594 
4595     return ICS;
4596   }
4597 
4598   // A temporary of function type cannot be created; don't even try.
4599   if (T1->isFunctionType())
4600     return ICS;
4601 
4602   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4603   //          initialized from the initializer expression using the
4604   //          rules for a non-reference copy initialization (8.5). The
4605   //          reference is then bound to the temporary. If T1 is
4606   //          reference-related to T2, cv1 must be the same
4607   //          cv-qualification as, or greater cv-qualification than,
4608   //          cv2; otherwise, the program is ill-formed.
4609   if (RefRelationship == Sema::Ref_Related) {
4610     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4611     // we would be reference-compatible or reference-compatible with
4612     // added qualification. But that wasn't the case, so the reference
4613     // initialization fails.
4614     //
4615     // Note that we only want to check address spaces and cvr-qualifiers here.
4616     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4617     Qualifiers T1Quals = T1.getQualifiers();
4618     Qualifiers T2Quals = T2.getQualifiers();
4619     T1Quals.removeObjCGCAttr();
4620     T1Quals.removeObjCLifetime();
4621     T2Quals.removeObjCGCAttr();
4622     T2Quals.removeObjCLifetime();
4623     // MS compiler ignores __unaligned qualifier for references; do the same.
4624     T1Quals.removeUnaligned();
4625     T2Quals.removeUnaligned();
4626     if (!T1Quals.compatiblyIncludes(T2Quals))
4627       return ICS;
4628   }
4629 
4630   // If at least one of the types is a class type, the types are not
4631   // related, and we aren't allowed any user conversions, the
4632   // reference binding fails. This case is important for breaking
4633   // recursion, since TryImplicitConversion below will attempt to
4634   // create a temporary through the use of a copy constructor.
4635   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4636       (T1->isRecordType() || T2->isRecordType()))
4637     return ICS;
4638 
4639   // If T1 is reference-related to T2 and the reference is an rvalue
4640   // reference, the initializer expression shall not be an lvalue.
4641   if (RefRelationship >= Sema::Ref_Related &&
4642       isRValRef && Init->Classify(S.Context).isLValue())
4643     return ICS;
4644 
4645   // C++ [over.ics.ref]p2:
4646   //   When a parameter of reference type is not bound directly to
4647   //   an argument expression, the conversion sequence is the one
4648   //   required to convert the argument expression to the
4649   //   underlying type of the reference according to
4650   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4651   //   to copy-initializing a temporary of the underlying type with
4652   //   the argument expression. Any difference in top-level
4653   //   cv-qualification is subsumed by the initialization itself
4654   //   and does not constitute a conversion.
4655   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4656                               /*AllowExplicit=*/false,
4657                               /*InOverloadResolution=*/false,
4658                               /*CStyle=*/false,
4659                               /*AllowObjCWritebackConversion=*/false,
4660                               /*AllowObjCConversionOnExplicit=*/false);
4661 
4662   // Of course, that's still a reference binding.
4663   if (ICS.isStandard()) {
4664     ICS.Standard.ReferenceBinding = true;
4665     ICS.Standard.IsLvalueReference = !isRValRef;
4666     ICS.Standard.BindsToFunctionLvalue = false;
4667     ICS.Standard.BindsToRvalue = true;
4668     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4669     ICS.Standard.ObjCLifetimeConversionBinding = false;
4670   } else if (ICS.isUserDefined()) {
4671     const ReferenceType *LValRefType =
4672         ICS.UserDefined.ConversionFunction->getReturnType()
4673             ->getAs<LValueReferenceType>();
4674 
4675     // C++ [over.ics.ref]p3:
4676     //   Except for an implicit object parameter, for which see 13.3.1, a
4677     //   standard conversion sequence cannot be formed if it requires [...]
4678     //   binding an rvalue reference to an lvalue other than a function
4679     //   lvalue.
4680     // Note that the function case is not possible here.
4681     if (DeclType->isRValueReferenceType() && LValRefType) {
4682       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4683       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4684       // reference to an rvalue!
4685       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4686       return ICS;
4687     }
4688 
4689     ICS.UserDefined.After.ReferenceBinding = true;
4690     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4691     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4692     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4693     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4694     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4695   }
4696 
4697   return ICS;
4698 }
4699 
4700 static ImplicitConversionSequence
4701 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4702                       bool SuppressUserConversions,
4703                       bool InOverloadResolution,
4704                       bool AllowObjCWritebackConversion,
4705                       bool AllowExplicit = false);
4706 
4707 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4708 /// initializer list From.
4709 static ImplicitConversionSequence
4710 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4711                   bool SuppressUserConversions,
4712                   bool InOverloadResolution,
4713                   bool AllowObjCWritebackConversion) {
4714   // C++11 [over.ics.list]p1:
4715   //   When an argument is an initializer list, it is not an expression and
4716   //   special rules apply for converting it to a parameter type.
4717 
4718   ImplicitConversionSequence Result;
4719   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4720 
4721   // We need a complete type for what follows. Incomplete types can never be
4722   // initialized from init lists.
4723   if (!S.isCompleteType(From->getLocStart(), ToType))
4724     return Result;
4725 
4726   // Per DR1467:
4727   //   If the parameter type is a class X and the initializer list has a single
4728   //   element of type cv U, where U is X or a class derived from X, the
4729   //   implicit conversion sequence is the one required to convert the element
4730   //   to the parameter type.
4731   //
4732   //   Otherwise, if the parameter type is a character array [... ]
4733   //   and the initializer list has a single element that is an
4734   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4735   //   implicit conversion sequence is the identity conversion.
4736   if (From->getNumInits() == 1) {
4737     if (ToType->isRecordType()) {
4738       QualType InitType = From->getInit(0)->getType();
4739       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4740           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4741         return TryCopyInitialization(S, From->getInit(0), ToType,
4742                                      SuppressUserConversions,
4743                                      InOverloadResolution,
4744                                      AllowObjCWritebackConversion);
4745     }
4746     // FIXME: Check the other conditions here: array of character type,
4747     // initializer is a string literal.
4748     if (ToType->isArrayType()) {
4749       InitializedEntity Entity =
4750         InitializedEntity::InitializeParameter(S.Context, ToType,
4751                                                /*Consumed=*/false);
4752       if (S.CanPerformCopyInitialization(Entity, From)) {
4753         Result.setStandard();
4754         Result.Standard.setAsIdentityConversion();
4755         Result.Standard.setFromType(ToType);
4756         Result.Standard.setAllToTypes(ToType);
4757         return Result;
4758       }
4759     }
4760   }
4761 
4762   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4763   // C++11 [over.ics.list]p2:
4764   //   If the parameter type is std::initializer_list<X> or "array of X" and
4765   //   all the elements can be implicitly converted to X, the implicit
4766   //   conversion sequence is the worst conversion necessary to convert an
4767   //   element of the list to X.
4768   //
4769   // C++14 [over.ics.list]p3:
4770   //   Otherwise, if the parameter type is "array of N X", if the initializer
4771   //   list has exactly N elements or if it has fewer than N elements and X is
4772   //   default-constructible, and if all the elements of the initializer list
4773   //   can be implicitly converted to X, the implicit conversion sequence is
4774   //   the worst conversion necessary to convert an element of the list to X.
4775   //
4776   // FIXME: We're missing a lot of these checks.
4777   bool toStdInitializerList = false;
4778   QualType X;
4779   if (ToType->isArrayType())
4780     X = S.Context.getAsArrayType(ToType)->getElementType();
4781   else
4782     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4783   if (!X.isNull()) {
4784     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4785       Expr *Init = From->getInit(i);
4786       ImplicitConversionSequence ICS =
4787           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4788                                 InOverloadResolution,
4789                                 AllowObjCWritebackConversion);
4790       // If a single element isn't convertible, fail.
4791       if (ICS.isBad()) {
4792         Result = ICS;
4793         break;
4794       }
4795       // Otherwise, look for the worst conversion.
4796       if (Result.isBad() ||
4797           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4798                                              Result) ==
4799               ImplicitConversionSequence::Worse)
4800         Result = ICS;
4801     }
4802 
4803     // For an empty list, we won't have computed any conversion sequence.
4804     // Introduce the identity conversion sequence.
4805     if (From->getNumInits() == 0) {
4806       Result.setStandard();
4807       Result.Standard.setAsIdentityConversion();
4808       Result.Standard.setFromType(ToType);
4809       Result.Standard.setAllToTypes(ToType);
4810     }
4811 
4812     Result.setStdInitializerListElement(toStdInitializerList);
4813     return Result;
4814   }
4815 
4816   // C++14 [over.ics.list]p4:
4817   // C++11 [over.ics.list]p3:
4818   //   Otherwise, if the parameter is a non-aggregate class X and overload
4819   //   resolution chooses a single best constructor [...] the implicit
4820   //   conversion sequence is a user-defined conversion sequence. If multiple
4821   //   constructors are viable but none is better than the others, the
4822   //   implicit conversion sequence is a user-defined conversion sequence.
4823   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4824     // This function can deal with initializer lists.
4825     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4826                                     /*AllowExplicit=*/false,
4827                                     InOverloadResolution, /*CStyle=*/false,
4828                                     AllowObjCWritebackConversion,
4829                                     /*AllowObjCConversionOnExplicit=*/false);
4830   }
4831 
4832   // C++14 [over.ics.list]p5:
4833   // C++11 [over.ics.list]p4:
4834   //   Otherwise, if the parameter has an aggregate type which can be
4835   //   initialized from the initializer list [...] the implicit conversion
4836   //   sequence is a user-defined conversion sequence.
4837   if (ToType->isAggregateType()) {
4838     // Type is an aggregate, argument is an init list. At this point it comes
4839     // down to checking whether the initialization works.
4840     // FIXME: Find out whether this parameter is consumed or not.
4841     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4842     // need to call into the initialization code here; overload resolution
4843     // should not be doing that.
4844     InitializedEntity Entity =
4845         InitializedEntity::InitializeParameter(S.Context, ToType,
4846                                                /*Consumed=*/false);
4847     if (S.CanPerformCopyInitialization(Entity, From)) {
4848       Result.setUserDefined();
4849       Result.UserDefined.Before.setAsIdentityConversion();
4850       // Initializer lists don't have a type.
4851       Result.UserDefined.Before.setFromType(QualType());
4852       Result.UserDefined.Before.setAllToTypes(QualType());
4853 
4854       Result.UserDefined.After.setAsIdentityConversion();
4855       Result.UserDefined.After.setFromType(ToType);
4856       Result.UserDefined.After.setAllToTypes(ToType);
4857       Result.UserDefined.ConversionFunction = nullptr;
4858     }
4859     return Result;
4860   }
4861 
4862   // C++14 [over.ics.list]p6:
4863   // C++11 [over.ics.list]p5:
4864   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4865   if (ToType->isReferenceType()) {
4866     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4867     // mention initializer lists in any way. So we go by what list-
4868     // initialization would do and try to extrapolate from that.
4869 
4870     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4871 
4872     // If the initializer list has a single element that is reference-related
4873     // to the parameter type, we initialize the reference from that.
4874     if (From->getNumInits() == 1) {
4875       Expr *Init = From->getInit(0);
4876 
4877       QualType T2 = Init->getType();
4878 
4879       // If the initializer is the address of an overloaded function, try
4880       // to resolve the overloaded function. If all goes well, T2 is the
4881       // type of the resulting function.
4882       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4883         DeclAccessPair Found;
4884         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4885                                    Init, ToType, false, Found))
4886           T2 = Fn->getType();
4887       }
4888 
4889       // Compute some basic properties of the types and the initializer.
4890       bool dummy1 = false;
4891       bool dummy2 = false;
4892       bool dummy3 = false;
4893       Sema::ReferenceCompareResult RefRelationship
4894         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4895                                          dummy2, dummy3);
4896 
4897       if (RefRelationship >= Sema::Ref_Related) {
4898         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4899                                 SuppressUserConversions,
4900                                 /*AllowExplicit=*/false);
4901       }
4902     }
4903 
4904     // Otherwise, we bind the reference to a temporary created from the
4905     // initializer list.
4906     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4907                                InOverloadResolution,
4908                                AllowObjCWritebackConversion);
4909     if (Result.isFailure())
4910       return Result;
4911     assert(!Result.isEllipsis() &&
4912            "Sub-initialization cannot result in ellipsis conversion.");
4913 
4914     // Can we even bind to a temporary?
4915     if (ToType->isRValueReferenceType() ||
4916         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4917       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4918                                             Result.UserDefined.After;
4919       SCS.ReferenceBinding = true;
4920       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4921       SCS.BindsToRvalue = true;
4922       SCS.BindsToFunctionLvalue = false;
4923       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4924       SCS.ObjCLifetimeConversionBinding = false;
4925     } else
4926       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4927                     From, ToType);
4928     return Result;
4929   }
4930 
4931   // C++14 [over.ics.list]p7:
4932   // C++11 [over.ics.list]p6:
4933   //   Otherwise, if the parameter type is not a class:
4934   if (!ToType->isRecordType()) {
4935     //    - if the initializer list has one element that is not itself an
4936     //      initializer list, the implicit conversion sequence is the one
4937     //      required to convert the element to the parameter type.
4938     unsigned NumInits = From->getNumInits();
4939     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4940       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4941                                      SuppressUserConversions,
4942                                      InOverloadResolution,
4943                                      AllowObjCWritebackConversion);
4944     //    - if the initializer list has no elements, the implicit conversion
4945     //      sequence is the identity conversion.
4946     else if (NumInits == 0) {
4947       Result.setStandard();
4948       Result.Standard.setAsIdentityConversion();
4949       Result.Standard.setFromType(ToType);
4950       Result.Standard.setAllToTypes(ToType);
4951     }
4952     return Result;
4953   }
4954 
4955   // C++14 [over.ics.list]p8:
4956   // C++11 [over.ics.list]p7:
4957   //   In all cases other than those enumerated above, no conversion is possible
4958   return Result;
4959 }
4960 
4961 /// TryCopyInitialization - Try to copy-initialize a value of type
4962 /// ToType from the expression From. Return the implicit conversion
4963 /// sequence required to pass this argument, which may be a bad
4964 /// conversion sequence (meaning that the argument cannot be passed to
4965 /// a parameter of this type). If @p SuppressUserConversions, then we
4966 /// do not permit any user-defined conversion sequences.
4967 static ImplicitConversionSequence
4968 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4969                       bool SuppressUserConversions,
4970                       bool InOverloadResolution,
4971                       bool AllowObjCWritebackConversion,
4972                       bool AllowExplicit) {
4973   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4974     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4975                              InOverloadResolution,AllowObjCWritebackConversion);
4976 
4977   if (ToType->isReferenceType())
4978     return TryReferenceInit(S, From, ToType,
4979                             /*FIXME:*/From->getLocStart(),
4980                             SuppressUserConversions,
4981                             AllowExplicit);
4982 
4983   return TryImplicitConversion(S, From, ToType,
4984                                SuppressUserConversions,
4985                                /*AllowExplicit=*/false,
4986                                InOverloadResolution,
4987                                /*CStyle=*/false,
4988                                AllowObjCWritebackConversion,
4989                                /*AllowObjCConversionOnExplicit=*/false);
4990 }
4991 
4992 static bool TryCopyInitialization(const CanQualType FromQTy,
4993                                   const CanQualType ToQTy,
4994                                   Sema &S,
4995                                   SourceLocation Loc,
4996                                   ExprValueKind FromVK) {
4997   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4998   ImplicitConversionSequence ICS =
4999     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5000 
5001   return !ICS.isBad();
5002 }
5003 
5004 /// TryObjectArgumentInitialization - Try to initialize the object
5005 /// parameter of the given member function (@c Method) from the
5006 /// expression @p From.
5007 static ImplicitConversionSequence
5008 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5009                                 Expr::Classification FromClassification,
5010                                 CXXMethodDecl *Method,
5011                                 CXXRecordDecl *ActingContext) {
5012   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5013   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5014   //                 const volatile object.
5015   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5016     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5017   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5018 
5019   // Set up the conversion sequence as a "bad" conversion, to allow us
5020   // to exit early.
5021   ImplicitConversionSequence ICS;
5022 
5023   // We need to have an object of class type.
5024   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5025     FromType = PT->getPointeeType();
5026 
5027     // When we had a pointer, it's implicitly dereferenced, so we
5028     // better have an lvalue.
5029     assert(FromClassification.isLValue());
5030   }
5031 
5032   assert(FromType->isRecordType());
5033 
5034   // C++0x [over.match.funcs]p4:
5035   //   For non-static member functions, the type of the implicit object
5036   //   parameter is
5037   //
5038   //     - "lvalue reference to cv X" for functions declared without a
5039   //        ref-qualifier or with the & ref-qualifier
5040   //     - "rvalue reference to cv X" for functions declared with the &&
5041   //        ref-qualifier
5042   //
5043   // where X is the class of which the function is a member and cv is the
5044   // cv-qualification on the member function declaration.
5045   //
5046   // However, when finding an implicit conversion sequence for the argument, we
5047   // are not allowed to perform user-defined conversions
5048   // (C++ [over.match.funcs]p5). We perform a simplified version of
5049   // reference binding here, that allows class rvalues to bind to
5050   // non-constant references.
5051 
5052   // First check the qualifiers.
5053   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5054   if (ImplicitParamType.getCVRQualifiers()
5055                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5056       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5057     ICS.setBad(BadConversionSequence::bad_qualifiers,
5058                FromType, ImplicitParamType);
5059     return ICS;
5060   }
5061 
5062   // Check that we have either the same type or a derived type. It
5063   // affects the conversion rank.
5064   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5065   ImplicitConversionKind SecondKind;
5066   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5067     SecondKind = ICK_Identity;
5068   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5069     SecondKind = ICK_Derived_To_Base;
5070   else {
5071     ICS.setBad(BadConversionSequence::unrelated_class,
5072                FromType, ImplicitParamType);
5073     return ICS;
5074   }
5075 
5076   // Check the ref-qualifier.
5077   switch (Method->getRefQualifier()) {
5078   case RQ_None:
5079     // Do nothing; we don't care about lvalueness or rvalueness.
5080     break;
5081 
5082   case RQ_LValue:
5083     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5084       // non-const lvalue reference cannot bind to an rvalue
5085       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5086                  ImplicitParamType);
5087       return ICS;
5088     }
5089     break;
5090 
5091   case RQ_RValue:
5092     if (!FromClassification.isRValue()) {
5093       // rvalue reference cannot bind to an lvalue
5094       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5095                  ImplicitParamType);
5096       return ICS;
5097     }
5098     break;
5099   }
5100 
5101   // Success. Mark this as a reference binding.
5102   ICS.setStandard();
5103   ICS.Standard.setAsIdentityConversion();
5104   ICS.Standard.Second = SecondKind;
5105   ICS.Standard.setFromType(FromType);
5106   ICS.Standard.setAllToTypes(ImplicitParamType);
5107   ICS.Standard.ReferenceBinding = true;
5108   ICS.Standard.DirectBinding = true;
5109   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5110   ICS.Standard.BindsToFunctionLvalue = false;
5111   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5112   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5113     = (Method->getRefQualifier() == RQ_None);
5114   return ICS;
5115 }
5116 
5117 /// PerformObjectArgumentInitialization - Perform initialization of
5118 /// the implicit object parameter for the given Method with the given
5119 /// expression.
5120 ExprResult
5121 Sema::PerformObjectArgumentInitialization(Expr *From,
5122                                           NestedNameSpecifier *Qualifier,
5123                                           NamedDecl *FoundDecl,
5124                                           CXXMethodDecl *Method) {
5125   QualType FromRecordType, DestType;
5126   QualType ImplicitParamRecordType  =
5127     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5128 
5129   Expr::Classification FromClassification;
5130   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5131     FromRecordType = PT->getPointeeType();
5132     DestType = Method->getThisType(Context);
5133     FromClassification = Expr::Classification::makeSimpleLValue();
5134   } else {
5135     FromRecordType = From->getType();
5136     DestType = ImplicitParamRecordType;
5137     FromClassification = From->Classify(Context);
5138   }
5139 
5140   // Note that we always use the true parent context when performing
5141   // the actual argument initialization.
5142   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5143       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5144       Method->getParent());
5145   if (ICS.isBad()) {
5146     switch (ICS.Bad.Kind) {
5147     case BadConversionSequence::bad_qualifiers: {
5148       Qualifiers FromQs = FromRecordType.getQualifiers();
5149       Qualifiers ToQs = DestType.getQualifiers();
5150       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5151       if (CVR) {
5152         Diag(From->getLocStart(),
5153              diag::err_member_function_call_bad_cvr)
5154           << Method->getDeclName() << FromRecordType << (CVR - 1)
5155           << From->getSourceRange();
5156         Diag(Method->getLocation(), diag::note_previous_decl)
5157           << Method->getDeclName();
5158         return ExprError();
5159       }
5160       break;
5161     }
5162 
5163     case BadConversionSequence::lvalue_ref_to_rvalue:
5164     case BadConversionSequence::rvalue_ref_to_lvalue: {
5165       bool IsRValueQualified =
5166         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5167       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5168         << Method->getDeclName() << FromClassification.isRValue()
5169         << IsRValueQualified;
5170       Diag(Method->getLocation(), diag::note_previous_decl)
5171         << Method->getDeclName();
5172       return ExprError();
5173     }
5174 
5175     case BadConversionSequence::no_conversion:
5176     case BadConversionSequence::unrelated_class:
5177       break;
5178     }
5179 
5180     return Diag(From->getLocStart(),
5181                 diag::err_member_function_call_bad_type)
5182        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5183   }
5184 
5185   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5186     ExprResult FromRes =
5187       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5188     if (FromRes.isInvalid())
5189       return ExprError();
5190     From = FromRes.get();
5191   }
5192 
5193   if (!Context.hasSameType(From->getType(), DestType))
5194     From = ImpCastExprToType(From, DestType, CK_NoOp,
5195                              From->getValueKind()).get();
5196   return From;
5197 }
5198 
5199 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5200 /// expression From to bool (C++0x [conv]p3).
5201 static ImplicitConversionSequence
5202 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5203   return TryImplicitConversion(S, From, S.Context.BoolTy,
5204                                /*SuppressUserConversions=*/false,
5205                                /*AllowExplicit=*/true,
5206                                /*InOverloadResolution=*/false,
5207                                /*CStyle=*/false,
5208                                /*AllowObjCWritebackConversion=*/false,
5209                                /*AllowObjCConversionOnExplicit=*/false);
5210 }
5211 
5212 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5213 /// of the expression From to bool (C++0x [conv]p3).
5214 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5215   if (checkPlaceholderForOverload(*this, From))
5216     return ExprError();
5217 
5218   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5219   if (!ICS.isBad())
5220     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5221 
5222   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5223     return Diag(From->getLocStart(),
5224                 diag::err_typecheck_bool_condition)
5225                   << From->getType() << From->getSourceRange();
5226   return ExprError();
5227 }
5228 
5229 /// Check that the specified conversion is permitted in a converted constant
5230 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5231 /// is acceptable.
5232 static bool CheckConvertedConstantConversions(Sema &S,
5233                                               StandardConversionSequence &SCS) {
5234   // Since we know that the target type is an integral or unscoped enumeration
5235   // type, most conversion kinds are impossible. All possible First and Third
5236   // conversions are fine.
5237   switch (SCS.Second) {
5238   case ICK_Identity:
5239   case ICK_Function_Conversion:
5240   case ICK_Integral_Promotion:
5241   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5242   case ICK_Zero_Queue_Conversion:
5243     return true;
5244 
5245   case ICK_Boolean_Conversion:
5246     // Conversion from an integral or unscoped enumeration type to bool is
5247     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5248     // conversion, so we allow it in a converted constant expression.
5249     //
5250     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5251     // a lot of popular code. We should at least add a warning for this
5252     // (non-conforming) extension.
5253     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5254            SCS.getToType(2)->isBooleanType();
5255 
5256   case ICK_Pointer_Conversion:
5257   case ICK_Pointer_Member:
5258     // C++1z: null pointer conversions and null member pointer conversions are
5259     // only permitted if the source type is std::nullptr_t.
5260     return SCS.getFromType()->isNullPtrType();
5261 
5262   case ICK_Floating_Promotion:
5263   case ICK_Complex_Promotion:
5264   case ICK_Floating_Conversion:
5265   case ICK_Complex_Conversion:
5266   case ICK_Floating_Integral:
5267   case ICK_Compatible_Conversion:
5268   case ICK_Derived_To_Base:
5269   case ICK_Vector_Conversion:
5270   case ICK_Vector_Splat:
5271   case ICK_Complex_Real:
5272   case ICK_Block_Pointer_Conversion:
5273   case ICK_TransparentUnionConversion:
5274   case ICK_Writeback_Conversion:
5275   case ICK_Zero_Event_Conversion:
5276   case ICK_C_Only_Conversion:
5277   case ICK_Incompatible_Pointer_Conversion:
5278     return false;
5279 
5280   case ICK_Lvalue_To_Rvalue:
5281   case ICK_Array_To_Pointer:
5282   case ICK_Function_To_Pointer:
5283     llvm_unreachable("found a first conversion kind in Second");
5284 
5285   case ICK_Qualification:
5286     llvm_unreachable("found a third conversion kind in Second");
5287 
5288   case ICK_Num_Conversion_Kinds:
5289     break;
5290   }
5291 
5292   llvm_unreachable("unknown conversion kind");
5293 }
5294 
5295 /// CheckConvertedConstantExpression - Check that the expression From is a
5296 /// converted constant expression of type T, perform the conversion and produce
5297 /// the converted expression, per C++11 [expr.const]p3.
5298 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5299                                                    QualType T, APValue &Value,
5300                                                    Sema::CCEKind CCE,
5301                                                    bool RequireInt) {
5302   assert(S.getLangOpts().CPlusPlus11 &&
5303          "converted constant expression outside C++11");
5304 
5305   if (checkPlaceholderForOverload(S, From))
5306     return ExprError();
5307 
5308   // C++1z [expr.const]p3:
5309   //  A converted constant expression of type T is an expression,
5310   //  implicitly converted to type T, where the converted
5311   //  expression is a constant expression and the implicit conversion
5312   //  sequence contains only [... list of conversions ...].
5313   // C++1z [stmt.if]p2:
5314   //  If the if statement is of the form if constexpr, the value of the
5315   //  condition shall be a contextually converted constant expression of type
5316   //  bool.
5317   ImplicitConversionSequence ICS =
5318       CCE == Sema::CCEK_ConstexprIf
5319           ? TryContextuallyConvertToBool(S, From)
5320           : TryCopyInitialization(S, From, T,
5321                                   /*SuppressUserConversions=*/false,
5322                                   /*InOverloadResolution=*/false,
5323                                   /*AllowObjcWritebackConversion=*/false,
5324                                   /*AllowExplicit=*/false);
5325   StandardConversionSequence *SCS = nullptr;
5326   switch (ICS.getKind()) {
5327   case ImplicitConversionSequence::StandardConversion:
5328     SCS = &ICS.Standard;
5329     break;
5330   case ImplicitConversionSequence::UserDefinedConversion:
5331     // We are converting to a non-class type, so the Before sequence
5332     // must be trivial.
5333     SCS = &ICS.UserDefined.After;
5334     break;
5335   case ImplicitConversionSequence::AmbiguousConversion:
5336   case ImplicitConversionSequence::BadConversion:
5337     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5338       return S.Diag(From->getLocStart(),
5339                     diag::err_typecheck_converted_constant_expression)
5340                 << From->getType() << From->getSourceRange() << T;
5341     return ExprError();
5342 
5343   case ImplicitConversionSequence::EllipsisConversion:
5344     llvm_unreachable("ellipsis conversion in converted constant expression");
5345   }
5346 
5347   // Check that we would only use permitted conversions.
5348   if (!CheckConvertedConstantConversions(S, *SCS)) {
5349     return S.Diag(From->getLocStart(),
5350                   diag::err_typecheck_converted_constant_expression_disallowed)
5351              << From->getType() << From->getSourceRange() << T;
5352   }
5353   // [...] and where the reference binding (if any) binds directly.
5354   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5355     return S.Diag(From->getLocStart(),
5356                   diag::err_typecheck_converted_constant_expression_indirect)
5357              << From->getType() << From->getSourceRange() << T;
5358   }
5359 
5360   ExprResult Result =
5361       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5362   if (Result.isInvalid())
5363     return Result;
5364 
5365   // Check for a narrowing implicit conversion.
5366   APValue PreNarrowingValue;
5367   QualType PreNarrowingType;
5368   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5369                                 PreNarrowingType)) {
5370   case NK_Dependent_Narrowing:
5371     // Implicit conversion to a narrower type, but the expression is
5372     // value-dependent so we can't tell whether it's actually narrowing.
5373   case NK_Variable_Narrowing:
5374     // Implicit conversion to a narrower type, and the value is not a constant
5375     // expression. We'll diagnose this in a moment.
5376   case NK_Not_Narrowing:
5377     break;
5378 
5379   case NK_Constant_Narrowing:
5380     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5381       << CCE << /*Constant*/1
5382       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5383     break;
5384 
5385   case NK_Type_Narrowing:
5386     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5387       << CCE << /*Constant*/0 << From->getType() << T;
5388     break;
5389   }
5390 
5391   if (Result.get()->isValueDependent()) {
5392     Value = APValue();
5393     return Result;
5394   }
5395 
5396   // Check the expression is a constant expression.
5397   SmallVector<PartialDiagnosticAt, 8> Notes;
5398   Expr::EvalResult Eval;
5399   Eval.Diag = &Notes;
5400 
5401   if ((T->isReferenceType()
5402            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5403            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5404       (RequireInt && !Eval.Val.isInt())) {
5405     // The expression can't be folded, so we can't keep it at this position in
5406     // the AST.
5407     Result = ExprError();
5408   } else {
5409     Value = Eval.Val;
5410 
5411     if (Notes.empty()) {
5412       // It's a constant expression.
5413       return Result;
5414     }
5415   }
5416 
5417   // It's not a constant expression. Produce an appropriate diagnostic.
5418   if (Notes.size() == 1 &&
5419       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5420     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5421   else {
5422     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5423       << CCE << From->getSourceRange();
5424     for (unsigned I = 0; I < Notes.size(); ++I)
5425       S.Diag(Notes[I].first, Notes[I].second);
5426   }
5427   return ExprError();
5428 }
5429 
5430 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5431                                                   APValue &Value, CCEKind CCE) {
5432   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5433 }
5434 
5435 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5436                                                   llvm::APSInt &Value,
5437                                                   CCEKind CCE) {
5438   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5439 
5440   APValue V;
5441   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5442   if (!R.isInvalid() && !R.get()->isValueDependent())
5443     Value = V.getInt();
5444   return R;
5445 }
5446 
5447 
5448 /// dropPointerConversions - If the given standard conversion sequence
5449 /// involves any pointer conversions, remove them.  This may change
5450 /// the result type of the conversion sequence.
5451 static void dropPointerConversion(StandardConversionSequence &SCS) {
5452   if (SCS.Second == ICK_Pointer_Conversion) {
5453     SCS.Second = ICK_Identity;
5454     SCS.Third = ICK_Identity;
5455     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5456   }
5457 }
5458 
5459 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5460 /// convert the expression From to an Objective-C pointer type.
5461 static ImplicitConversionSequence
5462 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5463   // Do an implicit conversion to 'id'.
5464   QualType Ty = S.Context.getObjCIdType();
5465   ImplicitConversionSequence ICS
5466     = TryImplicitConversion(S, From, Ty,
5467                             // FIXME: Are these flags correct?
5468                             /*SuppressUserConversions=*/false,
5469                             /*AllowExplicit=*/true,
5470                             /*InOverloadResolution=*/false,
5471                             /*CStyle=*/false,
5472                             /*AllowObjCWritebackConversion=*/false,
5473                             /*AllowObjCConversionOnExplicit=*/true);
5474 
5475   // Strip off any final conversions to 'id'.
5476   switch (ICS.getKind()) {
5477   case ImplicitConversionSequence::BadConversion:
5478   case ImplicitConversionSequence::AmbiguousConversion:
5479   case ImplicitConversionSequence::EllipsisConversion:
5480     break;
5481 
5482   case ImplicitConversionSequence::UserDefinedConversion:
5483     dropPointerConversion(ICS.UserDefined.After);
5484     break;
5485 
5486   case ImplicitConversionSequence::StandardConversion:
5487     dropPointerConversion(ICS.Standard);
5488     break;
5489   }
5490 
5491   return ICS;
5492 }
5493 
5494 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5495 /// conversion of the expression From to an Objective-C pointer type.
5496 /// Returns a valid but null ExprResult if no conversion sequence exists.
5497 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5498   if (checkPlaceholderForOverload(*this, From))
5499     return ExprError();
5500 
5501   QualType Ty = Context.getObjCIdType();
5502   ImplicitConversionSequence ICS =
5503     TryContextuallyConvertToObjCPointer(*this, From);
5504   if (!ICS.isBad())
5505     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5506   return ExprResult();
5507 }
5508 
5509 /// Determine whether the provided type is an integral type, or an enumeration
5510 /// type of a permitted flavor.
5511 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5512   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5513                                  : T->isIntegralOrUnscopedEnumerationType();
5514 }
5515 
5516 static ExprResult
5517 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5518                             Sema::ContextualImplicitConverter &Converter,
5519                             QualType T, UnresolvedSetImpl &ViableConversions) {
5520 
5521   if (Converter.Suppress)
5522     return ExprError();
5523 
5524   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5525   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5526     CXXConversionDecl *Conv =
5527         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5528     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5529     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5530   }
5531   return From;
5532 }
5533 
5534 static bool
5535 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5536                            Sema::ContextualImplicitConverter &Converter,
5537                            QualType T, bool HadMultipleCandidates,
5538                            UnresolvedSetImpl &ExplicitConversions) {
5539   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5540     DeclAccessPair Found = ExplicitConversions[0];
5541     CXXConversionDecl *Conversion =
5542         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5543 
5544     // The user probably meant to invoke the given explicit
5545     // conversion; use it.
5546     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5547     std::string TypeStr;
5548     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5549 
5550     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5551         << FixItHint::CreateInsertion(From->getLocStart(),
5552                                       "static_cast<" + TypeStr + ">(")
5553         << FixItHint::CreateInsertion(
5554                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5555     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5556 
5557     // If we aren't in a SFINAE context, build a call to the
5558     // explicit conversion function.
5559     if (SemaRef.isSFINAEContext())
5560       return true;
5561 
5562     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5563     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5564                                                        HadMultipleCandidates);
5565     if (Result.isInvalid())
5566       return true;
5567     // Record usage of conversion in an implicit cast.
5568     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5569                                     CK_UserDefinedConversion, Result.get(),
5570                                     nullptr, Result.get()->getValueKind());
5571   }
5572   return false;
5573 }
5574 
5575 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5576                              Sema::ContextualImplicitConverter &Converter,
5577                              QualType T, bool HadMultipleCandidates,
5578                              DeclAccessPair &Found) {
5579   CXXConversionDecl *Conversion =
5580       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5581   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5582 
5583   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5584   if (!Converter.SuppressConversion) {
5585     if (SemaRef.isSFINAEContext())
5586       return true;
5587 
5588     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5589         << From->getSourceRange();
5590   }
5591 
5592   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5593                                                      HadMultipleCandidates);
5594   if (Result.isInvalid())
5595     return true;
5596   // Record usage of conversion in an implicit cast.
5597   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5598                                   CK_UserDefinedConversion, Result.get(),
5599                                   nullptr, Result.get()->getValueKind());
5600   return false;
5601 }
5602 
5603 static ExprResult finishContextualImplicitConversion(
5604     Sema &SemaRef, SourceLocation Loc, Expr *From,
5605     Sema::ContextualImplicitConverter &Converter) {
5606   if (!Converter.match(From->getType()) && !Converter.Suppress)
5607     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5608         << From->getSourceRange();
5609 
5610   return SemaRef.DefaultLvalueConversion(From);
5611 }
5612 
5613 static void
5614 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5615                                   UnresolvedSetImpl &ViableConversions,
5616                                   OverloadCandidateSet &CandidateSet) {
5617   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5618     DeclAccessPair FoundDecl = ViableConversions[I];
5619     NamedDecl *D = FoundDecl.getDecl();
5620     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5621     if (isa<UsingShadowDecl>(D))
5622       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5623 
5624     CXXConversionDecl *Conv;
5625     FunctionTemplateDecl *ConvTemplate;
5626     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5627       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5628     else
5629       Conv = cast<CXXConversionDecl>(D);
5630 
5631     if (ConvTemplate)
5632       SemaRef.AddTemplateConversionCandidate(
5633         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5634         /*AllowObjCConversionOnExplicit=*/false);
5635     else
5636       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5637                                      ToType, CandidateSet,
5638                                      /*AllowObjCConversionOnExplicit=*/false);
5639   }
5640 }
5641 
5642 /// \brief Attempt to convert the given expression to a type which is accepted
5643 /// by the given converter.
5644 ///
5645 /// This routine will attempt to convert an expression of class type to a
5646 /// type accepted by the specified converter. In C++11 and before, the class
5647 /// must have a single non-explicit conversion function converting to a matching
5648 /// type. In C++1y, there can be multiple such conversion functions, but only
5649 /// one target type.
5650 ///
5651 /// \param Loc The source location of the construct that requires the
5652 /// conversion.
5653 ///
5654 /// \param From The expression we're converting from.
5655 ///
5656 /// \param Converter Used to control and diagnose the conversion process.
5657 ///
5658 /// \returns The expression, converted to an integral or enumeration type if
5659 /// successful.
5660 ExprResult Sema::PerformContextualImplicitConversion(
5661     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5662   // We can't perform any more checking for type-dependent expressions.
5663   if (From->isTypeDependent())
5664     return From;
5665 
5666   // Process placeholders immediately.
5667   if (From->hasPlaceholderType()) {
5668     ExprResult result = CheckPlaceholderExpr(From);
5669     if (result.isInvalid())
5670       return result;
5671     From = result.get();
5672   }
5673 
5674   // If the expression already has a matching type, we're golden.
5675   QualType T = From->getType();
5676   if (Converter.match(T))
5677     return DefaultLvalueConversion(From);
5678 
5679   // FIXME: Check for missing '()' if T is a function type?
5680 
5681   // We can only perform contextual implicit conversions on objects of class
5682   // type.
5683   const RecordType *RecordTy = T->getAs<RecordType>();
5684   if (!RecordTy || !getLangOpts().CPlusPlus) {
5685     if (!Converter.Suppress)
5686       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5687     return From;
5688   }
5689 
5690   // We must have a complete class type.
5691   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5692     ContextualImplicitConverter &Converter;
5693     Expr *From;
5694 
5695     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5696         : Converter(Converter), From(From) {}
5697 
5698     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5699       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5700     }
5701   } IncompleteDiagnoser(Converter, From);
5702 
5703   if (Converter.Suppress ? !isCompleteType(Loc, T)
5704                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5705     return From;
5706 
5707   // Look for a conversion to an integral or enumeration type.
5708   UnresolvedSet<4>
5709       ViableConversions; // These are *potentially* viable in C++1y.
5710   UnresolvedSet<4> ExplicitConversions;
5711   const auto &Conversions =
5712       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5713 
5714   bool HadMultipleCandidates =
5715       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5716 
5717   // To check that there is only one target type, in C++1y:
5718   QualType ToType;
5719   bool HasUniqueTargetType = true;
5720 
5721   // Collect explicit or viable (potentially in C++1y) conversions.
5722   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5723     NamedDecl *D = (*I)->getUnderlyingDecl();
5724     CXXConversionDecl *Conversion;
5725     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5726     if (ConvTemplate) {
5727       if (getLangOpts().CPlusPlus14)
5728         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5729       else
5730         continue; // C++11 does not consider conversion operator templates(?).
5731     } else
5732       Conversion = cast<CXXConversionDecl>(D);
5733 
5734     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5735            "Conversion operator templates are considered potentially "
5736            "viable in C++1y");
5737 
5738     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5739     if (Converter.match(CurToType) || ConvTemplate) {
5740 
5741       if (Conversion->isExplicit()) {
5742         // FIXME: For C++1y, do we need this restriction?
5743         // cf. diagnoseNoViableConversion()
5744         if (!ConvTemplate)
5745           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5746       } else {
5747         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5748           if (ToType.isNull())
5749             ToType = CurToType.getUnqualifiedType();
5750           else if (HasUniqueTargetType &&
5751                    (CurToType.getUnqualifiedType() != ToType))
5752             HasUniqueTargetType = false;
5753         }
5754         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5755       }
5756     }
5757   }
5758 
5759   if (getLangOpts().CPlusPlus14) {
5760     // C++1y [conv]p6:
5761     // ... An expression e of class type E appearing in such a context
5762     // is said to be contextually implicitly converted to a specified
5763     // type T and is well-formed if and only if e can be implicitly
5764     // converted to a type T that is determined as follows: E is searched
5765     // for conversion functions whose return type is cv T or reference to
5766     // cv T such that T is allowed by the context. There shall be
5767     // exactly one such T.
5768 
5769     // If no unique T is found:
5770     if (ToType.isNull()) {
5771       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5772                                      HadMultipleCandidates,
5773                                      ExplicitConversions))
5774         return ExprError();
5775       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5776     }
5777 
5778     // If more than one unique Ts are found:
5779     if (!HasUniqueTargetType)
5780       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5781                                          ViableConversions);
5782 
5783     // If one unique T is found:
5784     // First, build a candidate set from the previously recorded
5785     // potentially viable conversions.
5786     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5787     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5788                                       CandidateSet);
5789 
5790     // Then, perform overload resolution over the candidate set.
5791     OverloadCandidateSet::iterator Best;
5792     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5793     case OR_Success: {
5794       // Apply this conversion.
5795       DeclAccessPair Found =
5796           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5797       if (recordConversion(*this, Loc, From, Converter, T,
5798                            HadMultipleCandidates, Found))
5799         return ExprError();
5800       break;
5801     }
5802     case OR_Ambiguous:
5803       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5804                                          ViableConversions);
5805     case OR_No_Viable_Function:
5806       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5807                                      HadMultipleCandidates,
5808                                      ExplicitConversions))
5809         return ExprError();
5810       LLVM_FALLTHROUGH;
5811     case OR_Deleted:
5812       // We'll complain below about a non-integral condition type.
5813       break;
5814     }
5815   } else {
5816     switch (ViableConversions.size()) {
5817     case 0: {
5818       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5819                                      HadMultipleCandidates,
5820                                      ExplicitConversions))
5821         return ExprError();
5822 
5823       // We'll complain below about a non-integral condition type.
5824       break;
5825     }
5826     case 1: {
5827       // Apply this conversion.
5828       DeclAccessPair Found = ViableConversions[0];
5829       if (recordConversion(*this, Loc, From, Converter, T,
5830                            HadMultipleCandidates, Found))
5831         return ExprError();
5832       break;
5833     }
5834     default:
5835       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5836                                          ViableConversions);
5837     }
5838   }
5839 
5840   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5841 }
5842 
5843 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5844 /// an acceptable non-member overloaded operator for a call whose
5845 /// arguments have types T1 (and, if non-empty, T2). This routine
5846 /// implements the check in C++ [over.match.oper]p3b2 concerning
5847 /// enumeration types.
5848 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5849                                                    FunctionDecl *Fn,
5850                                                    ArrayRef<Expr *> Args) {
5851   QualType T1 = Args[0]->getType();
5852   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5853 
5854   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5855     return true;
5856 
5857   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5858     return true;
5859 
5860   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5861   if (Proto->getNumParams() < 1)
5862     return false;
5863 
5864   if (T1->isEnumeralType()) {
5865     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5866     if (Context.hasSameUnqualifiedType(T1, ArgType))
5867       return true;
5868   }
5869 
5870   if (Proto->getNumParams() < 2)
5871     return false;
5872 
5873   if (!T2.isNull() && T2->isEnumeralType()) {
5874     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5875     if (Context.hasSameUnqualifiedType(T2, ArgType))
5876       return true;
5877   }
5878 
5879   return false;
5880 }
5881 
5882 /// AddOverloadCandidate - Adds the given function to the set of
5883 /// candidate functions, using the given function call arguments.  If
5884 /// @p SuppressUserConversions, then don't allow user-defined
5885 /// conversions via constructors or conversion operators.
5886 ///
5887 /// \param PartialOverloading true if we are performing "partial" overloading
5888 /// based on an incomplete set of function arguments. This feature is used by
5889 /// code completion.
5890 void
5891 Sema::AddOverloadCandidate(FunctionDecl *Function,
5892                            DeclAccessPair FoundDecl,
5893                            ArrayRef<Expr *> Args,
5894                            OverloadCandidateSet &CandidateSet,
5895                            bool SuppressUserConversions,
5896                            bool PartialOverloading,
5897                            bool AllowExplicit,
5898                            ConversionSequenceList EarlyConversions) {
5899   const FunctionProtoType *Proto
5900     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5901   assert(Proto && "Functions without a prototype cannot be overloaded");
5902   assert(!Function->getDescribedFunctionTemplate() &&
5903          "Use AddTemplateOverloadCandidate for function templates");
5904 
5905   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5906     if (!isa<CXXConstructorDecl>(Method)) {
5907       // If we get here, it's because we're calling a member function
5908       // that is named without a member access expression (e.g.,
5909       // "this->f") that was either written explicitly or created
5910       // implicitly. This can happen with a qualified call to a member
5911       // function, e.g., X::f(). We use an empty type for the implied
5912       // object argument (C++ [over.call.func]p3), and the acting context
5913       // is irrelevant.
5914       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5915                          Expr::Classification::makeSimpleLValue(), Args,
5916                          CandidateSet, SuppressUserConversions,
5917                          PartialOverloading, EarlyConversions);
5918       return;
5919     }
5920     // We treat a constructor like a non-member function, since its object
5921     // argument doesn't participate in overload resolution.
5922   }
5923 
5924   if (!CandidateSet.isNewCandidate(Function))
5925     return;
5926 
5927   // C++ [over.match.oper]p3:
5928   //   if no operand has a class type, only those non-member functions in the
5929   //   lookup set that have a first parameter of type T1 or "reference to
5930   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5931   //   is a right operand) a second parameter of type T2 or "reference to
5932   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5933   //   candidate functions.
5934   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5935       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5936     return;
5937 
5938   // C++11 [class.copy]p11: [DR1402]
5939   //   A defaulted move constructor that is defined as deleted is ignored by
5940   //   overload resolution.
5941   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5942   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5943       Constructor->isMoveConstructor())
5944     return;
5945 
5946   // Overload resolution is always an unevaluated context.
5947   EnterExpressionEvaluationContext Unevaluated(
5948       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5949 
5950   // Add this candidate
5951   OverloadCandidate &Candidate =
5952       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5953   Candidate.FoundDecl = FoundDecl;
5954   Candidate.Function = Function;
5955   Candidate.Viable = true;
5956   Candidate.IsSurrogate = false;
5957   Candidate.IgnoreObjectArgument = false;
5958   Candidate.ExplicitCallArguments = Args.size();
5959 
5960   if (Constructor) {
5961     // C++ [class.copy]p3:
5962     //   A member function template is never instantiated to perform the copy
5963     //   of a class object to an object of its class type.
5964     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5965     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5966         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5967          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5968                        ClassType))) {
5969       Candidate.Viable = false;
5970       Candidate.FailureKind = ovl_fail_illegal_constructor;
5971       return;
5972     }
5973 
5974     // C++ [over.match.funcs]p8: (proposed DR resolution)
5975     //   A constructor inherited from class type C that has a first parameter
5976     //   of type "reference to P" (including such a constructor instantiated
5977     //   from a template) is excluded from the set of candidate functions when
5978     //   constructing an object of type cv D if the argument list has exactly
5979     //   one argument and D is reference-related to P and P is reference-related
5980     //   to C.
5981     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5982     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5983         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5984       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5985       QualType C = Context.getRecordType(Constructor->getParent());
5986       QualType D = Context.getRecordType(Shadow->getParent());
5987       SourceLocation Loc = Args.front()->getExprLoc();
5988       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5989           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5990         Candidate.Viable = false;
5991         Candidate.FailureKind = ovl_fail_inhctor_slice;
5992         return;
5993       }
5994     }
5995   }
5996 
5997   unsigned NumParams = Proto->getNumParams();
5998 
5999   // (C++ 13.3.2p2): A candidate function having fewer than m
6000   // parameters is viable only if it has an ellipsis in its parameter
6001   // list (8.3.5).
6002   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6003       !Proto->isVariadic()) {
6004     Candidate.Viable = false;
6005     Candidate.FailureKind = ovl_fail_too_many_arguments;
6006     return;
6007   }
6008 
6009   // (C++ 13.3.2p2): A candidate function having more than m parameters
6010   // is viable only if the (m+1)st parameter has a default argument
6011   // (8.3.6). For the purposes of overload resolution, the
6012   // parameter list is truncated on the right, so that there are
6013   // exactly m parameters.
6014   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6015   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6016     // Not enough arguments.
6017     Candidate.Viable = false;
6018     Candidate.FailureKind = ovl_fail_too_few_arguments;
6019     return;
6020   }
6021 
6022   // (CUDA B.1): Check for invalid calls between targets.
6023   if (getLangOpts().CUDA)
6024     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6025       // Skip the check for callers that are implicit members, because in this
6026       // case we may not yet know what the member's target is; the target is
6027       // inferred for the member automatically, based on the bases and fields of
6028       // the class.
6029       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6030         Candidate.Viable = false;
6031         Candidate.FailureKind = ovl_fail_bad_target;
6032         return;
6033       }
6034 
6035   // Determine the implicit conversion sequences for each of the
6036   // arguments.
6037   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6038     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6039       // We already formed a conversion sequence for this parameter during
6040       // template argument deduction.
6041     } else if (ArgIdx < NumParams) {
6042       // (C++ 13.3.2p3): for F to be a viable function, there shall
6043       // exist for each argument an implicit conversion sequence
6044       // (13.3.3.1) that converts that argument to the corresponding
6045       // parameter of F.
6046       QualType ParamType = Proto->getParamType(ArgIdx);
6047       Candidate.Conversions[ArgIdx]
6048         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6049                                 SuppressUserConversions,
6050                                 /*InOverloadResolution=*/true,
6051                                 /*AllowObjCWritebackConversion=*/
6052                                   getLangOpts().ObjCAutoRefCount,
6053                                 AllowExplicit);
6054       if (Candidate.Conversions[ArgIdx].isBad()) {
6055         Candidate.Viable = false;
6056         Candidate.FailureKind = ovl_fail_bad_conversion;
6057         return;
6058       }
6059     } else {
6060       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6061       // argument for which there is no corresponding parameter is
6062       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6063       Candidate.Conversions[ArgIdx].setEllipsis();
6064     }
6065   }
6066 
6067   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6068     Candidate.Viable = false;
6069     Candidate.FailureKind = ovl_fail_enable_if;
6070     Candidate.DeductionFailure.Data = FailedAttr;
6071     return;
6072   }
6073 
6074   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6075     Candidate.Viable = false;
6076     Candidate.FailureKind = ovl_fail_ext_disabled;
6077     return;
6078   }
6079 }
6080 
6081 ObjCMethodDecl *
6082 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6083                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6084   if (Methods.size() <= 1)
6085     return nullptr;
6086 
6087   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6088     bool Match = true;
6089     ObjCMethodDecl *Method = Methods[b];
6090     unsigned NumNamedArgs = Sel.getNumArgs();
6091     // Method might have more arguments than selector indicates. This is due
6092     // to addition of c-style arguments in method.
6093     if (Method->param_size() > NumNamedArgs)
6094       NumNamedArgs = Method->param_size();
6095     if (Args.size() < NumNamedArgs)
6096       continue;
6097 
6098     for (unsigned i = 0; i < NumNamedArgs; i++) {
6099       // We can't do any type-checking on a type-dependent argument.
6100       if (Args[i]->isTypeDependent()) {
6101         Match = false;
6102         break;
6103       }
6104 
6105       ParmVarDecl *param = Method->parameters()[i];
6106       Expr *argExpr = Args[i];
6107       assert(argExpr && "SelectBestMethod(): missing expression");
6108 
6109       // Strip the unbridged-cast placeholder expression off unless it's
6110       // a consumed argument.
6111       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6112           !param->hasAttr<CFConsumedAttr>())
6113         argExpr = stripARCUnbridgedCast(argExpr);
6114 
6115       // If the parameter is __unknown_anytype, move on to the next method.
6116       if (param->getType() == Context.UnknownAnyTy) {
6117         Match = false;
6118         break;
6119       }
6120 
6121       ImplicitConversionSequence ConversionState
6122         = TryCopyInitialization(*this, argExpr, param->getType(),
6123                                 /*SuppressUserConversions*/false,
6124                                 /*InOverloadResolution=*/true,
6125                                 /*AllowObjCWritebackConversion=*/
6126                                 getLangOpts().ObjCAutoRefCount,
6127                                 /*AllowExplicit*/false);
6128       // This function looks for a reasonably-exact match, so we consider
6129       // incompatible pointer conversions to be a failure here.
6130       if (ConversionState.isBad() ||
6131           (ConversionState.isStandard() &&
6132            ConversionState.Standard.Second ==
6133                ICK_Incompatible_Pointer_Conversion)) {
6134         Match = false;
6135         break;
6136       }
6137     }
6138     // Promote additional arguments to variadic methods.
6139     if (Match && Method->isVariadic()) {
6140       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6141         if (Args[i]->isTypeDependent()) {
6142           Match = false;
6143           break;
6144         }
6145         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6146                                                           nullptr);
6147         if (Arg.isInvalid()) {
6148           Match = false;
6149           break;
6150         }
6151       }
6152     } else {
6153       // Check for extra arguments to non-variadic methods.
6154       if (Args.size() != NumNamedArgs)
6155         Match = false;
6156       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6157         // Special case when selectors have no argument. In this case, select
6158         // one with the most general result type of 'id'.
6159         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6160           QualType ReturnT = Methods[b]->getReturnType();
6161           if (ReturnT->isObjCIdType())
6162             return Methods[b];
6163         }
6164       }
6165     }
6166 
6167     if (Match)
6168       return Method;
6169   }
6170   return nullptr;
6171 }
6172 
6173 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6174 // enable_if is order-sensitive. As a result, we need to reverse things
6175 // sometimes. Size of 4 elements is arbitrary.
6176 static SmallVector<EnableIfAttr *, 4>
6177 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6178   SmallVector<EnableIfAttr *, 4> Result;
6179   if (!Function->hasAttrs())
6180     return Result;
6181 
6182   const auto &FuncAttrs = Function->getAttrs();
6183   for (Attr *Attr : FuncAttrs)
6184     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6185       Result.push_back(EnableIf);
6186 
6187   std::reverse(Result.begin(), Result.end());
6188   return Result;
6189 }
6190 
6191 static bool
6192 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6193                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6194                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6195                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6196   if (ThisArg) {
6197     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6198     assert(!isa<CXXConstructorDecl>(Method) &&
6199            "Shouldn't have `this` for ctors!");
6200     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6201     ExprResult R = S.PerformObjectArgumentInitialization(
6202         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6203     if (R.isInvalid())
6204       return false;
6205     ConvertedThis = R.get();
6206   } else {
6207     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6208       (void)MD;
6209       assert((MissingImplicitThis || MD->isStatic() ||
6210               isa<CXXConstructorDecl>(MD)) &&
6211              "Expected `this` for non-ctor instance methods");
6212     }
6213     ConvertedThis = nullptr;
6214   }
6215 
6216   // Ignore any variadic arguments. Converting them is pointless, since the
6217   // user can't refer to them in the function condition.
6218   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6219 
6220   // Convert the arguments.
6221   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6222     ExprResult R;
6223     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6224                                         S.Context, Function->getParamDecl(I)),
6225                                     SourceLocation(), Args[I]);
6226 
6227     if (R.isInvalid())
6228       return false;
6229 
6230     ConvertedArgs.push_back(R.get());
6231   }
6232 
6233   if (Trap.hasErrorOccurred())
6234     return false;
6235 
6236   // Push default arguments if needed.
6237   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6238     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6239       ParmVarDecl *P = Function->getParamDecl(i);
6240       ExprResult R = S.PerformCopyInitialization(
6241           InitializedEntity::InitializeParameter(S.Context,
6242                                                  Function->getParamDecl(i)),
6243           SourceLocation(),
6244           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6245                                            : P->getDefaultArg());
6246       if (R.isInvalid())
6247         return false;
6248       ConvertedArgs.push_back(R.get());
6249     }
6250 
6251     if (Trap.hasErrorOccurred())
6252       return false;
6253   }
6254   return true;
6255 }
6256 
6257 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6258                                   bool MissingImplicitThis) {
6259   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6260       getOrderedEnableIfAttrs(Function);
6261   if (EnableIfAttrs.empty())
6262     return nullptr;
6263 
6264   SFINAETrap Trap(*this);
6265   SmallVector<Expr *, 16> ConvertedArgs;
6266   // FIXME: We should look into making enable_if late-parsed.
6267   Expr *DiscardedThis;
6268   if (!convertArgsForAvailabilityChecks(
6269           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6270           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6271     return EnableIfAttrs[0];
6272 
6273   for (auto *EIA : EnableIfAttrs) {
6274     APValue Result;
6275     // FIXME: This doesn't consider value-dependent cases, because doing so is
6276     // very difficult. Ideally, we should handle them more gracefully.
6277     if (!EIA->getCond()->EvaluateWithSubstitution(
6278             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6279       return EIA;
6280 
6281     if (!Result.isInt() || !Result.getInt().getBoolValue())
6282       return EIA;
6283   }
6284   return nullptr;
6285 }
6286 
6287 template <typename CheckFn>
6288 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6289                                         bool ArgDependent, SourceLocation Loc,
6290                                         CheckFn &&IsSuccessful) {
6291   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6292   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6293     if (ArgDependent == DIA->getArgDependent())
6294       Attrs.push_back(DIA);
6295   }
6296 
6297   // Common case: No diagnose_if attributes, so we can quit early.
6298   if (Attrs.empty())
6299     return false;
6300 
6301   auto WarningBegin = std::stable_partition(
6302       Attrs.begin(), Attrs.end(),
6303       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6304 
6305   // Note that diagnose_if attributes are late-parsed, so they appear in the
6306   // correct order (unlike enable_if attributes).
6307   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6308                                IsSuccessful);
6309   if (ErrAttr != WarningBegin) {
6310     const DiagnoseIfAttr *DIA = *ErrAttr;
6311     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6312     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6313         << DIA->getParent() << DIA->getCond()->getSourceRange();
6314     return true;
6315   }
6316 
6317   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6318     if (IsSuccessful(DIA)) {
6319       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6320       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6321           << DIA->getParent() << DIA->getCond()->getSourceRange();
6322     }
6323 
6324   return false;
6325 }
6326 
6327 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6328                                                const Expr *ThisArg,
6329                                                ArrayRef<const Expr *> Args,
6330                                                SourceLocation Loc) {
6331   return diagnoseDiagnoseIfAttrsWith(
6332       *this, Function, /*ArgDependent=*/true, Loc,
6333       [&](const DiagnoseIfAttr *DIA) {
6334         APValue Result;
6335         // It's sane to use the same Args for any redecl of this function, since
6336         // EvaluateWithSubstitution only cares about the position of each
6337         // argument in the arg list, not the ParmVarDecl* it maps to.
6338         if (!DIA->getCond()->EvaluateWithSubstitution(
6339                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6340           return false;
6341         return Result.isInt() && Result.getInt().getBoolValue();
6342       });
6343 }
6344 
6345 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6346                                                  SourceLocation Loc) {
6347   return diagnoseDiagnoseIfAttrsWith(
6348       *this, ND, /*ArgDependent=*/false, Loc,
6349       [&](const DiagnoseIfAttr *DIA) {
6350         bool Result;
6351         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6352                Result;
6353       });
6354 }
6355 
6356 /// \brief Add all of the function declarations in the given function set to
6357 /// the overload candidate set.
6358 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6359                                  ArrayRef<Expr *> Args,
6360                                  OverloadCandidateSet& CandidateSet,
6361                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6362                                  bool SuppressUserConversions,
6363                                  bool PartialOverloading,
6364                                  bool FirstArgumentIsBase) {
6365   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6366     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6367     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6368       ArrayRef<Expr *> FunctionArgs = Args;
6369       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6370         QualType ObjectType;
6371         Expr::Classification ObjectClassification;
6372         if (Args.size() > 0) {
6373           if (Expr *E = Args[0]) {
6374             // Use the explit base to restrict the lookup:
6375             ObjectType = E->getType();
6376             ObjectClassification = E->Classify(Context);
6377           } // .. else there is an implit base.
6378           FunctionArgs = Args.slice(1);
6379         }
6380         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6381                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6382                            ObjectClassification, FunctionArgs, CandidateSet,
6383                            SuppressUserConversions, PartialOverloading);
6384       } else {
6385         // Slice the first argument (which is the base) when we access
6386         // static method as non-static
6387         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6388                                              !isa<CXXConstructorDecl>(FD)))) {
6389           assert(cast<CXXMethodDecl>(FD)->isStatic());
6390           FunctionArgs = Args.slice(1);
6391         }
6392         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6393                              SuppressUserConversions, PartialOverloading);
6394       }
6395     } else {
6396       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6397       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6398           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6399         QualType ObjectType;
6400         Expr::Classification ObjectClassification;
6401         if (Expr *E = Args[0]) {
6402           // Use the explit base to restrict the lookup:
6403           ObjectType = E->getType();
6404           ObjectClassification = E->Classify(Context);
6405         } // .. else there is an implit base.
6406         AddMethodTemplateCandidate(
6407             FunTmpl, F.getPair(),
6408             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6409             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6410             Args.slice(1), CandidateSet, SuppressUserConversions,
6411             PartialOverloading);
6412       } else {
6413         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6414                                      ExplicitTemplateArgs, Args,
6415                                      CandidateSet, SuppressUserConversions,
6416                                      PartialOverloading);
6417       }
6418     }
6419   }
6420 }
6421 
6422 /// AddMethodCandidate - Adds a named decl (which is some kind of
6423 /// method) as a method candidate to the given overload set.
6424 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6425                               QualType ObjectType,
6426                               Expr::Classification ObjectClassification,
6427                               ArrayRef<Expr *> Args,
6428                               OverloadCandidateSet& CandidateSet,
6429                               bool SuppressUserConversions) {
6430   NamedDecl *Decl = FoundDecl.getDecl();
6431   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6432 
6433   if (isa<UsingShadowDecl>(Decl))
6434     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6435 
6436   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6437     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6438            "Expected a member function template");
6439     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6440                                /*ExplicitArgs*/ nullptr, ObjectType,
6441                                ObjectClassification, Args, CandidateSet,
6442                                SuppressUserConversions);
6443   } else {
6444     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6445                        ObjectType, ObjectClassification, Args, CandidateSet,
6446                        SuppressUserConversions);
6447   }
6448 }
6449 
6450 /// AddMethodCandidate - Adds the given C++ member function to the set
6451 /// of candidate functions, using the given function call arguments
6452 /// and the object argument (@c Object). For example, in a call
6453 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6454 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6455 /// allow user-defined conversions via constructors or conversion
6456 /// operators.
6457 void
6458 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6459                          CXXRecordDecl *ActingContext, QualType ObjectType,
6460                          Expr::Classification ObjectClassification,
6461                          ArrayRef<Expr *> Args,
6462                          OverloadCandidateSet &CandidateSet,
6463                          bool SuppressUserConversions,
6464                          bool PartialOverloading,
6465                          ConversionSequenceList EarlyConversions) {
6466   const FunctionProtoType *Proto
6467     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6468   assert(Proto && "Methods without a prototype cannot be overloaded");
6469   assert(!isa<CXXConstructorDecl>(Method) &&
6470          "Use AddOverloadCandidate for constructors");
6471 
6472   if (!CandidateSet.isNewCandidate(Method))
6473     return;
6474 
6475   // C++11 [class.copy]p23: [DR1402]
6476   //   A defaulted move assignment operator that is defined as deleted is
6477   //   ignored by overload resolution.
6478   if (Method->isDefaulted() && Method->isDeleted() &&
6479       Method->isMoveAssignmentOperator())
6480     return;
6481 
6482   // Overload resolution is always an unevaluated context.
6483   EnterExpressionEvaluationContext Unevaluated(
6484       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6485 
6486   // Add this candidate
6487   OverloadCandidate &Candidate =
6488       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6489   Candidate.FoundDecl = FoundDecl;
6490   Candidate.Function = Method;
6491   Candidate.IsSurrogate = false;
6492   Candidate.IgnoreObjectArgument = false;
6493   Candidate.ExplicitCallArguments = Args.size();
6494 
6495   unsigned NumParams = Proto->getNumParams();
6496 
6497   // (C++ 13.3.2p2): A candidate function having fewer than m
6498   // parameters is viable only if it has an ellipsis in its parameter
6499   // list (8.3.5).
6500   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6501       !Proto->isVariadic()) {
6502     Candidate.Viable = false;
6503     Candidate.FailureKind = ovl_fail_too_many_arguments;
6504     return;
6505   }
6506 
6507   // (C++ 13.3.2p2): A candidate function having more than m parameters
6508   // is viable only if the (m+1)st parameter has a default argument
6509   // (8.3.6). For the purposes of overload resolution, the
6510   // parameter list is truncated on the right, so that there are
6511   // exactly m parameters.
6512   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6513   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6514     // Not enough arguments.
6515     Candidate.Viable = false;
6516     Candidate.FailureKind = ovl_fail_too_few_arguments;
6517     return;
6518   }
6519 
6520   Candidate.Viable = true;
6521 
6522   if (Method->isStatic() || ObjectType.isNull())
6523     // The implicit object argument is ignored.
6524     Candidate.IgnoreObjectArgument = true;
6525   else {
6526     // Determine the implicit conversion sequence for the object
6527     // parameter.
6528     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6529         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6530         Method, ActingContext);
6531     if (Candidate.Conversions[0].isBad()) {
6532       Candidate.Viable = false;
6533       Candidate.FailureKind = ovl_fail_bad_conversion;
6534       return;
6535     }
6536   }
6537 
6538   // (CUDA B.1): Check for invalid calls between targets.
6539   if (getLangOpts().CUDA)
6540     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6541       if (!IsAllowedCUDACall(Caller, Method)) {
6542         Candidate.Viable = false;
6543         Candidate.FailureKind = ovl_fail_bad_target;
6544         return;
6545       }
6546 
6547   // Determine the implicit conversion sequences for each of the
6548   // arguments.
6549   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6550     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6551       // We already formed a conversion sequence for this parameter during
6552       // template argument deduction.
6553     } else if (ArgIdx < NumParams) {
6554       // (C++ 13.3.2p3): for F to be a viable function, there shall
6555       // exist for each argument an implicit conversion sequence
6556       // (13.3.3.1) that converts that argument to the corresponding
6557       // parameter of F.
6558       QualType ParamType = Proto->getParamType(ArgIdx);
6559       Candidate.Conversions[ArgIdx + 1]
6560         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6561                                 SuppressUserConversions,
6562                                 /*InOverloadResolution=*/true,
6563                                 /*AllowObjCWritebackConversion=*/
6564                                   getLangOpts().ObjCAutoRefCount);
6565       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6566         Candidate.Viable = false;
6567         Candidate.FailureKind = ovl_fail_bad_conversion;
6568         return;
6569       }
6570     } else {
6571       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6572       // argument for which there is no corresponding parameter is
6573       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6574       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6575     }
6576   }
6577 
6578   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6579     Candidate.Viable = false;
6580     Candidate.FailureKind = ovl_fail_enable_if;
6581     Candidate.DeductionFailure.Data = FailedAttr;
6582     return;
6583   }
6584 }
6585 
6586 /// \brief Add a C++ member function template as a candidate to the candidate
6587 /// set, using template argument deduction to produce an appropriate member
6588 /// function template specialization.
6589 void
6590 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6591                                  DeclAccessPair FoundDecl,
6592                                  CXXRecordDecl *ActingContext,
6593                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6594                                  QualType ObjectType,
6595                                  Expr::Classification ObjectClassification,
6596                                  ArrayRef<Expr *> Args,
6597                                  OverloadCandidateSet& CandidateSet,
6598                                  bool SuppressUserConversions,
6599                                  bool PartialOverloading) {
6600   if (!CandidateSet.isNewCandidate(MethodTmpl))
6601     return;
6602 
6603   // C++ [over.match.funcs]p7:
6604   //   In each case where a candidate is a function template, candidate
6605   //   function template specializations are generated using template argument
6606   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6607   //   candidate functions in the usual way.113) A given name can refer to one
6608   //   or more function templates and also to a set of overloaded non-template
6609   //   functions. In such a case, the candidate functions generated from each
6610   //   function template are combined with the set of non-template candidate
6611   //   functions.
6612   TemplateDeductionInfo Info(CandidateSet.getLocation());
6613   FunctionDecl *Specialization = nullptr;
6614   ConversionSequenceList Conversions;
6615   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6616           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6617           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6618             return CheckNonDependentConversions(
6619                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6620                 SuppressUserConversions, ActingContext, ObjectType,
6621                 ObjectClassification);
6622           })) {
6623     OverloadCandidate &Candidate =
6624         CandidateSet.addCandidate(Conversions.size(), Conversions);
6625     Candidate.FoundDecl = FoundDecl;
6626     Candidate.Function = MethodTmpl->getTemplatedDecl();
6627     Candidate.Viable = false;
6628     Candidate.IsSurrogate = false;
6629     Candidate.IgnoreObjectArgument =
6630         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6631         ObjectType.isNull();
6632     Candidate.ExplicitCallArguments = Args.size();
6633     if (Result == TDK_NonDependentConversionFailure)
6634       Candidate.FailureKind = ovl_fail_bad_conversion;
6635     else {
6636       Candidate.FailureKind = ovl_fail_bad_deduction;
6637       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6638                                                             Info);
6639     }
6640     return;
6641   }
6642 
6643   // Add the function template specialization produced by template argument
6644   // deduction as a candidate.
6645   assert(Specialization && "Missing member function template specialization?");
6646   assert(isa<CXXMethodDecl>(Specialization) &&
6647          "Specialization is not a member function?");
6648   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6649                      ActingContext, ObjectType, ObjectClassification, Args,
6650                      CandidateSet, SuppressUserConversions, PartialOverloading,
6651                      Conversions);
6652 }
6653 
6654 /// \brief Add a C++ function template specialization as a candidate
6655 /// in the candidate set, using template argument deduction to produce
6656 /// an appropriate function template specialization.
6657 void
6658 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6659                                    DeclAccessPair FoundDecl,
6660                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6661                                    ArrayRef<Expr *> Args,
6662                                    OverloadCandidateSet& CandidateSet,
6663                                    bool SuppressUserConversions,
6664                                    bool PartialOverloading) {
6665   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6666     return;
6667 
6668   // C++ [over.match.funcs]p7:
6669   //   In each case where a candidate is a function template, candidate
6670   //   function template specializations are generated using template argument
6671   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6672   //   candidate functions in the usual way.113) A given name can refer to one
6673   //   or more function templates and also to a set of overloaded non-template
6674   //   functions. In such a case, the candidate functions generated from each
6675   //   function template are combined with the set of non-template candidate
6676   //   functions.
6677   TemplateDeductionInfo Info(CandidateSet.getLocation());
6678   FunctionDecl *Specialization = nullptr;
6679   ConversionSequenceList Conversions;
6680   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6681           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6682           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6683             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6684                                                 Args, CandidateSet, Conversions,
6685                                                 SuppressUserConversions);
6686           })) {
6687     OverloadCandidate &Candidate =
6688         CandidateSet.addCandidate(Conversions.size(), Conversions);
6689     Candidate.FoundDecl = FoundDecl;
6690     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6691     Candidate.Viable = false;
6692     Candidate.IsSurrogate = false;
6693     // Ignore the object argument if there is one, since we don't have an object
6694     // type.
6695     Candidate.IgnoreObjectArgument =
6696         isa<CXXMethodDecl>(Candidate.Function) &&
6697         !isa<CXXConstructorDecl>(Candidate.Function);
6698     Candidate.ExplicitCallArguments = Args.size();
6699     if (Result == TDK_NonDependentConversionFailure)
6700       Candidate.FailureKind = ovl_fail_bad_conversion;
6701     else {
6702       Candidate.FailureKind = ovl_fail_bad_deduction;
6703       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6704                                                             Info);
6705     }
6706     return;
6707   }
6708 
6709   // Add the function template specialization produced by template argument
6710   // deduction as a candidate.
6711   assert(Specialization && "Missing function template specialization?");
6712   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6713                        SuppressUserConversions, PartialOverloading,
6714                        /*AllowExplicit*/false, Conversions);
6715 }
6716 
6717 /// Check that implicit conversion sequences can be formed for each argument
6718 /// whose corresponding parameter has a non-dependent type, per DR1391's
6719 /// [temp.deduct.call]p10.
6720 bool Sema::CheckNonDependentConversions(
6721     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6722     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6723     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6724     CXXRecordDecl *ActingContext, QualType ObjectType,
6725     Expr::Classification ObjectClassification) {
6726   // FIXME: The cases in which we allow explicit conversions for constructor
6727   // arguments never consider calling a constructor template. It's not clear
6728   // that is correct.
6729   const bool AllowExplicit = false;
6730 
6731   auto *FD = FunctionTemplate->getTemplatedDecl();
6732   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6733   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6734   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6735 
6736   Conversions =
6737       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6738 
6739   // Overload resolution is always an unevaluated context.
6740   EnterExpressionEvaluationContext Unevaluated(
6741       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6742 
6743   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6744   // require that, but this check should never result in a hard error, and
6745   // overload resolution is permitted to sidestep instantiations.
6746   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6747       !ObjectType.isNull()) {
6748     Conversions[0] = TryObjectArgumentInitialization(
6749         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6750         Method, ActingContext);
6751     if (Conversions[0].isBad())
6752       return true;
6753   }
6754 
6755   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6756        ++I) {
6757     QualType ParamType = ParamTypes[I];
6758     if (!ParamType->isDependentType()) {
6759       Conversions[ThisConversions + I]
6760         = TryCopyInitialization(*this, Args[I], ParamType,
6761                                 SuppressUserConversions,
6762                                 /*InOverloadResolution=*/true,
6763                                 /*AllowObjCWritebackConversion=*/
6764                                   getLangOpts().ObjCAutoRefCount,
6765                                 AllowExplicit);
6766       if (Conversions[ThisConversions + I].isBad())
6767         return true;
6768     }
6769   }
6770 
6771   return false;
6772 }
6773 
6774 /// Determine whether this is an allowable conversion from the result
6775 /// of an explicit conversion operator to the expected type, per C++
6776 /// [over.match.conv]p1 and [over.match.ref]p1.
6777 ///
6778 /// \param ConvType The return type of the conversion function.
6779 ///
6780 /// \param ToType The type we are converting to.
6781 ///
6782 /// \param AllowObjCPointerConversion Allow a conversion from one
6783 /// Objective-C pointer to another.
6784 ///
6785 /// \returns true if the conversion is allowable, false otherwise.
6786 static bool isAllowableExplicitConversion(Sema &S,
6787                                           QualType ConvType, QualType ToType,
6788                                           bool AllowObjCPointerConversion) {
6789   QualType ToNonRefType = ToType.getNonReferenceType();
6790 
6791   // Easy case: the types are the same.
6792   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6793     return true;
6794 
6795   // Allow qualification conversions.
6796   bool ObjCLifetimeConversion;
6797   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6798                                   ObjCLifetimeConversion))
6799     return true;
6800 
6801   // If we're not allowed to consider Objective-C pointer conversions,
6802   // we're done.
6803   if (!AllowObjCPointerConversion)
6804     return false;
6805 
6806   // Is this an Objective-C pointer conversion?
6807   bool IncompatibleObjC = false;
6808   QualType ConvertedType;
6809   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6810                                    IncompatibleObjC);
6811 }
6812 
6813 /// AddConversionCandidate - Add a C++ conversion function as a
6814 /// candidate in the candidate set (C++ [over.match.conv],
6815 /// C++ [over.match.copy]). From is the expression we're converting from,
6816 /// and ToType is the type that we're eventually trying to convert to
6817 /// (which may or may not be the same type as the type that the
6818 /// conversion function produces).
6819 void
6820 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6821                              DeclAccessPair FoundDecl,
6822                              CXXRecordDecl *ActingContext,
6823                              Expr *From, QualType ToType,
6824                              OverloadCandidateSet& CandidateSet,
6825                              bool AllowObjCConversionOnExplicit,
6826                              bool AllowResultConversion) {
6827   assert(!Conversion->getDescribedFunctionTemplate() &&
6828          "Conversion function templates use AddTemplateConversionCandidate");
6829   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6830   if (!CandidateSet.isNewCandidate(Conversion))
6831     return;
6832 
6833   // If the conversion function has an undeduced return type, trigger its
6834   // deduction now.
6835   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6836     if (DeduceReturnType(Conversion, From->getExprLoc()))
6837       return;
6838     ConvType = Conversion->getConversionType().getNonReferenceType();
6839   }
6840 
6841   // If we don't allow any conversion of the result type, ignore conversion
6842   // functions that don't convert to exactly (possibly cv-qualified) T.
6843   if (!AllowResultConversion &&
6844       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6845     return;
6846 
6847   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6848   // operator is only a candidate if its return type is the target type or
6849   // can be converted to the target type with a qualification conversion.
6850   if (Conversion->isExplicit() &&
6851       !isAllowableExplicitConversion(*this, ConvType, ToType,
6852                                      AllowObjCConversionOnExplicit))
6853     return;
6854 
6855   // Overload resolution is always an unevaluated context.
6856   EnterExpressionEvaluationContext Unevaluated(
6857       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6858 
6859   // Add this candidate
6860   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6861   Candidate.FoundDecl = FoundDecl;
6862   Candidate.Function = Conversion;
6863   Candidate.IsSurrogate = false;
6864   Candidate.IgnoreObjectArgument = false;
6865   Candidate.FinalConversion.setAsIdentityConversion();
6866   Candidate.FinalConversion.setFromType(ConvType);
6867   Candidate.FinalConversion.setAllToTypes(ToType);
6868   Candidate.Viable = true;
6869   Candidate.ExplicitCallArguments = 1;
6870 
6871   // C++ [over.match.funcs]p4:
6872   //   For conversion functions, the function is considered to be a member of
6873   //   the class of the implicit implied object argument for the purpose of
6874   //   defining the type of the implicit object parameter.
6875   //
6876   // Determine the implicit conversion sequence for the implicit
6877   // object parameter.
6878   QualType ImplicitParamType = From->getType();
6879   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6880     ImplicitParamType = FromPtrType->getPointeeType();
6881   CXXRecordDecl *ConversionContext
6882     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6883 
6884   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6885       *this, CandidateSet.getLocation(), From->getType(),
6886       From->Classify(Context), Conversion, ConversionContext);
6887 
6888   if (Candidate.Conversions[0].isBad()) {
6889     Candidate.Viable = false;
6890     Candidate.FailureKind = ovl_fail_bad_conversion;
6891     return;
6892   }
6893 
6894   // We won't go through a user-defined type conversion function to convert a
6895   // derived to base as such conversions are given Conversion Rank. They only
6896   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6897   QualType FromCanon
6898     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6899   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6900   if (FromCanon == ToCanon ||
6901       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6902     Candidate.Viable = false;
6903     Candidate.FailureKind = ovl_fail_trivial_conversion;
6904     return;
6905   }
6906 
6907   // To determine what the conversion from the result of calling the
6908   // conversion function to the type we're eventually trying to
6909   // convert to (ToType), we need to synthesize a call to the
6910   // conversion function and attempt copy initialization from it. This
6911   // makes sure that we get the right semantics with respect to
6912   // lvalues/rvalues and the type. Fortunately, we can allocate this
6913   // call on the stack and we don't need its arguments to be
6914   // well-formed.
6915   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6916                             VK_LValue, From->getLocStart());
6917   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6918                                 Context.getPointerType(Conversion->getType()),
6919                                 CK_FunctionToPointerDecay,
6920                                 &ConversionRef, VK_RValue);
6921 
6922   QualType ConversionType = Conversion->getConversionType();
6923   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6924     Candidate.Viable = false;
6925     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6926     return;
6927   }
6928 
6929   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6930 
6931   // Note that it is safe to allocate CallExpr on the stack here because
6932   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6933   // allocator).
6934   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6935   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6936                 From->getLocStart());
6937   ImplicitConversionSequence ICS =
6938     TryCopyInitialization(*this, &Call, ToType,
6939                           /*SuppressUserConversions=*/true,
6940                           /*InOverloadResolution=*/false,
6941                           /*AllowObjCWritebackConversion=*/false);
6942 
6943   switch (ICS.getKind()) {
6944   case ImplicitConversionSequence::StandardConversion:
6945     Candidate.FinalConversion = ICS.Standard;
6946 
6947     // C++ [over.ics.user]p3:
6948     //   If the user-defined conversion is specified by a specialization of a
6949     //   conversion function template, the second standard conversion sequence
6950     //   shall have exact match rank.
6951     if (Conversion->getPrimaryTemplate() &&
6952         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6953       Candidate.Viable = false;
6954       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6955       return;
6956     }
6957 
6958     // C++0x [dcl.init.ref]p5:
6959     //    In the second case, if the reference is an rvalue reference and
6960     //    the second standard conversion sequence of the user-defined
6961     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6962     //    program is ill-formed.
6963     if (ToType->isRValueReferenceType() &&
6964         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6965       Candidate.Viable = false;
6966       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6967       return;
6968     }
6969     break;
6970 
6971   case ImplicitConversionSequence::BadConversion:
6972     Candidate.Viable = false;
6973     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6974     return;
6975 
6976   default:
6977     llvm_unreachable(
6978            "Can only end up with a standard conversion sequence or failure");
6979   }
6980 
6981   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6982     Candidate.Viable = false;
6983     Candidate.FailureKind = ovl_fail_enable_if;
6984     Candidate.DeductionFailure.Data = FailedAttr;
6985     return;
6986   }
6987 }
6988 
6989 /// \brief Adds a conversion function template specialization
6990 /// candidate to the overload set, using template argument deduction
6991 /// to deduce the template arguments of the conversion function
6992 /// template from the type that we are converting to (C++
6993 /// [temp.deduct.conv]).
6994 void
6995 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6996                                      DeclAccessPair FoundDecl,
6997                                      CXXRecordDecl *ActingDC,
6998                                      Expr *From, QualType ToType,
6999                                      OverloadCandidateSet &CandidateSet,
7000                                      bool AllowObjCConversionOnExplicit,
7001                                      bool AllowResultConversion) {
7002   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7003          "Only conversion function templates permitted here");
7004 
7005   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7006     return;
7007 
7008   TemplateDeductionInfo Info(CandidateSet.getLocation());
7009   CXXConversionDecl *Specialization = nullptr;
7010   if (TemplateDeductionResult Result
7011         = DeduceTemplateArguments(FunctionTemplate, ToType,
7012                                   Specialization, Info)) {
7013     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7014     Candidate.FoundDecl = FoundDecl;
7015     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7016     Candidate.Viable = false;
7017     Candidate.FailureKind = ovl_fail_bad_deduction;
7018     Candidate.IsSurrogate = false;
7019     Candidate.IgnoreObjectArgument = false;
7020     Candidate.ExplicitCallArguments = 1;
7021     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7022                                                           Info);
7023     return;
7024   }
7025 
7026   // Add the conversion function template specialization produced by
7027   // template argument deduction as a candidate.
7028   assert(Specialization && "Missing function template specialization?");
7029   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7030                          CandidateSet, AllowObjCConversionOnExplicit,
7031                          AllowResultConversion);
7032 }
7033 
7034 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7035 /// converts the given @c Object to a function pointer via the
7036 /// conversion function @c Conversion, and then attempts to call it
7037 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7038 /// the type of function that we'll eventually be calling.
7039 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7040                                  DeclAccessPair FoundDecl,
7041                                  CXXRecordDecl *ActingContext,
7042                                  const FunctionProtoType *Proto,
7043                                  Expr *Object,
7044                                  ArrayRef<Expr *> Args,
7045                                  OverloadCandidateSet& CandidateSet) {
7046   if (!CandidateSet.isNewCandidate(Conversion))
7047     return;
7048 
7049   // Overload resolution is always an unevaluated context.
7050   EnterExpressionEvaluationContext Unevaluated(
7051       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7052 
7053   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7054   Candidate.FoundDecl = FoundDecl;
7055   Candidate.Function = nullptr;
7056   Candidate.Surrogate = Conversion;
7057   Candidate.Viable = true;
7058   Candidate.IsSurrogate = true;
7059   Candidate.IgnoreObjectArgument = false;
7060   Candidate.ExplicitCallArguments = Args.size();
7061 
7062   // Determine the implicit conversion sequence for the implicit
7063   // object parameter.
7064   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7065       *this, CandidateSet.getLocation(), Object->getType(),
7066       Object->Classify(Context), Conversion, ActingContext);
7067   if (ObjectInit.isBad()) {
7068     Candidate.Viable = false;
7069     Candidate.FailureKind = ovl_fail_bad_conversion;
7070     Candidate.Conversions[0] = ObjectInit;
7071     return;
7072   }
7073 
7074   // The first conversion is actually a user-defined conversion whose
7075   // first conversion is ObjectInit's standard conversion (which is
7076   // effectively a reference binding). Record it as such.
7077   Candidate.Conversions[0].setUserDefined();
7078   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7079   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7080   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7081   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7082   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7083   Candidate.Conversions[0].UserDefined.After
7084     = Candidate.Conversions[0].UserDefined.Before;
7085   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7086 
7087   // Find the
7088   unsigned NumParams = Proto->getNumParams();
7089 
7090   // (C++ 13.3.2p2): A candidate function having fewer than m
7091   // parameters is viable only if it has an ellipsis in its parameter
7092   // list (8.3.5).
7093   if (Args.size() > NumParams && !Proto->isVariadic()) {
7094     Candidate.Viable = false;
7095     Candidate.FailureKind = ovl_fail_too_many_arguments;
7096     return;
7097   }
7098 
7099   // Function types don't have any default arguments, so just check if
7100   // we have enough arguments.
7101   if (Args.size() < NumParams) {
7102     // Not enough arguments.
7103     Candidate.Viable = false;
7104     Candidate.FailureKind = ovl_fail_too_few_arguments;
7105     return;
7106   }
7107 
7108   // Determine the implicit conversion sequences for each of the
7109   // arguments.
7110   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7111     if (ArgIdx < NumParams) {
7112       // (C++ 13.3.2p3): for F to be a viable function, there shall
7113       // exist for each argument an implicit conversion sequence
7114       // (13.3.3.1) that converts that argument to the corresponding
7115       // parameter of F.
7116       QualType ParamType = Proto->getParamType(ArgIdx);
7117       Candidate.Conversions[ArgIdx + 1]
7118         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7119                                 /*SuppressUserConversions=*/false,
7120                                 /*InOverloadResolution=*/false,
7121                                 /*AllowObjCWritebackConversion=*/
7122                                   getLangOpts().ObjCAutoRefCount);
7123       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7124         Candidate.Viable = false;
7125         Candidate.FailureKind = ovl_fail_bad_conversion;
7126         return;
7127       }
7128     } else {
7129       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7130       // argument for which there is no corresponding parameter is
7131       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7132       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7133     }
7134   }
7135 
7136   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7137     Candidate.Viable = false;
7138     Candidate.FailureKind = ovl_fail_enable_if;
7139     Candidate.DeductionFailure.Data = FailedAttr;
7140     return;
7141   }
7142 }
7143 
7144 /// \brief Add overload candidates for overloaded operators that are
7145 /// member functions.
7146 ///
7147 /// Add the overloaded operator candidates that are member functions
7148 /// for the operator Op that was used in an operator expression such
7149 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7150 /// CandidateSet will store the added overload candidates. (C++
7151 /// [over.match.oper]).
7152 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7153                                        SourceLocation OpLoc,
7154                                        ArrayRef<Expr *> Args,
7155                                        OverloadCandidateSet& CandidateSet,
7156                                        SourceRange OpRange) {
7157   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7158 
7159   // C++ [over.match.oper]p3:
7160   //   For a unary operator @ with an operand of a type whose
7161   //   cv-unqualified version is T1, and for a binary operator @ with
7162   //   a left operand of a type whose cv-unqualified version is T1 and
7163   //   a right operand of a type whose cv-unqualified version is T2,
7164   //   three sets of candidate functions, designated member
7165   //   candidates, non-member candidates and built-in candidates, are
7166   //   constructed as follows:
7167   QualType T1 = Args[0]->getType();
7168 
7169   //     -- If T1 is a complete class type or a class currently being
7170   //        defined, the set of member candidates is the result of the
7171   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7172   //        the set of member candidates is empty.
7173   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7174     // Complete the type if it can be completed.
7175     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7176       return;
7177     // If the type is neither complete nor being defined, bail out now.
7178     if (!T1Rec->getDecl()->getDefinition())
7179       return;
7180 
7181     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7182     LookupQualifiedName(Operators, T1Rec->getDecl());
7183     Operators.suppressDiagnostics();
7184 
7185     for (LookupResult::iterator Oper = Operators.begin(),
7186                              OperEnd = Operators.end();
7187          Oper != OperEnd;
7188          ++Oper)
7189       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7190                          Args[0]->Classify(Context), Args.slice(1),
7191                          CandidateSet, /*SuppressUserConversions=*/false);
7192   }
7193 }
7194 
7195 /// AddBuiltinCandidate - Add a candidate for a built-in
7196 /// operator. ResultTy and ParamTys are the result and parameter types
7197 /// of the built-in candidate, respectively. Args and NumArgs are the
7198 /// arguments being passed to the candidate. IsAssignmentOperator
7199 /// should be true when this built-in candidate is an assignment
7200 /// operator. NumContextualBoolArguments is the number of arguments
7201 /// (at the beginning of the argument list) that will be contextually
7202 /// converted to bool.
7203 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7204                                OverloadCandidateSet& CandidateSet,
7205                                bool IsAssignmentOperator,
7206                                unsigned NumContextualBoolArguments) {
7207   // Overload resolution is always an unevaluated context.
7208   EnterExpressionEvaluationContext Unevaluated(
7209       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7210 
7211   // Add this candidate
7212   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7213   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7214   Candidate.Function = nullptr;
7215   Candidate.IsSurrogate = false;
7216   Candidate.IgnoreObjectArgument = false;
7217   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7218 
7219   // Determine the implicit conversion sequences for each of the
7220   // arguments.
7221   Candidate.Viable = true;
7222   Candidate.ExplicitCallArguments = Args.size();
7223   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7224     // C++ [over.match.oper]p4:
7225     //   For the built-in assignment operators, conversions of the
7226     //   left operand are restricted as follows:
7227     //     -- no temporaries are introduced to hold the left operand, and
7228     //     -- no user-defined conversions are applied to the left
7229     //        operand to achieve a type match with the left-most
7230     //        parameter of a built-in candidate.
7231     //
7232     // We block these conversions by turning off user-defined
7233     // conversions, since that is the only way that initialization of
7234     // a reference to a non-class type can occur from something that
7235     // is not of the same type.
7236     if (ArgIdx < NumContextualBoolArguments) {
7237       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7238              "Contextual conversion to bool requires bool type");
7239       Candidate.Conversions[ArgIdx]
7240         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7241     } else {
7242       Candidate.Conversions[ArgIdx]
7243         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7244                                 ArgIdx == 0 && IsAssignmentOperator,
7245                                 /*InOverloadResolution=*/false,
7246                                 /*AllowObjCWritebackConversion=*/
7247                                   getLangOpts().ObjCAutoRefCount);
7248     }
7249     if (Candidate.Conversions[ArgIdx].isBad()) {
7250       Candidate.Viable = false;
7251       Candidate.FailureKind = ovl_fail_bad_conversion;
7252       break;
7253     }
7254   }
7255 }
7256 
7257 namespace {
7258 
7259 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7260 /// candidate operator functions for built-in operators (C++
7261 /// [over.built]). The types are separated into pointer types and
7262 /// enumeration types.
7263 class BuiltinCandidateTypeSet  {
7264   /// TypeSet - A set of types.
7265   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7266                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7267 
7268   /// PointerTypes - The set of pointer types that will be used in the
7269   /// built-in candidates.
7270   TypeSet PointerTypes;
7271 
7272   /// MemberPointerTypes - The set of member pointer types that will be
7273   /// used in the built-in candidates.
7274   TypeSet MemberPointerTypes;
7275 
7276   /// EnumerationTypes - The set of enumeration types that will be
7277   /// used in the built-in candidates.
7278   TypeSet EnumerationTypes;
7279 
7280   /// \brief The set of vector types that will be used in the built-in
7281   /// candidates.
7282   TypeSet VectorTypes;
7283 
7284   /// \brief A flag indicating non-record types are viable candidates
7285   bool HasNonRecordTypes;
7286 
7287   /// \brief A flag indicating whether either arithmetic or enumeration types
7288   /// were present in the candidate set.
7289   bool HasArithmeticOrEnumeralTypes;
7290 
7291   /// \brief A flag indicating whether the nullptr type was present in the
7292   /// candidate set.
7293   bool HasNullPtrType;
7294 
7295   /// Sema - The semantic analysis instance where we are building the
7296   /// candidate type set.
7297   Sema &SemaRef;
7298 
7299   /// Context - The AST context in which we will build the type sets.
7300   ASTContext &Context;
7301 
7302   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7303                                                const Qualifiers &VisibleQuals);
7304   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7305 
7306 public:
7307   /// iterator - Iterates through the types that are part of the set.
7308   typedef TypeSet::iterator iterator;
7309 
7310   BuiltinCandidateTypeSet(Sema &SemaRef)
7311     : HasNonRecordTypes(false),
7312       HasArithmeticOrEnumeralTypes(false),
7313       HasNullPtrType(false),
7314       SemaRef(SemaRef),
7315       Context(SemaRef.Context) { }
7316 
7317   void AddTypesConvertedFrom(QualType Ty,
7318                              SourceLocation Loc,
7319                              bool AllowUserConversions,
7320                              bool AllowExplicitConversions,
7321                              const Qualifiers &VisibleTypeConversionsQuals);
7322 
7323   /// pointer_begin - First pointer type found;
7324   iterator pointer_begin() { return PointerTypes.begin(); }
7325 
7326   /// pointer_end - Past the last pointer type found;
7327   iterator pointer_end() { return PointerTypes.end(); }
7328 
7329   /// member_pointer_begin - First member pointer type found;
7330   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7331 
7332   /// member_pointer_end - Past the last member pointer type found;
7333   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7334 
7335   /// enumeration_begin - First enumeration type found;
7336   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7337 
7338   /// enumeration_end - Past the last enumeration type found;
7339   iterator enumeration_end() { return EnumerationTypes.end(); }
7340 
7341   iterator vector_begin() { return VectorTypes.begin(); }
7342   iterator vector_end() { return VectorTypes.end(); }
7343 
7344   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7345   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7346   bool hasNullPtrType() const { return HasNullPtrType; }
7347 };
7348 
7349 } // end anonymous namespace
7350 
7351 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7352 /// the set of pointer types along with any more-qualified variants of
7353 /// that type. For example, if @p Ty is "int const *", this routine
7354 /// will add "int const *", "int const volatile *", "int const
7355 /// restrict *", and "int const volatile restrict *" to the set of
7356 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7357 /// false otherwise.
7358 ///
7359 /// FIXME: what to do about extended qualifiers?
7360 bool
7361 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7362                                              const Qualifiers &VisibleQuals) {
7363 
7364   // Insert this type.
7365   if (!PointerTypes.insert(Ty))
7366     return false;
7367 
7368   QualType PointeeTy;
7369   const PointerType *PointerTy = Ty->getAs<PointerType>();
7370   bool buildObjCPtr = false;
7371   if (!PointerTy) {
7372     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7373     PointeeTy = PTy->getPointeeType();
7374     buildObjCPtr = true;
7375   } else {
7376     PointeeTy = PointerTy->getPointeeType();
7377   }
7378 
7379   // Don't add qualified variants of arrays. For one, they're not allowed
7380   // (the qualifier would sink to the element type), and for another, the
7381   // only overload situation where it matters is subscript or pointer +- int,
7382   // and those shouldn't have qualifier variants anyway.
7383   if (PointeeTy->isArrayType())
7384     return true;
7385 
7386   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7387   bool hasVolatile = VisibleQuals.hasVolatile();
7388   bool hasRestrict = VisibleQuals.hasRestrict();
7389 
7390   // Iterate through all strict supersets of BaseCVR.
7391   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7392     if ((CVR | BaseCVR) != CVR) continue;
7393     // Skip over volatile if no volatile found anywhere in the types.
7394     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7395 
7396     // Skip over restrict if no restrict found anywhere in the types, or if
7397     // the type cannot be restrict-qualified.
7398     if ((CVR & Qualifiers::Restrict) &&
7399         (!hasRestrict ||
7400          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7401       continue;
7402 
7403     // Build qualified pointee type.
7404     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7405 
7406     // Build qualified pointer type.
7407     QualType QPointerTy;
7408     if (!buildObjCPtr)
7409       QPointerTy = Context.getPointerType(QPointeeTy);
7410     else
7411       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7412 
7413     // Insert qualified pointer type.
7414     PointerTypes.insert(QPointerTy);
7415   }
7416 
7417   return true;
7418 }
7419 
7420 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7421 /// to the set of pointer types along with any more-qualified variants of
7422 /// that type. For example, if @p Ty is "int const *", this routine
7423 /// will add "int const *", "int const volatile *", "int const
7424 /// restrict *", and "int const volatile restrict *" to the set of
7425 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7426 /// false otherwise.
7427 ///
7428 /// FIXME: what to do about extended qualifiers?
7429 bool
7430 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7431     QualType Ty) {
7432   // Insert this type.
7433   if (!MemberPointerTypes.insert(Ty))
7434     return false;
7435 
7436   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7437   assert(PointerTy && "type was not a member pointer type!");
7438 
7439   QualType PointeeTy = PointerTy->getPointeeType();
7440   // Don't add qualified variants of arrays. For one, they're not allowed
7441   // (the qualifier would sink to the element type), and for another, the
7442   // only overload situation where it matters is subscript or pointer +- int,
7443   // and those shouldn't have qualifier variants anyway.
7444   if (PointeeTy->isArrayType())
7445     return true;
7446   const Type *ClassTy = PointerTy->getClass();
7447 
7448   // Iterate through all strict supersets of the pointee type's CVR
7449   // qualifiers.
7450   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7451   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7452     if ((CVR | BaseCVR) != CVR) continue;
7453 
7454     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7455     MemberPointerTypes.insert(
7456       Context.getMemberPointerType(QPointeeTy, ClassTy));
7457   }
7458 
7459   return true;
7460 }
7461 
7462 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7463 /// Ty can be implicit converted to the given set of @p Types. We're
7464 /// primarily interested in pointer types and enumeration types. We also
7465 /// take member pointer types, for the conditional operator.
7466 /// AllowUserConversions is true if we should look at the conversion
7467 /// functions of a class type, and AllowExplicitConversions if we
7468 /// should also include the explicit conversion functions of a class
7469 /// type.
7470 void
7471 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7472                                                SourceLocation Loc,
7473                                                bool AllowUserConversions,
7474                                                bool AllowExplicitConversions,
7475                                                const Qualifiers &VisibleQuals) {
7476   // Only deal with canonical types.
7477   Ty = Context.getCanonicalType(Ty);
7478 
7479   // Look through reference types; they aren't part of the type of an
7480   // expression for the purposes of conversions.
7481   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7482     Ty = RefTy->getPointeeType();
7483 
7484   // If we're dealing with an array type, decay to the pointer.
7485   if (Ty->isArrayType())
7486     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7487 
7488   // Otherwise, we don't care about qualifiers on the type.
7489   Ty = Ty.getLocalUnqualifiedType();
7490 
7491   // Flag if we ever add a non-record type.
7492   const RecordType *TyRec = Ty->getAs<RecordType>();
7493   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7494 
7495   // Flag if we encounter an arithmetic type.
7496   HasArithmeticOrEnumeralTypes =
7497     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7498 
7499   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7500     PointerTypes.insert(Ty);
7501   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7502     // Insert our type, and its more-qualified variants, into the set
7503     // of types.
7504     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7505       return;
7506   } else if (Ty->isMemberPointerType()) {
7507     // Member pointers are far easier, since the pointee can't be converted.
7508     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7509       return;
7510   } else if (Ty->isEnumeralType()) {
7511     HasArithmeticOrEnumeralTypes = true;
7512     EnumerationTypes.insert(Ty);
7513   } else if (Ty->isVectorType()) {
7514     // We treat vector types as arithmetic types in many contexts as an
7515     // extension.
7516     HasArithmeticOrEnumeralTypes = true;
7517     VectorTypes.insert(Ty);
7518   } else if (Ty->isNullPtrType()) {
7519     HasNullPtrType = true;
7520   } else if (AllowUserConversions && TyRec) {
7521     // No conversion functions in incomplete types.
7522     if (!SemaRef.isCompleteType(Loc, Ty))
7523       return;
7524 
7525     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7526     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7527       if (isa<UsingShadowDecl>(D))
7528         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7529 
7530       // Skip conversion function templates; they don't tell us anything
7531       // about which builtin types we can convert to.
7532       if (isa<FunctionTemplateDecl>(D))
7533         continue;
7534 
7535       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7536       if (AllowExplicitConversions || !Conv->isExplicit()) {
7537         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7538                               VisibleQuals);
7539       }
7540     }
7541   }
7542 }
7543 
7544 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7545 /// the volatile- and non-volatile-qualified assignment operators for the
7546 /// given type to the candidate set.
7547 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7548                                                    QualType T,
7549                                                    ArrayRef<Expr *> Args,
7550                                     OverloadCandidateSet &CandidateSet) {
7551   QualType ParamTypes[2];
7552 
7553   // T& operator=(T&, T)
7554   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7555   ParamTypes[1] = T;
7556   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7557                         /*IsAssignmentOperator=*/true);
7558 
7559   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7560     // volatile T& operator=(volatile T&, T)
7561     ParamTypes[0]
7562       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7563     ParamTypes[1] = T;
7564     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7565                           /*IsAssignmentOperator=*/true);
7566   }
7567 }
7568 
7569 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7570 /// if any, found in visible type conversion functions found in ArgExpr's type.
7571 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7572     Qualifiers VRQuals;
7573     const RecordType *TyRec;
7574     if (const MemberPointerType *RHSMPType =
7575         ArgExpr->getType()->getAs<MemberPointerType>())
7576       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7577     else
7578       TyRec = ArgExpr->getType()->getAs<RecordType>();
7579     if (!TyRec) {
7580       // Just to be safe, assume the worst case.
7581       VRQuals.addVolatile();
7582       VRQuals.addRestrict();
7583       return VRQuals;
7584     }
7585 
7586     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7587     if (!ClassDecl->hasDefinition())
7588       return VRQuals;
7589 
7590     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7591       if (isa<UsingShadowDecl>(D))
7592         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7593       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7594         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7595         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7596           CanTy = ResTypeRef->getPointeeType();
7597         // Need to go down the pointer/mempointer chain and add qualifiers
7598         // as see them.
7599         bool done = false;
7600         while (!done) {
7601           if (CanTy.isRestrictQualified())
7602             VRQuals.addRestrict();
7603           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7604             CanTy = ResTypePtr->getPointeeType();
7605           else if (const MemberPointerType *ResTypeMPtr =
7606                 CanTy->getAs<MemberPointerType>())
7607             CanTy = ResTypeMPtr->getPointeeType();
7608           else
7609             done = true;
7610           if (CanTy.isVolatileQualified())
7611             VRQuals.addVolatile();
7612           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7613             return VRQuals;
7614         }
7615       }
7616     }
7617     return VRQuals;
7618 }
7619 
7620 namespace {
7621 
7622 /// \brief Helper class to manage the addition of builtin operator overload
7623 /// candidates. It provides shared state and utility methods used throughout
7624 /// the process, as well as a helper method to add each group of builtin
7625 /// operator overloads from the standard to a candidate set.
7626 class BuiltinOperatorOverloadBuilder {
7627   // Common instance state available to all overload candidate addition methods.
7628   Sema &S;
7629   ArrayRef<Expr *> Args;
7630   Qualifiers VisibleTypeConversionsQuals;
7631   bool HasArithmeticOrEnumeralCandidateType;
7632   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7633   OverloadCandidateSet &CandidateSet;
7634 
7635   static constexpr int ArithmeticTypesCap = 24;
7636   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7637 
7638   // Define some indices used to iterate over the arithemetic types in
7639   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7640   // types are that preserved by promotion (C++ [over.built]p2).
7641   unsigned FirstIntegralType,
7642            LastIntegralType;
7643   unsigned FirstPromotedIntegralType,
7644            LastPromotedIntegralType;
7645   unsigned FirstPromotedArithmeticType,
7646            LastPromotedArithmeticType;
7647   unsigned NumArithmeticTypes;
7648 
7649   void InitArithmeticTypes() {
7650     // Start of promoted types.
7651     FirstPromotedArithmeticType = 0;
7652     ArithmeticTypes.push_back(S.Context.FloatTy);
7653     ArithmeticTypes.push_back(S.Context.DoubleTy);
7654     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7655     if (S.Context.getTargetInfo().hasFloat128Type())
7656       ArithmeticTypes.push_back(S.Context.Float128Ty);
7657 
7658     // Start of integral types.
7659     FirstIntegralType = ArithmeticTypes.size();
7660     FirstPromotedIntegralType = ArithmeticTypes.size();
7661     ArithmeticTypes.push_back(S.Context.IntTy);
7662     ArithmeticTypes.push_back(S.Context.LongTy);
7663     ArithmeticTypes.push_back(S.Context.LongLongTy);
7664     if (S.Context.getTargetInfo().hasInt128Type())
7665       ArithmeticTypes.push_back(S.Context.Int128Ty);
7666     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7667     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7668     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7669     if (S.Context.getTargetInfo().hasInt128Type())
7670       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7671     LastPromotedIntegralType = ArithmeticTypes.size();
7672     LastPromotedArithmeticType = ArithmeticTypes.size();
7673     // End of promoted types.
7674 
7675     ArithmeticTypes.push_back(S.Context.BoolTy);
7676     ArithmeticTypes.push_back(S.Context.CharTy);
7677     ArithmeticTypes.push_back(S.Context.WCharTy);
7678     ArithmeticTypes.push_back(S.Context.Char16Ty);
7679     ArithmeticTypes.push_back(S.Context.Char32Ty);
7680     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7681     ArithmeticTypes.push_back(S.Context.ShortTy);
7682     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7683     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7684     LastIntegralType = ArithmeticTypes.size();
7685     NumArithmeticTypes = ArithmeticTypes.size();
7686     // End of integral types.
7687     // FIXME: What about complex? What about half?
7688 
7689     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7690            "Enough inline storage for all arithmetic types.");
7691   }
7692 
7693   /// \brief Helper method to factor out the common pattern of adding overloads
7694   /// for '++' and '--' builtin operators.
7695   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7696                                            bool HasVolatile,
7697                                            bool HasRestrict) {
7698     QualType ParamTypes[2] = {
7699       S.Context.getLValueReferenceType(CandidateTy),
7700       S.Context.IntTy
7701     };
7702 
7703     // Non-volatile version.
7704     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7705 
7706     // Use a heuristic to reduce number of builtin candidates in the set:
7707     // add volatile version only if there are conversions to a volatile type.
7708     if (HasVolatile) {
7709       ParamTypes[0] =
7710         S.Context.getLValueReferenceType(
7711           S.Context.getVolatileType(CandidateTy));
7712       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7713     }
7714 
7715     // Add restrict version only if there are conversions to a restrict type
7716     // and our candidate type is a non-restrict-qualified pointer.
7717     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7718         !CandidateTy.isRestrictQualified()) {
7719       ParamTypes[0]
7720         = S.Context.getLValueReferenceType(
7721             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7722       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7723 
7724       if (HasVolatile) {
7725         ParamTypes[0]
7726           = S.Context.getLValueReferenceType(
7727               S.Context.getCVRQualifiedType(CandidateTy,
7728                                             (Qualifiers::Volatile |
7729                                              Qualifiers::Restrict)));
7730         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7731       }
7732     }
7733 
7734   }
7735 
7736 public:
7737   BuiltinOperatorOverloadBuilder(
7738     Sema &S, ArrayRef<Expr *> Args,
7739     Qualifiers VisibleTypeConversionsQuals,
7740     bool HasArithmeticOrEnumeralCandidateType,
7741     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7742     OverloadCandidateSet &CandidateSet)
7743     : S(S), Args(Args),
7744       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7745       HasArithmeticOrEnumeralCandidateType(
7746         HasArithmeticOrEnumeralCandidateType),
7747       CandidateTypes(CandidateTypes),
7748       CandidateSet(CandidateSet) {
7749 
7750     InitArithmeticTypes();
7751   }
7752 
7753   // C++ [over.built]p3:
7754   //
7755   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7756   //   is either volatile or empty, there exist candidate operator
7757   //   functions of the form
7758   //
7759   //       VQ T&      operator++(VQ T&);
7760   //       T          operator++(VQ T&, int);
7761   //
7762   // C++ [over.built]p4:
7763   //
7764   //   For every pair (T, VQ), where T is an arithmetic type other
7765   //   than bool, and VQ is either volatile or empty, there exist
7766   //   candidate operator functions of the form
7767   //
7768   //       VQ T&      operator--(VQ T&);
7769   //       T          operator--(VQ T&, int);
7770   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7771     if (!HasArithmeticOrEnumeralCandidateType)
7772       return;
7773 
7774     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7775          Arith < NumArithmeticTypes; ++Arith) {
7776       addPlusPlusMinusMinusStyleOverloads(
7777         ArithmeticTypes[Arith],
7778         VisibleTypeConversionsQuals.hasVolatile(),
7779         VisibleTypeConversionsQuals.hasRestrict());
7780     }
7781   }
7782 
7783   // C++ [over.built]p5:
7784   //
7785   //   For every pair (T, VQ), where T is a cv-qualified or
7786   //   cv-unqualified object type, and VQ is either volatile or
7787   //   empty, there exist candidate operator functions of the form
7788   //
7789   //       T*VQ&      operator++(T*VQ&);
7790   //       T*VQ&      operator--(T*VQ&);
7791   //       T*         operator++(T*VQ&, int);
7792   //       T*         operator--(T*VQ&, int);
7793   void addPlusPlusMinusMinusPointerOverloads() {
7794     for (BuiltinCandidateTypeSet::iterator
7795               Ptr = CandidateTypes[0].pointer_begin(),
7796            PtrEnd = CandidateTypes[0].pointer_end();
7797          Ptr != PtrEnd; ++Ptr) {
7798       // Skip pointer types that aren't pointers to object types.
7799       if (!(*Ptr)->getPointeeType()->isObjectType())
7800         continue;
7801 
7802       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7803         (!(*Ptr).isVolatileQualified() &&
7804          VisibleTypeConversionsQuals.hasVolatile()),
7805         (!(*Ptr).isRestrictQualified() &&
7806          VisibleTypeConversionsQuals.hasRestrict()));
7807     }
7808   }
7809 
7810   // C++ [over.built]p6:
7811   //   For every cv-qualified or cv-unqualified object type T, there
7812   //   exist candidate operator functions of the form
7813   //
7814   //       T&         operator*(T*);
7815   //
7816   // C++ [over.built]p7:
7817   //   For every function type T that does not have cv-qualifiers or a
7818   //   ref-qualifier, there exist candidate operator functions of the form
7819   //       T&         operator*(T*);
7820   void addUnaryStarPointerOverloads() {
7821     for (BuiltinCandidateTypeSet::iterator
7822               Ptr = CandidateTypes[0].pointer_begin(),
7823            PtrEnd = CandidateTypes[0].pointer_end();
7824          Ptr != PtrEnd; ++Ptr) {
7825       QualType ParamTy = *Ptr;
7826       QualType PointeeTy = ParamTy->getPointeeType();
7827       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7828         continue;
7829 
7830       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7831         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7832           continue;
7833 
7834       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7835     }
7836   }
7837 
7838   // C++ [over.built]p9:
7839   //  For every promoted arithmetic type T, there exist candidate
7840   //  operator functions of the form
7841   //
7842   //       T         operator+(T);
7843   //       T         operator-(T);
7844   void addUnaryPlusOrMinusArithmeticOverloads() {
7845     if (!HasArithmeticOrEnumeralCandidateType)
7846       return;
7847 
7848     for (unsigned Arith = FirstPromotedArithmeticType;
7849          Arith < LastPromotedArithmeticType; ++Arith) {
7850       QualType ArithTy = ArithmeticTypes[Arith];
7851       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7852     }
7853 
7854     // Extension: We also add these operators for vector types.
7855     for (BuiltinCandidateTypeSet::iterator
7856               Vec = CandidateTypes[0].vector_begin(),
7857            VecEnd = CandidateTypes[0].vector_end();
7858          Vec != VecEnd; ++Vec) {
7859       QualType VecTy = *Vec;
7860       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7861     }
7862   }
7863 
7864   // C++ [over.built]p8:
7865   //   For every type T, there exist candidate operator functions of
7866   //   the form
7867   //
7868   //       T*         operator+(T*);
7869   void addUnaryPlusPointerOverloads() {
7870     for (BuiltinCandidateTypeSet::iterator
7871               Ptr = CandidateTypes[0].pointer_begin(),
7872            PtrEnd = CandidateTypes[0].pointer_end();
7873          Ptr != PtrEnd; ++Ptr) {
7874       QualType ParamTy = *Ptr;
7875       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7876     }
7877   }
7878 
7879   // C++ [over.built]p10:
7880   //   For every promoted integral type T, there exist candidate
7881   //   operator functions of the form
7882   //
7883   //        T         operator~(T);
7884   void addUnaryTildePromotedIntegralOverloads() {
7885     if (!HasArithmeticOrEnumeralCandidateType)
7886       return;
7887 
7888     for (unsigned Int = FirstPromotedIntegralType;
7889          Int < LastPromotedIntegralType; ++Int) {
7890       QualType IntTy = ArithmeticTypes[Int];
7891       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7892     }
7893 
7894     // Extension: We also add this operator for vector types.
7895     for (BuiltinCandidateTypeSet::iterator
7896               Vec = CandidateTypes[0].vector_begin(),
7897            VecEnd = CandidateTypes[0].vector_end();
7898          Vec != VecEnd; ++Vec) {
7899       QualType VecTy = *Vec;
7900       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7901     }
7902   }
7903 
7904   // C++ [over.match.oper]p16:
7905   //   For every pointer to member type T or type std::nullptr_t, there
7906   //   exist candidate operator functions of the form
7907   //
7908   //        bool operator==(T,T);
7909   //        bool operator!=(T,T);
7910   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7911     /// Set of (canonical) types that we've already handled.
7912     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7913 
7914     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7915       for (BuiltinCandidateTypeSet::iterator
7916                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7917              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7918            MemPtr != MemPtrEnd;
7919            ++MemPtr) {
7920         // Don't add the same builtin candidate twice.
7921         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7922           continue;
7923 
7924         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7925         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7926       }
7927 
7928       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7929         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7930         if (AddedTypes.insert(NullPtrTy).second) {
7931           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7932           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7933         }
7934       }
7935     }
7936   }
7937 
7938   // C++ [over.built]p15:
7939   //
7940   //   For every T, where T is an enumeration type or a pointer type,
7941   //   there exist candidate operator functions of the form
7942   //
7943   //        bool       operator<(T, T);
7944   //        bool       operator>(T, T);
7945   //        bool       operator<=(T, T);
7946   //        bool       operator>=(T, T);
7947   //        bool       operator==(T, T);
7948   //        bool       operator!=(T, T);
7949   void addRelationalPointerOrEnumeralOverloads() {
7950     // C++ [over.match.oper]p3:
7951     //   [...]the built-in candidates include all of the candidate operator
7952     //   functions defined in 13.6 that, compared to the given operator, [...]
7953     //   do not have the same parameter-type-list as any non-template non-member
7954     //   candidate.
7955     //
7956     // Note that in practice, this only affects enumeration types because there
7957     // aren't any built-in candidates of record type, and a user-defined operator
7958     // must have an operand of record or enumeration type. Also, the only other
7959     // overloaded operator with enumeration arguments, operator=,
7960     // cannot be overloaded for enumeration types, so this is the only place
7961     // where we must suppress candidates like this.
7962     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7963       UserDefinedBinaryOperators;
7964 
7965     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7966       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7967           CandidateTypes[ArgIdx].enumeration_end()) {
7968         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7969                                          CEnd = CandidateSet.end();
7970              C != CEnd; ++C) {
7971           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7972             continue;
7973 
7974           if (C->Function->isFunctionTemplateSpecialization())
7975             continue;
7976 
7977           QualType FirstParamType =
7978             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7979           QualType SecondParamType =
7980             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7981 
7982           // Skip if either parameter isn't of enumeral type.
7983           if (!FirstParamType->isEnumeralType() ||
7984               !SecondParamType->isEnumeralType())
7985             continue;
7986 
7987           // Add this operator to the set of known user-defined operators.
7988           UserDefinedBinaryOperators.insert(
7989             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7990                            S.Context.getCanonicalType(SecondParamType)));
7991         }
7992       }
7993     }
7994 
7995     /// Set of (canonical) types that we've already handled.
7996     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7997 
7998     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7999       for (BuiltinCandidateTypeSet::iterator
8000                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8001              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8002            Ptr != PtrEnd; ++Ptr) {
8003         // Don't add the same builtin candidate twice.
8004         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8005           continue;
8006 
8007         QualType ParamTypes[2] = { *Ptr, *Ptr };
8008         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8009       }
8010       for (BuiltinCandidateTypeSet::iterator
8011                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8012              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8013            Enum != EnumEnd; ++Enum) {
8014         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8015 
8016         // Don't add the same builtin candidate twice, or if a user defined
8017         // candidate exists.
8018         if (!AddedTypes.insert(CanonType).second ||
8019             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8020                                                             CanonType)))
8021           continue;
8022 
8023         QualType ParamTypes[2] = { *Enum, *Enum };
8024         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8025       }
8026     }
8027   }
8028 
8029   // C++ [over.built]p13:
8030   //
8031   //   For every cv-qualified or cv-unqualified object type T
8032   //   there exist candidate operator functions of the form
8033   //
8034   //      T*         operator+(T*, ptrdiff_t);
8035   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8036   //      T*         operator-(T*, ptrdiff_t);
8037   //      T*         operator+(ptrdiff_t, T*);
8038   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8039   //
8040   // C++ [over.built]p14:
8041   //
8042   //   For every T, where T is a pointer to object type, there
8043   //   exist candidate operator functions of the form
8044   //
8045   //      ptrdiff_t  operator-(T, T);
8046   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8047     /// Set of (canonical) types that we've already handled.
8048     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8049 
8050     for (int Arg = 0; Arg < 2; ++Arg) {
8051       QualType AsymmetricParamTypes[2] = {
8052         S.Context.getPointerDiffType(),
8053         S.Context.getPointerDiffType(),
8054       };
8055       for (BuiltinCandidateTypeSet::iterator
8056                 Ptr = CandidateTypes[Arg].pointer_begin(),
8057              PtrEnd = CandidateTypes[Arg].pointer_end();
8058            Ptr != PtrEnd; ++Ptr) {
8059         QualType PointeeTy = (*Ptr)->getPointeeType();
8060         if (!PointeeTy->isObjectType())
8061           continue;
8062 
8063         AsymmetricParamTypes[Arg] = *Ptr;
8064         if (Arg == 0 || Op == OO_Plus) {
8065           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8066           // T* operator+(ptrdiff_t, T*);
8067           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8068         }
8069         if (Op == OO_Minus) {
8070           // ptrdiff_t operator-(T, T);
8071           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8072             continue;
8073 
8074           QualType ParamTypes[2] = { *Ptr, *Ptr };
8075           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8076         }
8077       }
8078     }
8079   }
8080 
8081   // C++ [over.built]p12:
8082   //
8083   //   For every pair of promoted arithmetic types L and R, there
8084   //   exist candidate operator functions of the form
8085   //
8086   //        LR         operator*(L, R);
8087   //        LR         operator/(L, R);
8088   //        LR         operator+(L, R);
8089   //        LR         operator-(L, R);
8090   //        bool       operator<(L, R);
8091   //        bool       operator>(L, R);
8092   //        bool       operator<=(L, R);
8093   //        bool       operator>=(L, R);
8094   //        bool       operator==(L, R);
8095   //        bool       operator!=(L, R);
8096   //
8097   //   where LR is the result of the usual arithmetic conversions
8098   //   between types L and R.
8099   //
8100   // C++ [over.built]p24:
8101   //
8102   //   For every pair of promoted arithmetic types L and R, there exist
8103   //   candidate operator functions of the form
8104   //
8105   //        LR       operator?(bool, L, R);
8106   //
8107   //   where LR is the result of the usual arithmetic conversions
8108   //   between types L and R.
8109   // Our candidates ignore the first parameter.
8110   void addGenericBinaryArithmeticOverloads() {
8111     if (!HasArithmeticOrEnumeralCandidateType)
8112       return;
8113 
8114     for (unsigned Left = FirstPromotedArithmeticType;
8115          Left < LastPromotedArithmeticType; ++Left) {
8116       for (unsigned Right = FirstPromotedArithmeticType;
8117            Right < LastPromotedArithmeticType; ++Right) {
8118         QualType LandR[2] = { ArithmeticTypes[Left],
8119                               ArithmeticTypes[Right] };
8120         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8121       }
8122     }
8123 
8124     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8125     // conditional operator for vector types.
8126     for (BuiltinCandidateTypeSet::iterator
8127               Vec1 = CandidateTypes[0].vector_begin(),
8128            Vec1End = CandidateTypes[0].vector_end();
8129          Vec1 != Vec1End; ++Vec1) {
8130       for (BuiltinCandidateTypeSet::iterator
8131                 Vec2 = CandidateTypes[1].vector_begin(),
8132              Vec2End = CandidateTypes[1].vector_end();
8133            Vec2 != Vec2End; ++Vec2) {
8134         QualType LandR[2] = { *Vec1, *Vec2 };
8135         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8136       }
8137     }
8138   }
8139 
8140   // C++ [over.built]p17:
8141   //
8142   //   For every pair of promoted integral types L and R, there
8143   //   exist candidate operator functions of the form
8144   //
8145   //      LR         operator%(L, R);
8146   //      LR         operator&(L, R);
8147   //      LR         operator^(L, R);
8148   //      LR         operator|(L, R);
8149   //      L          operator<<(L, R);
8150   //      L          operator>>(L, R);
8151   //
8152   //   where LR is the result of the usual arithmetic conversions
8153   //   between types L and R.
8154   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8155     if (!HasArithmeticOrEnumeralCandidateType)
8156       return;
8157 
8158     for (unsigned Left = FirstPromotedIntegralType;
8159          Left < LastPromotedIntegralType; ++Left) {
8160       for (unsigned Right = FirstPromotedIntegralType;
8161            Right < LastPromotedIntegralType; ++Right) {
8162         QualType LandR[2] = { ArithmeticTypes[Left],
8163                               ArithmeticTypes[Right] };
8164         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8165       }
8166     }
8167   }
8168 
8169   // C++ [over.built]p20:
8170   //
8171   //   For every pair (T, VQ), where T is an enumeration or
8172   //   pointer to member type and VQ is either volatile or
8173   //   empty, there exist candidate operator functions of the form
8174   //
8175   //        VQ T&      operator=(VQ T&, T);
8176   void addAssignmentMemberPointerOrEnumeralOverloads() {
8177     /// Set of (canonical) types that we've already handled.
8178     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8179 
8180     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8181       for (BuiltinCandidateTypeSet::iterator
8182                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8183              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8184            Enum != EnumEnd; ++Enum) {
8185         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8186           continue;
8187 
8188         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8189       }
8190 
8191       for (BuiltinCandidateTypeSet::iterator
8192                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8193              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8194            MemPtr != MemPtrEnd; ++MemPtr) {
8195         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8196           continue;
8197 
8198         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8199       }
8200     }
8201   }
8202 
8203   // C++ [over.built]p19:
8204   //
8205   //   For every pair (T, VQ), where T is any type and VQ is either
8206   //   volatile or empty, there exist candidate operator functions
8207   //   of the form
8208   //
8209   //        T*VQ&      operator=(T*VQ&, T*);
8210   //
8211   // C++ [over.built]p21:
8212   //
8213   //   For every pair (T, VQ), where T is a cv-qualified or
8214   //   cv-unqualified object type and VQ is either volatile or
8215   //   empty, there exist candidate operator functions of the form
8216   //
8217   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8218   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8219   void addAssignmentPointerOverloads(bool isEqualOp) {
8220     /// Set of (canonical) types that we've already handled.
8221     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8222 
8223     for (BuiltinCandidateTypeSet::iterator
8224               Ptr = CandidateTypes[0].pointer_begin(),
8225            PtrEnd = CandidateTypes[0].pointer_end();
8226          Ptr != PtrEnd; ++Ptr) {
8227       // If this is operator=, keep track of the builtin candidates we added.
8228       if (isEqualOp)
8229         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8230       else if (!(*Ptr)->getPointeeType()->isObjectType())
8231         continue;
8232 
8233       // non-volatile version
8234       QualType ParamTypes[2] = {
8235         S.Context.getLValueReferenceType(*Ptr),
8236         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8237       };
8238       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8239                             /*IsAssigmentOperator=*/ isEqualOp);
8240 
8241       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8242                           VisibleTypeConversionsQuals.hasVolatile();
8243       if (NeedVolatile) {
8244         // volatile version
8245         ParamTypes[0] =
8246           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8247         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8248                               /*IsAssigmentOperator=*/isEqualOp);
8249       }
8250 
8251       if (!(*Ptr).isRestrictQualified() &&
8252           VisibleTypeConversionsQuals.hasRestrict()) {
8253         // restrict version
8254         ParamTypes[0]
8255           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8256         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8257                               /*IsAssigmentOperator=*/isEqualOp);
8258 
8259         if (NeedVolatile) {
8260           // volatile restrict version
8261           ParamTypes[0]
8262             = S.Context.getLValueReferenceType(
8263                 S.Context.getCVRQualifiedType(*Ptr,
8264                                               (Qualifiers::Volatile |
8265                                                Qualifiers::Restrict)));
8266           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8267                                 /*IsAssigmentOperator=*/isEqualOp);
8268         }
8269       }
8270     }
8271 
8272     if (isEqualOp) {
8273       for (BuiltinCandidateTypeSet::iterator
8274                 Ptr = CandidateTypes[1].pointer_begin(),
8275              PtrEnd = CandidateTypes[1].pointer_end();
8276            Ptr != PtrEnd; ++Ptr) {
8277         // Make sure we don't add the same candidate twice.
8278         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8279           continue;
8280 
8281         QualType ParamTypes[2] = {
8282           S.Context.getLValueReferenceType(*Ptr),
8283           *Ptr,
8284         };
8285 
8286         // non-volatile version
8287         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8288                               /*IsAssigmentOperator=*/true);
8289 
8290         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8291                            VisibleTypeConversionsQuals.hasVolatile();
8292         if (NeedVolatile) {
8293           // volatile version
8294           ParamTypes[0] =
8295             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8296           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8297                                 /*IsAssigmentOperator=*/true);
8298         }
8299 
8300         if (!(*Ptr).isRestrictQualified() &&
8301             VisibleTypeConversionsQuals.hasRestrict()) {
8302           // restrict version
8303           ParamTypes[0]
8304             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8305           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8306                                 /*IsAssigmentOperator=*/true);
8307 
8308           if (NeedVolatile) {
8309             // volatile restrict version
8310             ParamTypes[0]
8311               = S.Context.getLValueReferenceType(
8312                   S.Context.getCVRQualifiedType(*Ptr,
8313                                                 (Qualifiers::Volatile |
8314                                                  Qualifiers::Restrict)));
8315             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8316                                   /*IsAssigmentOperator=*/true);
8317           }
8318         }
8319       }
8320     }
8321   }
8322 
8323   // C++ [over.built]p18:
8324   //
8325   //   For every triple (L, VQ, R), where L is an arithmetic type,
8326   //   VQ is either volatile or empty, and R is a promoted
8327   //   arithmetic type, there exist candidate operator functions of
8328   //   the form
8329   //
8330   //        VQ L&      operator=(VQ L&, R);
8331   //        VQ L&      operator*=(VQ L&, R);
8332   //        VQ L&      operator/=(VQ L&, R);
8333   //        VQ L&      operator+=(VQ L&, R);
8334   //        VQ L&      operator-=(VQ L&, R);
8335   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8336     if (!HasArithmeticOrEnumeralCandidateType)
8337       return;
8338 
8339     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8340       for (unsigned Right = FirstPromotedArithmeticType;
8341            Right < LastPromotedArithmeticType; ++Right) {
8342         QualType ParamTypes[2];
8343         ParamTypes[1] = ArithmeticTypes[Right];
8344 
8345         // Add this built-in operator as a candidate (VQ is empty).
8346         ParamTypes[0] =
8347           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8348         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8349                               /*IsAssigmentOperator=*/isEqualOp);
8350 
8351         // Add this built-in operator as a candidate (VQ is 'volatile').
8352         if (VisibleTypeConversionsQuals.hasVolatile()) {
8353           ParamTypes[0] =
8354             S.Context.getVolatileType(ArithmeticTypes[Left]);
8355           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8356           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8357                                 /*IsAssigmentOperator=*/isEqualOp);
8358         }
8359       }
8360     }
8361 
8362     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8363     for (BuiltinCandidateTypeSet::iterator
8364               Vec1 = CandidateTypes[0].vector_begin(),
8365            Vec1End = CandidateTypes[0].vector_end();
8366          Vec1 != Vec1End; ++Vec1) {
8367       for (BuiltinCandidateTypeSet::iterator
8368                 Vec2 = CandidateTypes[1].vector_begin(),
8369              Vec2End = CandidateTypes[1].vector_end();
8370            Vec2 != Vec2End; ++Vec2) {
8371         QualType ParamTypes[2];
8372         ParamTypes[1] = *Vec2;
8373         // Add this built-in operator as a candidate (VQ is empty).
8374         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8375         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8376                               /*IsAssigmentOperator=*/isEqualOp);
8377 
8378         // Add this built-in operator as a candidate (VQ is 'volatile').
8379         if (VisibleTypeConversionsQuals.hasVolatile()) {
8380           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8381           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8382           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8383                                 /*IsAssigmentOperator=*/isEqualOp);
8384         }
8385       }
8386     }
8387   }
8388 
8389   // C++ [over.built]p22:
8390   //
8391   //   For every triple (L, VQ, R), where L is an integral type, VQ
8392   //   is either volatile or empty, and R is a promoted integral
8393   //   type, there exist candidate operator functions of the form
8394   //
8395   //        VQ L&       operator%=(VQ L&, R);
8396   //        VQ L&       operator<<=(VQ L&, R);
8397   //        VQ L&       operator>>=(VQ L&, R);
8398   //        VQ L&       operator&=(VQ L&, R);
8399   //        VQ L&       operator^=(VQ L&, R);
8400   //        VQ L&       operator|=(VQ L&, R);
8401   void addAssignmentIntegralOverloads() {
8402     if (!HasArithmeticOrEnumeralCandidateType)
8403       return;
8404 
8405     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8406       for (unsigned Right = FirstPromotedIntegralType;
8407            Right < LastPromotedIntegralType; ++Right) {
8408         QualType ParamTypes[2];
8409         ParamTypes[1] = ArithmeticTypes[Right];
8410 
8411         // Add this built-in operator as a candidate (VQ is empty).
8412         ParamTypes[0] =
8413           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8414         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8415         if (VisibleTypeConversionsQuals.hasVolatile()) {
8416           // Add this built-in operator as a candidate (VQ is 'volatile').
8417           ParamTypes[0] = ArithmeticTypes[Left];
8418           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8419           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8420           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8421         }
8422       }
8423     }
8424   }
8425 
8426   // C++ [over.operator]p23:
8427   //
8428   //   There also exist candidate operator functions of the form
8429   //
8430   //        bool        operator!(bool);
8431   //        bool        operator&&(bool, bool);
8432   //        bool        operator||(bool, bool);
8433   void addExclaimOverload() {
8434     QualType ParamTy = S.Context.BoolTy;
8435     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8436                           /*IsAssignmentOperator=*/false,
8437                           /*NumContextualBoolArguments=*/1);
8438   }
8439   void addAmpAmpOrPipePipeOverload() {
8440     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8441     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8442                           /*IsAssignmentOperator=*/false,
8443                           /*NumContextualBoolArguments=*/2);
8444   }
8445 
8446   // C++ [over.built]p13:
8447   //
8448   //   For every cv-qualified or cv-unqualified object type T there
8449   //   exist candidate operator functions of the form
8450   //
8451   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8452   //        T&         operator[](T*, ptrdiff_t);
8453   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8454   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8455   //        T&         operator[](ptrdiff_t, T*);
8456   void addSubscriptOverloads() {
8457     for (BuiltinCandidateTypeSet::iterator
8458               Ptr = CandidateTypes[0].pointer_begin(),
8459            PtrEnd = CandidateTypes[0].pointer_end();
8460          Ptr != PtrEnd; ++Ptr) {
8461       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8462       QualType PointeeType = (*Ptr)->getPointeeType();
8463       if (!PointeeType->isObjectType())
8464         continue;
8465 
8466       // T& operator[](T*, ptrdiff_t)
8467       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8468     }
8469 
8470     for (BuiltinCandidateTypeSet::iterator
8471               Ptr = CandidateTypes[1].pointer_begin(),
8472            PtrEnd = CandidateTypes[1].pointer_end();
8473          Ptr != PtrEnd; ++Ptr) {
8474       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8475       QualType PointeeType = (*Ptr)->getPointeeType();
8476       if (!PointeeType->isObjectType())
8477         continue;
8478 
8479       // T& operator[](ptrdiff_t, T*)
8480       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8481     }
8482   }
8483 
8484   // C++ [over.built]p11:
8485   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8486   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8487   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8488   //    there exist candidate operator functions of the form
8489   //
8490   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8491   //
8492   //    where CV12 is the union of CV1 and CV2.
8493   void addArrowStarOverloads() {
8494     for (BuiltinCandidateTypeSet::iterator
8495              Ptr = CandidateTypes[0].pointer_begin(),
8496            PtrEnd = CandidateTypes[0].pointer_end();
8497          Ptr != PtrEnd; ++Ptr) {
8498       QualType C1Ty = (*Ptr);
8499       QualType C1;
8500       QualifierCollector Q1;
8501       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8502       if (!isa<RecordType>(C1))
8503         continue;
8504       // heuristic to reduce number of builtin candidates in the set.
8505       // Add volatile/restrict version only if there are conversions to a
8506       // volatile/restrict type.
8507       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8508         continue;
8509       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8510         continue;
8511       for (BuiltinCandidateTypeSet::iterator
8512                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8513              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8514            MemPtr != MemPtrEnd; ++MemPtr) {
8515         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8516         QualType C2 = QualType(mptr->getClass(), 0);
8517         C2 = C2.getUnqualifiedType();
8518         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8519           break;
8520         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8521         // build CV12 T&
8522         QualType T = mptr->getPointeeType();
8523         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8524             T.isVolatileQualified())
8525           continue;
8526         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8527             T.isRestrictQualified())
8528           continue;
8529         T = Q1.apply(S.Context, T);
8530         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8531       }
8532     }
8533   }
8534 
8535   // Note that we don't consider the first argument, since it has been
8536   // contextually converted to bool long ago. The candidates below are
8537   // therefore added as binary.
8538   //
8539   // C++ [over.built]p25:
8540   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8541   //   enumeration type, there exist candidate operator functions of the form
8542   //
8543   //        T        operator?(bool, T, T);
8544   //
8545   void addConditionalOperatorOverloads() {
8546     /// Set of (canonical) types that we've already handled.
8547     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8548 
8549     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8550       for (BuiltinCandidateTypeSet::iterator
8551                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8552              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8553            Ptr != PtrEnd; ++Ptr) {
8554         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8555           continue;
8556 
8557         QualType ParamTypes[2] = { *Ptr, *Ptr };
8558         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8559       }
8560 
8561       for (BuiltinCandidateTypeSet::iterator
8562                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8563              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8564            MemPtr != MemPtrEnd; ++MemPtr) {
8565         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8566           continue;
8567 
8568         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8569         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8570       }
8571 
8572       if (S.getLangOpts().CPlusPlus11) {
8573         for (BuiltinCandidateTypeSet::iterator
8574                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8575                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8576              Enum != EnumEnd; ++Enum) {
8577           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8578             continue;
8579 
8580           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8581             continue;
8582 
8583           QualType ParamTypes[2] = { *Enum, *Enum };
8584           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8585         }
8586       }
8587     }
8588   }
8589 };
8590 
8591 } // end anonymous namespace
8592 
8593 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8594 /// operator overloads to the candidate set (C++ [over.built]), based
8595 /// on the operator @p Op and the arguments given. For example, if the
8596 /// operator is a binary '+', this routine might add "int
8597 /// operator+(int, int)" to cover integer addition.
8598 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8599                                         SourceLocation OpLoc,
8600                                         ArrayRef<Expr *> Args,
8601                                         OverloadCandidateSet &CandidateSet) {
8602   // Find all of the types that the arguments can convert to, but only
8603   // if the operator we're looking at has built-in operator candidates
8604   // that make use of these types. Also record whether we encounter non-record
8605   // candidate types or either arithmetic or enumeral candidate types.
8606   Qualifiers VisibleTypeConversionsQuals;
8607   VisibleTypeConversionsQuals.addConst();
8608   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8609     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8610 
8611   bool HasNonRecordCandidateType = false;
8612   bool HasArithmeticOrEnumeralCandidateType = false;
8613   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8614   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8615     CandidateTypes.emplace_back(*this);
8616     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8617                                                  OpLoc,
8618                                                  true,
8619                                                  (Op == OO_Exclaim ||
8620                                                   Op == OO_AmpAmp ||
8621                                                   Op == OO_PipePipe),
8622                                                  VisibleTypeConversionsQuals);
8623     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8624         CandidateTypes[ArgIdx].hasNonRecordTypes();
8625     HasArithmeticOrEnumeralCandidateType =
8626         HasArithmeticOrEnumeralCandidateType ||
8627         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8628   }
8629 
8630   // Exit early when no non-record types have been added to the candidate set
8631   // for any of the arguments to the operator.
8632   //
8633   // We can't exit early for !, ||, or &&, since there we have always have
8634   // 'bool' overloads.
8635   if (!HasNonRecordCandidateType &&
8636       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8637     return;
8638 
8639   // Setup an object to manage the common state for building overloads.
8640   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8641                                            VisibleTypeConversionsQuals,
8642                                            HasArithmeticOrEnumeralCandidateType,
8643                                            CandidateTypes, CandidateSet);
8644 
8645   // Dispatch over the operation to add in only those overloads which apply.
8646   switch (Op) {
8647   case OO_None:
8648   case NUM_OVERLOADED_OPERATORS:
8649     llvm_unreachable("Expected an overloaded operator");
8650 
8651   case OO_New:
8652   case OO_Delete:
8653   case OO_Array_New:
8654   case OO_Array_Delete:
8655   case OO_Call:
8656     llvm_unreachable(
8657                     "Special operators don't use AddBuiltinOperatorCandidates");
8658 
8659   case OO_Comma:
8660   case OO_Arrow:
8661   case OO_Coawait:
8662     // C++ [over.match.oper]p3:
8663     //   -- For the operator ',', the unary operator '&', the
8664     //      operator '->', or the operator 'co_await', the
8665     //      built-in candidates set is empty.
8666     break;
8667 
8668   case OO_Plus: // '+' is either unary or binary
8669     if (Args.size() == 1)
8670       OpBuilder.addUnaryPlusPointerOverloads();
8671     LLVM_FALLTHROUGH;
8672 
8673   case OO_Minus: // '-' is either unary or binary
8674     if (Args.size() == 1) {
8675       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8676     } else {
8677       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8678       OpBuilder.addGenericBinaryArithmeticOverloads();
8679     }
8680     break;
8681 
8682   case OO_Star: // '*' is either unary or binary
8683     if (Args.size() == 1)
8684       OpBuilder.addUnaryStarPointerOverloads();
8685     else
8686       OpBuilder.addGenericBinaryArithmeticOverloads();
8687     break;
8688 
8689   case OO_Slash:
8690     OpBuilder.addGenericBinaryArithmeticOverloads();
8691     break;
8692 
8693   case OO_PlusPlus:
8694   case OO_MinusMinus:
8695     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8696     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8697     break;
8698 
8699   case OO_EqualEqual:
8700   case OO_ExclaimEqual:
8701     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8702     LLVM_FALLTHROUGH;
8703 
8704   case OO_Less:
8705   case OO_Greater:
8706   case OO_LessEqual:
8707   case OO_GreaterEqual:
8708     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8709     OpBuilder.addGenericBinaryArithmeticOverloads();
8710     break;
8711 
8712   case OO_Spaceship:
8713     llvm_unreachable("<=> expressions not supported yet");
8714 
8715   case OO_Percent:
8716   case OO_Caret:
8717   case OO_Pipe:
8718   case OO_LessLess:
8719   case OO_GreaterGreater:
8720     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8721     break;
8722 
8723   case OO_Amp: // '&' is either unary or binary
8724     if (Args.size() == 1)
8725       // C++ [over.match.oper]p3:
8726       //   -- For the operator ',', the unary operator '&', or the
8727       //      operator '->', the built-in candidates set is empty.
8728       break;
8729 
8730     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8731     break;
8732 
8733   case OO_Tilde:
8734     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8735     break;
8736 
8737   case OO_Equal:
8738     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8739     LLVM_FALLTHROUGH;
8740 
8741   case OO_PlusEqual:
8742   case OO_MinusEqual:
8743     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8744     LLVM_FALLTHROUGH;
8745 
8746   case OO_StarEqual:
8747   case OO_SlashEqual:
8748     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8749     break;
8750 
8751   case OO_PercentEqual:
8752   case OO_LessLessEqual:
8753   case OO_GreaterGreaterEqual:
8754   case OO_AmpEqual:
8755   case OO_CaretEqual:
8756   case OO_PipeEqual:
8757     OpBuilder.addAssignmentIntegralOverloads();
8758     break;
8759 
8760   case OO_Exclaim:
8761     OpBuilder.addExclaimOverload();
8762     break;
8763 
8764   case OO_AmpAmp:
8765   case OO_PipePipe:
8766     OpBuilder.addAmpAmpOrPipePipeOverload();
8767     break;
8768 
8769   case OO_Subscript:
8770     OpBuilder.addSubscriptOverloads();
8771     break;
8772 
8773   case OO_ArrowStar:
8774     OpBuilder.addArrowStarOverloads();
8775     break;
8776 
8777   case OO_Conditional:
8778     OpBuilder.addConditionalOperatorOverloads();
8779     OpBuilder.addGenericBinaryArithmeticOverloads();
8780     break;
8781   }
8782 }
8783 
8784 /// \brief Add function candidates found via argument-dependent lookup
8785 /// to the set of overloading candidates.
8786 ///
8787 /// This routine performs argument-dependent name lookup based on the
8788 /// given function name (which may also be an operator name) and adds
8789 /// all of the overload candidates found by ADL to the overload
8790 /// candidate set (C++ [basic.lookup.argdep]).
8791 void
8792 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8793                                            SourceLocation Loc,
8794                                            ArrayRef<Expr *> Args,
8795                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8796                                            OverloadCandidateSet& CandidateSet,
8797                                            bool PartialOverloading) {
8798   ADLResult Fns;
8799 
8800   // FIXME: This approach for uniquing ADL results (and removing
8801   // redundant candidates from the set) relies on pointer-equality,
8802   // which means we need to key off the canonical decl.  However,
8803   // always going back to the canonical decl might not get us the
8804   // right set of default arguments.  What default arguments are
8805   // we supposed to consider on ADL candidates, anyway?
8806 
8807   // FIXME: Pass in the explicit template arguments?
8808   ArgumentDependentLookup(Name, Loc, Args, Fns);
8809 
8810   // Erase all of the candidates we already knew about.
8811   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8812                                    CandEnd = CandidateSet.end();
8813        Cand != CandEnd; ++Cand)
8814     if (Cand->Function) {
8815       Fns.erase(Cand->Function);
8816       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8817         Fns.erase(FunTmpl);
8818     }
8819 
8820   // For each of the ADL candidates we found, add it to the overload
8821   // set.
8822   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8823     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8824     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8825       if (ExplicitTemplateArgs)
8826         continue;
8827 
8828       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8829                            PartialOverloading);
8830     } else
8831       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8832                                    FoundDecl, ExplicitTemplateArgs,
8833                                    Args, CandidateSet, PartialOverloading);
8834   }
8835 }
8836 
8837 namespace {
8838 enum class Comparison { Equal, Better, Worse };
8839 }
8840 
8841 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8842 /// overload resolution.
8843 ///
8844 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8845 /// Cand1's first N enable_if attributes have precisely the same conditions as
8846 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8847 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8848 ///
8849 /// Note that you can have a pair of candidates such that Cand1's enable_if
8850 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8851 /// worse than Cand1's.
8852 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8853                                        const FunctionDecl *Cand2) {
8854   // Common case: One (or both) decls don't have enable_if attrs.
8855   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8856   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8857   if (!Cand1Attr || !Cand2Attr) {
8858     if (Cand1Attr == Cand2Attr)
8859       return Comparison::Equal;
8860     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8861   }
8862 
8863   // FIXME: The next several lines are just
8864   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8865   // instead of reverse order which is how they're stored in the AST.
8866   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8867   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8868 
8869   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8870   // has fewer enable_if attributes than Cand2.
8871   if (Cand1Attrs.size() < Cand2Attrs.size())
8872     return Comparison::Worse;
8873 
8874   auto Cand1I = Cand1Attrs.begin();
8875   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8876   for (auto &Cand2A : Cand2Attrs) {
8877     Cand1ID.clear();
8878     Cand2ID.clear();
8879 
8880     auto &Cand1A = *Cand1I++;
8881     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8882     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8883     if (Cand1ID != Cand2ID)
8884       return Comparison::Worse;
8885   }
8886 
8887   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8888 }
8889 
8890 /// isBetterOverloadCandidate - Determines whether the first overload
8891 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8892 bool clang::isBetterOverloadCandidate(
8893     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8894     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8895   // Define viable functions to be better candidates than non-viable
8896   // functions.
8897   if (!Cand2.Viable)
8898     return Cand1.Viable;
8899   else if (!Cand1.Viable)
8900     return false;
8901 
8902   // C++ [over.match.best]p1:
8903   //
8904   //   -- if F is a static member function, ICS1(F) is defined such
8905   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8906   //      any function G, and, symmetrically, ICS1(G) is neither
8907   //      better nor worse than ICS1(F).
8908   unsigned StartArg = 0;
8909   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8910     StartArg = 1;
8911 
8912   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8913     // We don't allow incompatible pointer conversions in C++.
8914     if (!S.getLangOpts().CPlusPlus)
8915       return ICS.isStandard() &&
8916              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8917 
8918     // The only ill-formed conversion we allow in C++ is the string literal to
8919     // char* conversion, which is only considered ill-formed after C++11.
8920     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8921            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8922   };
8923 
8924   // Define functions that don't require ill-formed conversions for a given
8925   // argument to be better candidates than functions that do.
8926   unsigned NumArgs = Cand1.Conversions.size();
8927   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8928   bool HasBetterConversion = false;
8929   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8930     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8931     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8932     if (Cand1Bad != Cand2Bad) {
8933       if (Cand1Bad)
8934         return false;
8935       HasBetterConversion = true;
8936     }
8937   }
8938 
8939   if (HasBetterConversion)
8940     return true;
8941 
8942   // C++ [over.match.best]p1:
8943   //   A viable function F1 is defined to be a better function than another
8944   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8945   //   conversion sequence than ICSi(F2), and then...
8946   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8947     switch (CompareImplicitConversionSequences(S, Loc,
8948                                                Cand1.Conversions[ArgIdx],
8949                                                Cand2.Conversions[ArgIdx])) {
8950     case ImplicitConversionSequence::Better:
8951       // Cand1 has a better conversion sequence.
8952       HasBetterConversion = true;
8953       break;
8954 
8955     case ImplicitConversionSequence::Worse:
8956       // Cand1 can't be better than Cand2.
8957       return false;
8958 
8959     case ImplicitConversionSequence::Indistinguishable:
8960       // Do nothing.
8961       break;
8962     }
8963   }
8964 
8965   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8966   //       ICSj(F2), or, if not that,
8967   if (HasBetterConversion)
8968     return true;
8969 
8970   //   -- the context is an initialization by user-defined conversion
8971   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8972   //      from the return type of F1 to the destination type (i.e.,
8973   //      the type of the entity being initialized) is a better
8974   //      conversion sequence than the standard conversion sequence
8975   //      from the return type of F2 to the destination type.
8976   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8977       Cand1.Function && Cand2.Function &&
8978       isa<CXXConversionDecl>(Cand1.Function) &&
8979       isa<CXXConversionDecl>(Cand2.Function)) {
8980     // First check whether we prefer one of the conversion functions over the
8981     // other. This only distinguishes the results in non-standard, extension
8982     // cases such as the conversion from a lambda closure type to a function
8983     // pointer or block.
8984     ImplicitConversionSequence::CompareKind Result =
8985         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8986     if (Result == ImplicitConversionSequence::Indistinguishable)
8987       Result = CompareStandardConversionSequences(S, Loc,
8988                                                   Cand1.FinalConversion,
8989                                                   Cand2.FinalConversion);
8990 
8991     if (Result != ImplicitConversionSequence::Indistinguishable)
8992       return Result == ImplicitConversionSequence::Better;
8993 
8994     // FIXME: Compare kind of reference binding if conversion functions
8995     // convert to a reference type used in direct reference binding, per
8996     // C++14 [over.match.best]p1 section 2 bullet 3.
8997   }
8998 
8999   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9000   // as combined with the resolution to CWG issue 243.
9001   //
9002   // When the context is initialization by constructor ([over.match.ctor] or
9003   // either phase of [over.match.list]), a constructor is preferred over
9004   // a conversion function.
9005   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9006       Cand1.Function && Cand2.Function &&
9007       isa<CXXConstructorDecl>(Cand1.Function) !=
9008           isa<CXXConstructorDecl>(Cand2.Function))
9009     return isa<CXXConstructorDecl>(Cand1.Function);
9010 
9011   //    -- F1 is a non-template function and F2 is a function template
9012   //       specialization, or, if not that,
9013   bool Cand1IsSpecialization = Cand1.Function &&
9014                                Cand1.Function->getPrimaryTemplate();
9015   bool Cand2IsSpecialization = Cand2.Function &&
9016                                Cand2.Function->getPrimaryTemplate();
9017   if (Cand1IsSpecialization != Cand2IsSpecialization)
9018     return Cand2IsSpecialization;
9019 
9020   //   -- F1 and F2 are function template specializations, and the function
9021   //      template for F1 is more specialized than the template for F2
9022   //      according to the partial ordering rules described in 14.5.5.2, or,
9023   //      if not that,
9024   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9025     if (FunctionTemplateDecl *BetterTemplate
9026           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9027                                          Cand2.Function->getPrimaryTemplate(),
9028                                          Loc,
9029                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9030                                                              : TPOC_Call,
9031                                          Cand1.ExplicitCallArguments,
9032                                          Cand2.ExplicitCallArguments))
9033       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9034   }
9035 
9036   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9037   // A derived-class constructor beats an (inherited) base class constructor.
9038   bool Cand1IsInherited =
9039       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9040   bool Cand2IsInherited =
9041       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9042   if (Cand1IsInherited != Cand2IsInherited)
9043     return Cand2IsInherited;
9044   else if (Cand1IsInherited) {
9045     assert(Cand2IsInherited);
9046     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9047     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9048     if (Cand1Class->isDerivedFrom(Cand2Class))
9049       return true;
9050     if (Cand2Class->isDerivedFrom(Cand1Class))
9051       return false;
9052     // Inherited from sibling base classes: still ambiguous.
9053   }
9054 
9055   // Check C++17 tie-breakers for deduction guides.
9056   {
9057     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9058     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9059     if (Guide1 && Guide2) {
9060       //  -- F1 is generated from a deduction-guide and F2 is not
9061       if (Guide1->isImplicit() != Guide2->isImplicit())
9062         return Guide2->isImplicit();
9063 
9064       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9065       if (Guide1->isCopyDeductionCandidate())
9066         return true;
9067     }
9068   }
9069 
9070   // Check for enable_if value-based overload resolution.
9071   if (Cand1.Function && Cand2.Function) {
9072     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9073     if (Cmp != Comparison::Equal)
9074       return Cmp == Comparison::Better;
9075   }
9076 
9077   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9078     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9079     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9080            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9081   }
9082 
9083   bool HasPS1 = Cand1.Function != nullptr &&
9084                 functionHasPassObjectSizeParams(Cand1.Function);
9085   bool HasPS2 = Cand2.Function != nullptr &&
9086                 functionHasPassObjectSizeParams(Cand2.Function);
9087   return HasPS1 != HasPS2 && HasPS1;
9088 }
9089 
9090 /// Determine whether two declarations are "equivalent" for the purposes of
9091 /// name lookup and overload resolution. This applies when the same internal/no
9092 /// linkage entity is defined by two modules (probably by textually including
9093 /// the same header). In such a case, we don't consider the declarations to
9094 /// declare the same entity, but we also don't want lookups with both
9095 /// declarations visible to be ambiguous in some cases (this happens when using
9096 /// a modularized libstdc++).
9097 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9098                                                   const NamedDecl *B) {
9099   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9100   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9101   if (!VA || !VB)
9102     return false;
9103 
9104   // The declarations must be declaring the same name as an internal linkage
9105   // entity in different modules.
9106   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9107           VB->getDeclContext()->getRedeclContext()) ||
9108       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9109           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9110       VA->isExternallyVisible() || VB->isExternallyVisible())
9111     return false;
9112 
9113   // Check that the declarations appear to be equivalent.
9114   //
9115   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9116   // For constants and functions, we should check the initializer or body is
9117   // the same. For non-constant variables, we shouldn't allow it at all.
9118   if (Context.hasSameType(VA->getType(), VB->getType()))
9119     return true;
9120 
9121   // Enum constants within unnamed enumerations will have different types, but
9122   // may still be similar enough to be interchangeable for our purposes.
9123   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9124     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9125       // Only handle anonymous enums. If the enumerations were named and
9126       // equivalent, they would have been merged to the same type.
9127       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9128       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9129       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9130           !Context.hasSameType(EnumA->getIntegerType(),
9131                                EnumB->getIntegerType()))
9132         return false;
9133       // Allow this only if the value is the same for both enumerators.
9134       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9135     }
9136   }
9137 
9138   // Nothing else is sufficiently similar.
9139   return false;
9140 }
9141 
9142 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9143     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9144   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9145 
9146   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9147   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9148       << !M << (M ? M->getFullModuleName() : "");
9149 
9150   for (auto *E : Equiv) {
9151     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9152     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9153         << !M << (M ? M->getFullModuleName() : "");
9154   }
9155 }
9156 
9157 /// \brief Computes the best viable function (C++ 13.3.3)
9158 /// within an overload candidate set.
9159 ///
9160 /// \param Loc The location of the function name (or operator symbol) for
9161 /// which overload resolution occurs.
9162 ///
9163 /// \param Best If overload resolution was successful or found a deleted
9164 /// function, \p Best points to the candidate function found.
9165 ///
9166 /// \returns The result of overload resolution.
9167 OverloadingResult
9168 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9169                                          iterator &Best) {
9170   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9171   std::transform(begin(), end(), std::back_inserter(Candidates),
9172                  [](OverloadCandidate &Cand) { return &Cand; });
9173 
9174   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9175   // are accepted by both clang and NVCC. However, during a particular
9176   // compilation mode only one call variant is viable. We need to
9177   // exclude non-viable overload candidates from consideration based
9178   // only on their host/device attributes. Specifically, if one
9179   // candidate call is WrongSide and the other is SameSide, we ignore
9180   // the WrongSide candidate.
9181   if (S.getLangOpts().CUDA) {
9182     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9183     bool ContainsSameSideCandidate =
9184         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9185           return Cand->Function &&
9186                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9187                      Sema::CFP_SameSide;
9188         });
9189     if (ContainsSameSideCandidate) {
9190       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9191         return Cand->Function &&
9192                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9193                    Sema::CFP_WrongSide;
9194       };
9195       llvm::erase_if(Candidates, IsWrongSideCandidate);
9196     }
9197   }
9198 
9199   // Find the best viable function.
9200   Best = end();
9201   for (auto *Cand : Candidates)
9202     if (Cand->Viable)
9203       if (Best == end() ||
9204           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9205         Best = Cand;
9206 
9207   // If we didn't find any viable functions, abort.
9208   if (Best == end())
9209     return OR_No_Viable_Function;
9210 
9211   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9212 
9213   // Make sure that this function is better than every other viable
9214   // function. If not, we have an ambiguity.
9215   for (auto *Cand : Candidates) {
9216     if (Cand->Viable && Cand != Best &&
9217         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9218       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9219                                                    Cand->Function)) {
9220         EquivalentCands.push_back(Cand->Function);
9221         continue;
9222       }
9223 
9224       Best = end();
9225       return OR_Ambiguous;
9226     }
9227   }
9228 
9229   // Best is the best viable function.
9230   if (Best->Function &&
9231       (Best->Function->isDeleted() ||
9232        S.isFunctionConsideredUnavailable(Best->Function)))
9233     return OR_Deleted;
9234 
9235   if (!EquivalentCands.empty())
9236     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9237                                                     EquivalentCands);
9238 
9239   return OR_Success;
9240 }
9241 
9242 namespace {
9243 
9244 enum OverloadCandidateKind {
9245   oc_function,
9246   oc_method,
9247   oc_constructor,
9248   oc_function_template,
9249   oc_method_template,
9250   oc_constructor_template,
9251   oc_implicit_default_constructor,
9252   oc_implicit_copy_constructor,
9253   oc_implicit_move_constructor,
9254   oc_implicit_copy_assignment,
9255   oc_implicit_move_assignment,
9256   oc_inherited_constructor,
9257   oc_inherited_constructor_template
9258 };
9259 
9260 static OverloadCandidateKind
9261 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9262                           std::string &Description) {
9263   bool isTemplate = false;
9264 
9265   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9266     isTemplate = true;
9267     Description = S.getTemplateArgumentBindingsText(
9268       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9269   }
9270 
9271   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9272     if (!Ctor->isImplicit()) {
9273       if (isa<ConstructorUsingShadowDecl>(Found))
9274         return isTemplate ? oc_inherited_constructor_template
9275                           : oc_inherited_constructor;
9276       else
9277         return isTemplate ? oc_constructor_template : oc_constructor;
9278     }
9279 
9280     if (Ctor->isDefaultConstructor())
9281       return oc_implicit_default_constructor;
9282 
9283     if (Ctor->isMoveConstructor())
9284       return oc_implicit_move_constructor;
9285 
9286     assert(Ctor->isCopyConstructor() &&
9287            "unexpected sort of implicit constructor");
9288     return oc_implicit_copy_constructor;
9289   }
9290 
9291   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9292     // This actually gets spelled 'candidate function' for now, but
9293     // it doesn't hurt to split it out.
9294     if (!Meth->isImplicit())
9295       return isTemplate ? oc_method_template : oc_method;
9296 
9297     if (Meth->isMoveAssignmentOperator())
9298       return oc_implicit_move_assignment;
9299 
9300     if (Meth->isCopyAssignmentOperator())
9301       return oc_implicit_copy_assignment;
9302 
9303     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9304     return oc_method;
9305   }
9306 
9307   return isTemplate ? oc_function_template : oc_function;
9308 }
9309 
9310 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9311   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9312   // set.
9313   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9314     S.Diag(FoundDecl->getLocation(),
9315            diag::note_ovl_candidate_inherited_constructor)
9316       << Shadow->getNominatedBaseClass();
9317 }
9318 
9319 } // end anonymous namespace
9320 
9321 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9322                                     const FunctionDecl *FD) {
9323   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9324     bool AlwaysTrue;
9325     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9326       return false;
9327     if (!AlwaysTrue)
9328       return false;
9329   }
9330   return true;
9331 }
9332 
9333 /// \brief Returns true if we can take the address of the function.
9334 ///
9335 /// \param Complain - If true, we'll emit a diagnostic
9336 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9337 ///   we in overload resolution?
9338 /// \param Loc - The location of the statement we're complaining about. Ignored
9339 ///   if we're not complaining, or if we're in overload resolution.
9340 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9341                                               bool Complain,
9342                                               bool InOverloadResolution,
9343                                               SourceLocation Loc) {
9344   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9345     if (Complain) {
9346       if (InOverloadResolution)
9347         S.Diag(FD->getLocStart(),
9348                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9349       else
9350         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9351     }
9352     return false;
9353   }
9354 
9355   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9356     return P->hasAttr<PassObjectSizeAttr>();
9357   });
9358   if (I == FD->param_end())
9359     return true;
9360 
9361   if (Complain) {
9362     // Add one to ParamNo because it's user-facing
9363     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9364     if (InOverloadResolution)
9365       S.Diag(FD->getLocation(),
9366              diag::note_ovl_candidate_has_pass_object_size_params)
9367           << ParamNo;
9368     else
9369       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9370           << FD << ParamNo;
9371   }
9372   return false;
9373 }
9374 
9375 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9376                                                const FunctionDecl *FD) {
9377   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9378                                            /*InOverloadResolution=*/true,
9379                                            /*Loc=*/SourceLocation());
9380 }
9381 
9382 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9383                                              bool Complain,
9384                                              SourceLocation Loc) {
9385   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9386                                              /*InOverloadResolution=*/false,
9387                                              Loc);
9388 }
9389 
9390 // Notes the location of an overload candidate.
9391 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9392                                  QualType DestType, bool TakingAddress) {
9393   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9394     return;
9395 
9396   std::string FnDesc;
9397   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9398   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9399                              << (unsigned) K << Fn << FnDesc;
9400 
9401   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9402   Diag(Fn->getLocation(), PD);
9403   MaybeEmitInheritedConstructorNote(*this, Found);
9404 }
9405 
9406 // Notes the location of all overload candidates designated through
9407 // OverloadedExpr
9408 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9409                                      bool TakingAddress) {
9410   assert(OverloadedExpr->getType() == Context.OverloadTy);
9411 
9412   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9413   OverloadExpr *OvlExpr = Ovl.Expression;
9414 
9415   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9416                             IEnd = OvlExpr->decls_end();
9417        I != IEnd; ++I) {
9418     if (FunctionTemplateDecl *FunTmpl =
9419                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9420       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9421                             TakingAddress);
9422     } else if (FunctionDecl *Fun
9423                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9424       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9425     }
9426   }
9427 }
9428 
9429 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9430 /// "lead" diagnostic; it will be given two arguments, the source and
9431 /// target types of the conversion.
9432 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9433                                  Sema &S,
9434                                  SourceLocation CaretLoc,
9435                                  const PartialDiagnostic &PDiag) const {
9436   S.Diag(CaretLoc, PDiag)
9437     << Ambiguous.getFromType() << Ambiguous.getToType();
9438   // FIXME: The note limiting machinery is borrowed from
9439   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9440   // refactoring here.
9441   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9442   unsigned CandsShown = 0;
9443   AmbiguousConversionSequence::const_iterator I, E;
9444   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9445     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9446       break;
9447     ++CandsShown;
9448     S.NoteOverloadCandidate(I->first, I->second);
9449   }
9450   if (I != E)
9451     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9452 }
9453 
9454 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9455                                   unsigned I, bool TakingCandidateAddress) {
9456   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9457   assert(Conv.isBad());
9458   assert(Cand->Function && "for now, candidate must be a function");
9459   FunctionDecl *Fn = Cand->Function;
9460 
9461   // There's a conversion slot for the object argument if this is a
9462   // non-constructor method.  Note that 'I' corresponds the
9463   // conversion-slot index.
9464   bool isObjectArgument = false;
9465   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9466     if (I == 0)
9467       isObjectArgument = true;
9468     else
9469       I--;
9470   }
9471 
9472   std::string FnDesc;
9473   OverloadCandidateKind FnKind =
9474       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9475 
9476   Expr *FromExpr = Conv.Bad.FromExpr;
9477   QualType FromTy = Conv.Bad.getFromType();
9478   QualType ToTy = Conv.Bad.getToType();
9479 
9480   if (FromTy == S.Context.OverloadTy) {
9481     assert(FromExpr && "overload set argument came from implicit argument?");
9482     Expr *E = FromExpr->IgnoreParens();
9483     if (isa<UnaryOperator>(E))
9484       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9485     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9486 
9487     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9488       << (unsigned) FnKind << FnDesc
9489       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9490       << ToTy << Name << I+1;
9491     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9492     return;
9493   }
9494 
9495   // Do some hand-waving analysis to see if the non-viability is due
9496   // to a qualifier mismatch.
9497   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9498   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9499   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9500     CToTy = RT->getPointeeType();
9501   else {
9502     // TODO: detect and diagnose the full richness of const mismatches.
9503     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9504       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9505         CFromTy = FromPT->getPointeeType();
9506         CToTy = ToPT->getPointeeType();
9507       }
9508   }
9509 
9510   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9511       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9512     Qualifiers FromQs = CFromTy.getQualifiers();
9513     Qualifiers ToQs = CToTy.getQualifiers();
9514 
9515     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9516       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9517         << (unsigned) FnKind << FnDesc
9518         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9519         << FromTy
9520         << FromQs.getAddressSpaceAttributePrintValue()
9521         << ToQs.getAddressSpaceAttributePrintValue()
9522         << (unsigned) isObjectArgument << I+1;
9523       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9524       return;
9525     }
9526 
9527     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9528       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9529         << (unsigned) FnKind << FnDesc
9530         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9531         << FromTy
9532         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9533         << (unsigned) isObjectArgument << I+1;
9534       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9535       return;
9536     }
9537 
9538     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9539       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9540       << (unsigned) FnKind << FnDesc
9541       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9542       << FromTy
9543       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9544       << (unsigned) isObjectArgument << I+1;
9545       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9546       return;
9547     }
9548 
9549     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9550       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9551         << (unsigned) FnKind << FnDesc
9552         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9553         << FromTy << FromQs.hasUnaligned() << I+1;
9554       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9555       return;
9556     }
9557 
9558     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9559     assert(CVR && "unexpected qualifiers mismatch");
9560 
9561     if (isObjectArgument) {
9562       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9563         << (unsigned) FnKind << FnDesc
9564         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9565         << FromTy << (CVR - 1);
9566     } else {
9567       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9568         << (unsigned) FnKind << FnDesc
9569         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9570         << FromTy << (CVR - 1) << I+1;
9571     }
9572     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9573     return;
9574   }
9575 
9576   // Special diagnostic for failure to convert an initializer list, since
9577   // telling the user that it has type void is not useful.
9578   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9579     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9580       << (unsigned) FnKind << FnDesc
9581       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9582       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9583     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9584     return;
9585   }
9586 
9587   // Diagnose references or pointers to incomplete types differently,
9588   // since it's far from impossible that the incompleteness triggered
9589   // the failure.
9590   QualType TempFromTy = FromTy.getNonReferenceType();
9591   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9592     TempFromTy = PTy->getPointeeType();
9593   if (TempFromTy->isIncompleteType()) {
9594     // Emit the generic diagnostic and, optionally, add the hints to it.
9595     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9596       << (unsigned) FnKind << FnDesc
9597       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9598       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9599       << (unsigned) (Cand->Fix.Kind);
9600 
9601     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9602     return;
9603   }
9604 
9605   // Diagnose base -> derived pointer conversions.
9606   unsigned BaseToDerivedConversion = 0;
9607   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9608     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9609       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9610                                                FromPtrTy->getPointeeType()) &&
9611           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9612           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9613           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9614                           FromPtrTy->getPointeeType()))
9615         BaseToDerivedConversion = 1;
9616     }
9617   } else if (const ObjCObjectPointerType *FromPtrTy
9618                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9619     if (const ObjCObjectPointerType *ToPtrTy
9620                                         = ToTy->getAs<ObjCObjectPointerType>())
9621       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9622         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9623           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9624                                                 FromPtrTy->getPointeeType()) &&
9625               FromIface->isSuperClassOf(ToIface))
9626             BaseToDerivedConversion = 2;
9627   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9628     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9629         !FromTy->isIncompleteType() &&
9630         !ToRefTy->getPointeeType()->isIncompleteType() &&
9631         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9632       BaseToDerivedConversion = 3;
9633     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9634                ToTy.getNonReferenceType().getCanonicalType() ==
9635                FromTy.getNonReferenceType().getCanonicalType()) {
9636       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9637         << (unsigned) FnKind << FnDesc
9638         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9639         << (unsigned) isObjectArgument << I + 1;
9640       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9641       return;
9642     }
9643   }
9644 
9645   if (BaseToDerivedConversion) {
9646     S.Diag(Fn->getLocation(),
9647            diag::note_ovl_candidate_bad_base_to_derived_conv)
9648       << (unsigned) FnKind << FnDesc
9649       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9650       << (BaseToDerivedConversion - 1)
9651       << FromTy << ToTy << I+1;
9652     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9653     return;
9654   }
9655 
9656   if (isa<ObjCObjectPointerType>(CFromTy) &&
9657       isa<PointerType>(CToTy)) {
9658       Qualifiers FromQs = CFromTy.getQualifiers();
9659       Qualifiers ToQs = CToTy.getQualifiers();
9660       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9661         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9662         << (unsigned) FnKind << FnDesc
9663         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9664         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9665         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9666         return;
9667       }
9668   }
9669 
9670   if (TakingCandidateAddress &&
9671       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9672     return;
9673 
9674   // Emit the generic diagnostic and, optionally, add the hints to it.
9675   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9676   FDiag << (unsigned) FnKind << FnDesc
9677     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9678     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9679     << (unsigned) (Cand->Fix.Kind);
9680 
9681   // If we can fix the conversion, suggest the FixIts.
9682   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9683        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9684     FDiag << *HI;
9685   S.Diag(Fn->getLocation(), FDiag);
9686 
9687   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9688 }
9689 
9690 /// Additional arity mismatch diagnosis specific to a function overload
9691 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9692 /// over a candidate in any candidate set.
9693 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9694                                unsigned NumArgs) {
9695   FunctionDecl *Fn = Cand->Function;
9696   unsigned MinParams = Fn->getMinRequiredArguments();
9697 
9698   // With invalid overloaded operators, it's possible that we think we
9699   // have an arity mismatch when in fact it looks like we have the
9700   // right number of arguments, because only overloaded operators have
9701   // the weird behavior of overloading member and non-member functions.
9702   // Just don't report anything.
9703   if (Fn->isInvalidDecl() &&
9704       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9705     return true;
9706 
9707   if (NumArgs < MinParams) {
9708     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9709            (Cand->FailureKind == ovl_fail_bad_deduction &&
9710             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9711   } else {
9712     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9713            (Cand->FailureKind == ovl_fail_bad_deduction &&
9714             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9715   }
9716 
9717   return false;
9718 }
9719 
9720 /// General arity mismatch diagnosis over a candidate in a candidate set.
9721 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9722                                   unsigned NumFormalArgs) {
9723   assert(isa<FunctionDecl>(D) &&
9724       "The templated declaration should at least be a function"
9725       " when diagnosing bad template argument deduction due to too many"
9726       " or too few arguments");
9727 
9728   FunctionDecl *Fn = cast<FunctionDecl>(D);
9729 
9730   // TODO: treat calls to a missing default constructor as a special case
9731   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9732   unsigned MinParams = Fn->getMinRequiredArguments();
9733 
9734   // at least / at most / exactly
9735   unsigned mode, modeCount;
9736   if (NumFormalArgs < MinParams) {
9737     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9738         FnTy->isTemplateVariadic())
9739       mode = 0; // "at least"
9740     else
9741       mode = 2; // "exactly"
9742     modeCount = MinParams;
9743   } else {
9744     if (MinParams != FnTy->getNumParams())
9745       mode = 1; // "at most"
9746     else
9747       mode = 2; // "exactly"
9748     modeCount = FnTy->getNumParams();
9749   }
9750 
9751   std::string Description;
9752   OverloadCandidateKind FnKind =
9753       ClassifyOverloadCandidate(S, Found, Fn, Description);
9754 
9755   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9756     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9757       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9758       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9759   else
9760     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9761       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9762       << mode << modeCount << NumFormalArgs;
9763   MaybeEmitInheritedConstructorNote(S, Found);
9764 }
9765 
9766 /// Arity mismatch diagnosis specific to a function overload candidate.
9767 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9768                                   unsigned NumFormalArgs) {
9769   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9770     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9771 }
9772 
9773 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9774   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9775     return TD;
9776   llvm_unreachable("Unsupported: Getting the described template declaration"
9777                    " for bad deduction diagnosis");
9778 }
9779 
9780 /// Diagnose a failed template-argument deduction.
9781 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9782                                  DeductionFailureInfo &DeductionFailure,
9783                                  unsigned NumArgs,
9784                                  bool TakingCandidateAddress) {
9785   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9786   NamedDecl *ParamD;
9787   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9788   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9789   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9790   switch (DeductionFailure.Result) {
9791   case Sema::TDK_Success:
9792     llvm_unreachable("TDK_success while diagnosing bad deduction");
9793 
9794   case Sema::TDK_Incomplete: {
9795     assert(ParamD && "no parameter found for incomplete deduction result");
9796     S.Diag(Templated->getLocation(),
9797            diag::note_ovl_candidate_incomplete_deduction)
9798         << ParamD->getDeclName();
9799     MaybeEmitInheritedConstructorNote(S, Found);
9800     return;
9801   }
9802 
9803   case Sema::TDK_Underqualified: {
9804     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9805     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9806 
9807     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9808 
9809     // Param will have been canonicalized, but it should just be a
9810     // qualified version of ParamD, so move the qualifiers to that.
9811     QualifierCollector Qs;
9812     Qs.strip(Param);
9813     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9814     assert(S.Context.hasSameType(Param, NonCanonParam));
9815 
9816     // Arg has also been canonicalized, but there's nothing we can do
9817     // about that.  It also doesn't matter as much, because it won't
9818     // have any template parameters in it (because deduction isn't
9819     // done on dependent types).
9820     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9821 
9822     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9823         << ParamD->getDeclName() << Arg << NonCanonParam;
9824     MaybeEmitInheritedConstructorNote(S, Found);
9825     return;
9826   }
9827 
9828   case Sema::TDK_Inconsistent: {
9829     assert(ParamD && "no parameter found for inconsistent deduction result");
9830     int which = 0;
9831     if (isa<TemplateTypeParmDecl>(ParamD))
9832       which = 0;
9833     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9834       // Deduction might have failed because we deduced arguments of two
9835       // different types for a non-type template parameter.
9836       // FIXME: Use a different TDK value for this.
9837       QualType T1 =
9838           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9839       QualType T2 =
9840           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9841       if (!S.Context.hasSameType(T1, T2)) {
9842         S.Diag(Templated->getLocation(),
9843                diag::note_ovl_candidate_inconsistent_deduction_types)
9844           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9845           << *DeductionFailure.getSecondArg() << T2;
9846         MaybeEmitInheritedConstructorNote(S, Found);
9847         return;
9848       }
9849 
9850       which = 1;
9851     } else {
9852       which = 2;
9853     }
9854 
9855     S.Diag(Templated->getLocation(),
9856            diag::note_ovl_candidate_inconsistent_deduction)
9857         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9858         << *DeductionFailure.getSecondArg();
9859     MaybeEmitInheritedConstructorNote(S, Found);
9860     return;
9861   }
9862 
9863   case Sema::TDK_InvalidExplicitArguments:
9864     assert(ParamD && "no parameter found for invalid explicit arguments");
9865     if (ParamD->getDeclName())
9866       S.Diag(Templated->getLocation(),
9867              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9868           << ParamD->getDeclName();
9869     else {
9870       int index = 0;
9871       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9872         index = TTP->getIndex();
9873       else if (NonTypeTemplateParmDecl *NTTP
9874                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9875         index = NTTP->getIndex();
9876       else
9877         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9878       S.Diag(Templated->getLocation(),
9879              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9880           << (index + 1);
9881     }
9882     MaybeEmitInheritedConstructorNote(S, Found);
9883     return;
9884 
9885   case Sema::TDK_TooManyArguments:
9886   case Sema::TDK_TooFewArguments:
9887     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9888     return;
9889 
9890   case Sema::TDK_InstantiationDepth:
9891     S.Diag(Templated->getLocation(),
9892            diag::note_ovl_candidate_instantiation_depth);
9893     MaybeEmitInheritedConstructorNote(S, Found);
9894     return;
9895 
9896   case Sema::TDK_SubstitutionFailure: {
9897     // Format the template argument list into the argument string.
9898     SmallString<128> TemplateArgString;
9899     if (TemplateArgumentList *Args =
9900             DeductionFailure.getTemplateArgumentList()) {
9901       TemplateArgString = " ";
9902       TemplateArgString += S.getTemplateArgumentBindingsText(
9903           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9904     }
9905 
9906     // If this candidate was disabled by enable_if, say so.
9907     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9908     if (PDiag && PDiag->second.getDiagID() ==
9909           diag::err_typename_nested_not_found_enable_if) {
9910       // FIXME: Use the source range of the condition, and the fully-qualified
9911       //        name of the enable_if template. These are both present in PDiag.
9912       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9913         << "'enable_if'" << TemplateArgString;
9914       return;
9915     }
9916 
9917     // We found a specific requirement that disabled the enable_if.
9918     if (PDiag && PDiag->second.getDiagID() ==
9919         diag::err_typename_nested_not_found_requirement) {
9920       S.Diag(Templated->getLocation(),
9921              diag::note_ovl_candidate_disabled_by_requirement)
9922         << PDiag->second.getStringArg(0) << TemplateArgString;
9923       return;
9924     }
9925 
9926     // Format the SFINAE diagnostic into the argument string.
9927     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9928     //        formatted message in another diagnostic.
9929     SmallString<128> SFINAEArgString;
9930     SourceRange R;
9931     if (PDiag) {
9932       SFINAEArgString = ": ";
9933       R = SourceRange(PDiag->first, PDiag->first);
9934       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9935     }
9936 
9937     S.Diag(Templated->getLocation(),
9938            diag::note_ovl_candidate_substitution_failure)
9939         << TemplateArgString << SFINAEArgString << R;
9940     MaybeEmitInheritedConstructorNote(S, Found);
9941     return;
9942   }
9943 
9944   case Sema::TDK_DeducedMismatch:
9945   case Sema::TDK_DeducedMismatchNested: {
9946     // Format the template argument list into the argument string.
9947     SmallString<128> TemplateArgString;
9948     if (TemplateArgumentList *Args =
9949             DeductionFailure.getTemplateArgumentList()) {
9950       TemplateArgString = " ";
9951       TemplateArgString += S.getTemplateArgumentBindingsText(
9952           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9953     }
9954 
9955     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9956         << (*DeductionFailure.getCallArgIndex() + 1)
9957         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9958         << TemplateArgString
9959         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9960     break;
9961   }
9962 
9963   case Sema::TDK_NonDeducedMismatch: {
9964     // FIXME: Provide a source location to indicate what we couldn't match.
9965     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9966     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9967     if (FirstTA.getKind() == TemplateArgument::Template &&
9968         SecondTA.getKind() == TemplateArgument::Template) {
9969       TemplateName FirstTN = FirstTA.getAsTemplate();
9970       TemplateName SecondTN = SecondTA.getAsTemplate();
9971       if (FirstTN.getKind() == TemplateName::Template &&
9972           SecondTN.getKind() == TemplateName::Template) {
9973         if (FirstTN.getAsTemplateDecl()->getName() ==
9974             SecondTN.getAsTemplateDecl()->getName()) {
9975           // FIXME: This fixes a bad diagnostic where both templates are named
9976           // the same.  This particular case is a bit difficult since:
9977           // 1) It is passed as a string to the diagnostic printer.
9978           // 2) The diagnostic printer only attempts to find a better
9979           //    name for types, not decls.
9980           // Ideally, this should folded into the diagnostic printer.
9981           S.Diag(Templated->getLocation(),
9982                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9983               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9984           return;
9985         }
9986       }
9987     }
9988 
9989     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9990         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9991       return;
9992 
9993     // FIXME: For generic lambda parameters, check if the function is a lambda
9994     // call operator, and if so, emit a prettier and more informative
9995     // diagnostic that mentions 'auto' and lambda in addition to
9996     // (or instead of?) the canonical template type parameters.
9997     S.Diag(Templated->getLocation(),
9998            diag::note_ovl_candidate_non_deduced_mismatch)
9999         << FirstTA << SecondTA;
10000     return;
10001   }
10002   // TODO: diagnose these individually, then kill off
10003   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10004   case Sema::TDK_MiscellaneousDeductionFailure:
10005     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10006     MaybeEmitInheritedConstructorNote(S, Found);
10007     return;
10008   case Sema::TDK_CUDATargetMismatch:
10009     S.Diag(Templated->getLocation(),
10010            diag::note_cuda_ovl_candidate_target_mismatch);
10011     return;
10012   }
10013 }
10014 
10015 /// Diagnose a failed template-argument deduction, for function calls.
10016 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10017                                  unsigned NumArgs,
10018                                  bool TakingCandidateAddress) {
10019   unsigned TDK = Cand->DeductionFailure.Result;
10020   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10021     if (CheckArityMismatch(S, Cand, NumArgs))
10022       return;
10023   }
10024   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10025                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10026 }
10027 
10028 /// CUDA: diagnose an invalid call across targets.
10029 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10030   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10031   FunctionDecl *Callee = Cand->Function;
10032 
10033   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10034                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10035 
10036   std::string FnDesc;
10037   OverloadCandidateKind FnKind =
10038       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10039 
10040   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10041       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10042 
10043   // This could be an implicit constructor for which we could not infer the
10044   // target due to a collsion. Diagnose that case.
10045   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10046   if (Meth != nullptr && Meth->isImplicit()) {
10047     CXXRecordDecl *ParentClass = Meth->getParent();
10048     Sema::CXXSpecialMember CSM;
10049 
10050     switch (FnKind) {
10051     default:
10052       return;
10053     case oc_implicit_default_constructor:
10054       CSM = Sema::CXXDefaultConstructor;
10055       break;
10056     case oc_implicit_copy_constructor:
10057       CSM = Sema::CXXCopyConstructor;
10058       break;
10059     case oc_implicit_move_constructor:
10060       CSM = Sema::CXXMoveConstructor;
10061       break;
10062     case oc_implicit_copy_assignment:
10063       CSM = Sema::CXXCopyAssignment;
10064       break;
10065     case oc_implicit_move_assignment:
10066       CSM = Sema::CXXMoveAssignment;
10067       break;
10068     };
10069 
10070     bool ConstRHS = false;
10071     if (Meth->getNumParams()) {
10072       if (const ReferenceType *RT =
10073               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10074         ConstRHS = RT->getPointeeType().isConstQualified();
10075       }
10076     }
10077 
10078     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10079                                               /* ConstRHS */ ConstRHS,
10080                                               /* Diagnose */ true);
10081   }
10082 }
10083 
10084 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10085   FunctionDecl *Callee = Cand->Function;
10086   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10087 
10088   S.Diag(Callee->getLocation(),
10089          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10090       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10091 }
10092 
10093 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10094   FunctionDecl *Callee = Cand->Function;
10095 
10096   S.Diag(Callee->getLocation(),
10097          diag::note_ovl_candidate_disabled_by_extension);
10098 }
10099 
10100 /// Generates a 'note' diagnostic for an overload candidate.  We've
10101 /// already generated a primary error at the call site.
10102 ///
10103 /// It really does need to be a single diagnostic with its caret
10104 /// pointed at the candidate declaration.  Yes, this creates some
10105 /// major challenges of technical writing.  Yes, this makes pointing
10106 /// out problems with specific arguments quite awkward.  It's still
10107 /// better than generating twenty screens of text for every failed
10108 /// overload.
10109 ///
10110 /// It would be great to be able to express per-candidate problems
10111 /// more richly for those diagnostic clients that cared, but we'd
10112 /// still have to be just as careful with the default diagnostics.
10113 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10114                                   unsigned NumArgs,
10115                                   bool TakingCandidateAddress) {
10116   FunctionDecl *Fn = Cand->Function;
10117 
10118   // Note deleted candidates, but only if they're viable.
10119   if (Cand->Viable) {
10120     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10121       std::string FnDesc;
10122       OverloadCandidateKind FnKind =
10123         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10124 
10125       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10126         << FnKind << FnDesc
10127         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10128       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10129       return;
10130     }
10131 
10132     // We don't really have anything else to say about viable candidates.
10133     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10134     return;
10135   }
10136 
10137   switch (Cand->FailureKind) {
10138   case ovl_fail_too_many_arguments:
10139   case ovl_fail_too_few_arguments:
10140     return DiagnoseArityMismatch(S, Cand, NumArgs);
10141 
10142   case ovl_fail_bad_deduction:
10143     return DiagnoseBadDeduction(S, Cand, NumArgs,
10144                                 TakingCandidateAddress);
10145 
10146   case ovl_fail_illegal_constructor: {
10147     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10148       << (Fn->getPrimaryTemplate() ? 1 : 0);
10149     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10150     return;
10151   }
10152 
10153   case ovl_fail_trivial_conversion:
10154   case ovl_fail_bad_final_conversion:
10155   case ovl_fail_final_conversion_not_exact:
10156     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10157 
10158   case ovl_fail_bad_conversion: {
10159     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10160     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10161       if (Cand->Conversions[I].isBad())
10162         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10163 
10164     // FIXME: this currently happens when we're called from SemaInit
10165     // when user-conversion overload fails.  Figure out how to handle
10166     // those conditions and diagnose them well.
10167     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10168   }
10169 
10170   case ovl_fail_bad_target:
10171     return DiagnoseBadTarget(S, Cand);
10172 
10173   case ovl_fail_enable_if:
10174     return DiagnoseFailedEnableIfAttr(S, Cand);
10175 
10176   case ovl_fail_ext_disabled:
10177     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10178 
10179   case ovl_fail_inhctor_slice:
10180     // It's generally not interesting to note copy/move constructors here.
10181     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10182       return;
10183     S.Diag(Fn->getLocation(),
10184            diag::note_ovl_candidate_inherited_constructor_slice)
10185       << (Fn->getPrimaryTemplate() ? 1 : 0)
10186       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10187     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10188     return;
10189 
10190   case ovl_fail_addr_not_available: {
10191     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10192     (void)Available;
10193     assert(!Available);
10194     break;
10195   }
10196   }
10197 }
10198 
10199 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10200   // Desugar the type of the surrogate down to a function type,
10201   // retaining as many typedefs as possible while still showing
10202   // the function type (and, therefore, its parameter types).
10203   QualType FnType = Cand->Surrogate->getConversionType();
10204   bool isLValueReference = false;
10205   bool isRValueReference = false;
10206   bool isPointer = false;
10207   if (const LValueReferenceType *FnTypeRef =
10208         FnType->getAs<LValueReferenceType>()) {
10209     FnType = FnTypeRef->getPointeeType();
10210     isLValueReference = true;
10211   } else if (const RValueReferenceType *FnTypeRef =
10212                FnType->getAs<RValueReferenceType>()) {
10213     FnType = FnTypeRef->getPointeeType();
10214     isRValueReference = true;
10215   }
10216   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10217     FnType = FnTypePtr->getPointeeType();
10218     isPointer = true;
10219   }
10220   // Desugar down to a function type.
10221   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10222   // Reconstruct the pointer/reference as appropriate.
10223   if (isPointer) FnType = S.Context.getPointerType(FnType);
10224   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10225   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10226 
10227   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10228     << FnType;
10229 }
10230 
10231 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10232                                          SourceLocation OpLoc,
10233                                          OverloadCandidate *Cand) {
10234   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10235   std::string TypeStr("operator");
10236   TypeStr += Opc;
10237   TypeStr += "(";
10238   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10239   if (Cand->Conversions.size() == 1) {
10240     TypeStr += ")";
10241     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10242   } else {
10243     TypeStr += ", ";
10244     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10245     TypeStr += ")";
10246     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10247   }
10248 }
10249 
10250 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10251                                          OverloadCandidate *Cand) {
10252   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10253     if (ICS.isBad()) break; // all meaningless after first invalid
10254     if (!ICS.isAmbiguous()) continue;
10255 
10256     ICS.DiagnoseAmbiguousConversion(
10257         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10258   }
10259 }
10260 
10261 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10262   if (Cand->Function)
10263     return Cand->Function->getLocation();
10264   if (Cand->IsSurrogate)
10265     return Cand->Surrogate->getLocation();
10266   return SourceLocation();
10267 }
10268 
10269 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10270   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10271   case Sema::TDK_Success:
10272   case Sema::TDK_NonDependentConversionFailure:
10273     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10274 
10275   case Sema::TDK_Invalid:
10276   case Sema::TDK_Incomplete:
10277     return 1;
10278 
10279   case Sema::TDK_Underqualified:
10280   case Sema::TDK_Inconsistent:
10281     return 2;
10282 
10283   case Sema::TDK_SubstitutionFailure:
10284   case Sema::TDK_DeducedMismatch:
10285   case Sema::TDK_DeducedMismatchNested:
10286   case Sema::TDK_NonDeducedMismatch:
10287   case Sema::TDK_MiscellaneousDeductionFailure:
10288   case Sema::TDK_CUDATargetMismatch:
10289     return 3;
10290 
10291   case Sema::TDK_InstantiationDepth:
10292     return 4;
10293 
10294   case Sema::TDK_InvalidExplicitArguments:
10295     return 5;
10296 
10297   case Sema::TDK_TooManyArguments:
10298   case Sema::TDK_TooFewArguments:
10299     return 6;
10300   }
10301   llvm_unreachable("Unhandled deduction result");
10302 }
10303 
10304 namespace {
10305 struct CompareOverloadCandidatesForDisplay {
10306   Sema &S;
10307   SourceLocation Loc;
10308   size_t NumArgs;
10309   OverloadCandidateSet::CandidateSetKind CSK;
10310 
10311   CompareOverloadCandidatesForDisplay(
10312       Sema &S, SourceLocation Loc, size_t NArgs,
10313       OverloadCandidateSet::CandidateSetKind CSK)
10314       : S(S), NumArgs(NArgs), CSK(CSK) {}
10315 
10316   bool operator()(const OverloadCandidate *L,
10317                   const OverloadCandidate *R) {
10318     // Fast-path this check.
10319     if (L == R) return false;
10320 
10321     // Order first by viability.
10322     if (L->Viable) {
10323       if (!R->Viable) return true;
10324 
10325       // TODO: introduce a tri-valued comparison for overload
10326       // candidates.  Would be more worthwhile if we had a sort
10327       // that could exploit it.
10328       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10329         return true;
10330       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10331         return false;
10332     } else if (R->Viable)
10333       return false;
10334 
10335     assert(L->Viable == R->Viable);
10336 
10337     // Criteria by which we can sort non-viable candidates:
10338     if (!L->Viable) {
10339       // 1. Arity mismatches come after other candidates.
10340       if (L->FailureKind == ovl_fail_too_many_arguments ||
10341           L->FailureKind == ovl_fail_too_few_arguments) {
10342         if (R->FailureKind == ovl_fail_too_many_arguments ||
10343             R->FailureKind == ovl_fail_too_few_arguments) {
10344           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10345           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10346           if (LDist == RDist) {
10347             if (L->FailureKind == R->FailureKind)
10348               // Sort non-surrogates before surrogates.
10349               return !L->IsSurrogate && R->IsSurrogate;
10350             // Sort candidates requiring fewer parameters than there were
10351             // arguments given after candidates requiring more parameters
10352             // than there were arguments given.
10353             return L->FailureKind == ovl_fail_too_many_arguments;
10354           }
10355           return LDist < RDist;
10356         }
10357         return false;
10358       }
10359       if (R->FailureKind == ovl_fail_too_many_arguments ||
10360           R->FailureKind == ovl_fail_too_few_arguments)
10361         return true;
10362 
10363       // 2. Bad conversions come first and are ordered by the number
10364       // of bad conversions and quality of good conversions.
10365       if (L->FailureKind == ovl_fail_bad_conversion) {
10366         if (R->FailureKind != ovl_fail_bad_conversion)
10367           return true;
10368 
10369         // The conversion that can be fixed with a smaller number of changes,
10370         // comes first.
10371         unsigned numLFixes = L->Fix.NumConversionsFixed;
10372         unsigned numRFixes = R->Fix.NumConversionsFixed;
10373         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10374         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10375         if (numLFixes != numRFixes) {
10376           return numLFixes < numRFixes;
10377         }
10378 
10379         // If there's any ordering between the defined conversions...
10380         // FIXME: this might not be transitive.
10381         assert(L->Conversions.size() == R->Conversions.size());
10382 
10383         int leftBetter = 0;
10384         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10385         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10386           switch (CompareImplicitConversionSequences(S, Loc,
10387                                                      L->Conversions[I],
10388                                                      R->Conversions[I])) {
10389           case ImplicitConversionSequence::Better:
10390             leftBetter++;
10391             break;
10392 
10393           case ImplicitConversionSequence::Worse:
10394             leftBetter--;
10395             break;
10396 
10397           case ImplicitConversionSequence::Indistinguishable:
10398             break;
10399           }
10400         }
10401         if (leftBetter > 0) return true;
10402         if (leftBetter < 0) return false;
10403 
10404       } else if (R->FailureKind == ovl_fail_bad_conversion)
10405         return false;
10406 
10407       if (L->FailureKind == ovl_fail_bad_deduction) {
10408         if (R->FailureKind != ovl_fail_bad_deduction)
10409           return true;
10410 
10411         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10412           return RankDeductionFailure(L->DeductionFailure)
10413                < RankDeductionFailure(R->DeductionFailure);
10414       } else if (R->FailureKind == ovl_fail_bad_deduction)
10415         return false;
10416 
10417       // TODO: others?
10418     }
10419 
10420     // Sort everything else by location.
10421     SourceLocation LLoc = GetLocationForCandidate(L);
10422     SourceLocation RLoc = GetLocationForCandidate(R);
10423 
10424     // Put candidates without locations (e.g. builtins) at the end.
10425     if (LLoc.isInvalid()) return false;
10426     if (RLoc.isInvalid()) return true;
10427 
10428     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10429   }
10430 };
10431 }
10432 
10433 /// CompleteNonViableCandidate - Normally, overload resolution only
10434 /// computes up to the first bad conversion. Produces the FixIt set if
10435 /// possible.
10436 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10437                                        ArrayRef<Expr *> Args) {
10438   assert(!Cand->Viable);
10439 
10440   // Don't do anything on failures other than bad conversion.
10441   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10442 
10443   // We only want the FixIts if all the arguments can be corrected.
10444   bool Unfixable = false;
10445   // Use a implicit copy initialization to check conversion fixes.
10446   Cand->Fix.setConversionChecker(TryCopyInitialization);
10447 
10448   // Attempt to fix the bad conversion.
10449   unsigned ConvCount = Cand->Conversions.size();
10450   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10451        ++ConvIdx) {
10452     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10453     if (Cand->Conversions[ConvIdx].isInitialized() &&
10454         Cand->Conversions[ConvIdx].isBad()) {
10455       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10456       break;
10457     }
10458   }
10459 
10460   // FIXME: this should probably be preserved from the overload
10461   // operation somehow.
10462   bool SuppressUserConversions = false;
10463 
10464   unsigned ConvIdx = 0;
10465   ArrayRef<QualType> ParamTypes;
10466 
10467   if (Cand->IsSurrogate) {
10468     QualType ConvType
10469       = Cand->Surrogate->getConversionType().getNonReferenceType();
10470     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10471       ConvType = ConvPtrType->getPointeeType();
10472     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10473     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10474     ConvIdx = 1;
10475   } else if (Cand->Function) {
10476     ParamTypes =
10477         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10478     if (isa<CXXMethodDecl>(Cand->Function) &&
10479         !isa<CXXConstructorDecl>(Cand->Function)) {
10480       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10481       ConvIdx = 1;
10482     }
10483   } else {
10484     // Builtin operator.
10485     assert(ConvCount <= 3);
10486     ParamTypes = Cand->BuiltinParamTypes;
10487   }
10488 
10489   // Fill in the rest of the conversions.
10490   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10491     if (Cand->Conversions[ConvIdx].isInitialized()) {
10492       // We've already checked this conversion.
10493     } else if (ArgIdx < ParamTypes.size()) {
10494       if (ParamTypes[ArgIdx]->isDependentType())
10495         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10496             Args[ArgIdx]->getType());
10497       else {
10498         Cand->Conversions[ConvIdx] =
10499             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10500                                   SuppressUserConversions,
10501                                   /*InOverloadResolution=*/true,
10502                                   /*AllowObjCWritebackConversion=*/
10503                                   S.getLangOpts().ObjCAutoRefCount);
10504         // Store the FixIt in the candidate if it exists.
10505         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10506           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10507       }
10508     } else
10509       Cand->Conversions[ConvIdx].setEllipsis();
10510   }
10511 }
10512 
10513 /// PrintOverloadCandidates - When overload resolution fails, prints
10514 /// diagnostic messages containing the candidates in the candidate
10515 /// set.
10516 void OverloadCandidateSet::NoteCandidates(
10517     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10518     StringRef Opc, SourceLocation OpLoc,
10519     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10520   // Sort the candidates by viability and position.  Sorting directly would
10521   // be prohibitive, so we make a set of pointers and sort those.
10522   SmallVector<OverloadCandidate*, 32> Cands;
10523   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10524   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10525     if (!Filter(*Cand))
10526       continue;
10527     if (Cand->Viable)
10528       Cands.push_back(Cand);
10529     else if (OCD == OCD_AllCandidates) {
10530       CompleteNonViableCandidate(S, Cand, Args);
10531       if (Cand->Function || Cand->IsSurrogate)
10532         Cands.push_back(Cand);
10533       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10534       // want to list every possible builtin candidate.
10535     }
10536   }
10537 
10538   std::stable_sort(Cands.begin(), Cands.end(),
10539             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10540 
10541   bool ReportedAmbiguousConversions = false;
10542 
10543   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10544   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10545   unsigned CandsShown = 0;
10546   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10547     OverloadCandidate *Cand = *I;
10548 
10549     // Set an arbitrary limit on the number of candidate functions we'll spam
10550     // the user with.  FIXME: This limit should depend on details of the
10551     // candidate list.
10552     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10553       break;
10554     }
10555     ++CandsShown;
10556 
10557     if (Cand->Function)
10558       NoteFunctionCandidate(S, Cand, Args.size(),
10559                             /*TakingCandidateAddress=*/false);
10560     else if (Cand->IsSurrogate)
10561       NoteSurrogateCandidate(S, Cand);
10562     else {
10563       assert(Cand->Viable &&
10564              "Non-viable built-in candidates are not added to Cands.");
10565       // Generally we only see ambiguities including viable builtin
10566       // operators if overload resolution got screwed up by an
10567       // ambiguous user-defined conversion.
10568       //
10569       // FIXME: It's quite possible for different conversions to see
10570       // different ambiguities, though.
10571       if (!ReportedAmbiguousConversions) {
10572         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10573         ReportedAmbiguousConversions = true;
10574       }
10575 
10576       // If this is a viable builtin, print it.
10577       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10578     }
10579   }
10580 
10581   if (I != E)
10582     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10583 }
10584 
10585 static SourceLocation
10586 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10587   return Cand->Specialization ? Cand->Specialization->getLocation()
10588                               : SourceLocation();
10589 }
10590 
10591 namespace {
10592 struct CompareTemplateSpecCandidatesForDisplay {
10593   Sema &S;
10594   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10595 
10596   bool operator()(const TemplateSpecCandidate *L,
10597                   const TemplateSpecCandidate *R) {
10598     // Fast-path this check.
10599     if (L == R)
10600       return false;
10601 
10602     // Assuming that both candidates are not matches...
10603 
10604     // Sort by the ranking of deduction failures.
10605     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10606       return RankDeductionFailure(L->DeductionFailure) <
10607              RankDeductionFailure(R->DeductionFailure);
10608 
10609     // Sort everything else by location.
10610     SourceLocation LLoc = GetLocationForCandidate(L);
10611     SourceLocation RLoc = GetLocationForCandidate(R);
10612 
10613     // Put candidates without locations (e.g. builtins) at the end.
10614     if (LLoc.isInvalid())
10615       return false;
10616     if (RLoc.isInvalid())
10617       return true;
10618 
10619     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10620   }
10621 };
10622 }
10623 
10624 /// Diagnose a template argument deduction failure.
10625 /// We are treating these failures as overload failures due to bad
10626 /// deductions.
10627 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10628                                                  bool ForTakingAddress) {
10629   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10630                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10631 }
10632 
10633 void TemplateSpecCandidateSet::destroyCandidates() {
10634   for (iterator i = begin(), e = end(); i != e; ++i) {
10635     i->DeductionFailure.Destroy();
10636   }
10637 }
10638 
10639 void TemplateSpecCandidateSet::clear() {
10640   destroyCandidates();
10641   Candidates.clear();
10642 }
10643 
10644 /// NoteCandidates - When no template specialization match is found, prints
10645 /// diagnostic messages containing the non-matching specializations that form
10646 /// the candidate set.
10647 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10648 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10649 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10650   // Sort the candidates by position (assuming no candidate is a match).
10651   // Sorting directly would be prohibitive, so we make a set of pointers
10652   // and sort those.
10653   SmallVector<TemplateSpecCandidate *, 32> Cands;
10654   Cands.reserve(size());
10655   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10656     if (Cand->Specialization)
10657       Cands.push_back(Cand);
10658     // Otherwise, this is a non-matching builtin candidate.  We do not,
10659     // in general, want to list every possible builtin candidate.
10660   }
10661 
10662   std::sort(Cands.begin(), Cands.end(),
10663             CompareTemplateSpecCandidatesForDisplay(S));
10664 
10665   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10666   // for generalization purposes (?).
10667   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10668 
10669   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10670   unsigned CandsShown = 0;
10671   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10672     TemplateSpecCandidate *Cand = *I;
10673 
10674     // Set an arbitrary limit on the number of candidates we'll spam
10675     // the user with.  FIXME: This limit should depend on details of the
10676     // candidate list.
10677     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10678       break;
10679     ++CandsShown;
10680 
10681     assert(Cand->Specialization &&
10682            "Non-matching built-in candidates are not added to Cands.");
10683     Cand->NoteDeductionFailure(S, ForTakingAddress);
10684   }
10685 
10686   if (I != E)
10687     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10688 }
10689 
10690 // [PossiblyAFunctionType]  -->   [Return]
10691 // NonFunctionType --> NonFunctionType
10692 // R (A) --> R(A)
10693 // R (*)(A) --> R (A)
10694 // R (&)(A) --> R (A)
10695 // R (S::*)(A) --> R (A)
10696 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10697   QualType Ret = PossiblyAFunctionType;
10698   if (const PointerType *ToTypePtr =
10699     PossiblyAFunctionType->getAs<PointerType>())
10700     Ret = ToTypePtr->getPointeeType();
10701   else if (const ReferenceType *ToTypeRef =
10702     PossiblyAFunctionType->getAs<ReferenceType>())
10703     Ret = ToTypeRef->getPointeeType();
10704   else if (const MemberPointerType *MemTypePtr =
10705     PossiblyAFunctionType->getAs<MemberPointerType>())
10706     Ret = MemTypePtr->getPointeeType();
10707   Ret =
10708     Context.getCanonicalType(Ret).getUnqualifiedType();
10709   return Ret;
10710 }
10711 
10712 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10713                                  bool Complain = true) {
10714   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10715       S.DeduceReturnType(FD, Loc, Complain))
10716     return true;
10717 
10718   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10719   if (S.getLangOpts().CPlusPlus17 &&
10720       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10721       !S.ResolveExceptionSpec(Loc, FPT))
10722     return true;
10723 
10724   return false;
10725 }
10726 
10727 namespace {
10728 // A helper class to help with address of function resolution
10729 // - allows us to avoid passing around all those ugly parameters
10730 class AddressOfFunctionResolver {
10731   Sema& S;
10732   Expr* SourceExpr;
10733   const QualType& TargetType;
10734   QualType TargetFunctionType; // Extracted function type from target type
10735 
10736   bool Complain;
10737   //DeclAccessPair& ResultFunctionAccessPair;
10738   ASTContext& Context;
10739 
10740   bool TargetTypeIsNonStaticMemberFunction;
10741   bool FoundNonTemplateFunction;
10742   bool StaticMemberFunctionFromBoundPointer;
10743   bool HasComplained;
10744 
10745   OverloadExpr::FindResult OvlExprInfo;
10746   OverloadExpr *OvlExpr;
10747   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10748   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10749   TemplateSpecCandidateSet FailedCandidates;
10750 
10751 public:
10752   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10753                             const QualType &TargetType, bool Complain)
10754       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10755         Complain(Complain), Context(S.getASTContext()),
10756         TargetTypeIsNonStaticMemberFunction(
10757             !!TargetType->getAs<MemberPointerType>()),
10758         FoundNonTemplateFunction(false),
10759         StaticMemberFunctionFromBoundPointer(false),
10760         HasComplained(false),
10761         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10762         OvlExpr(OvlExprInfo.Expression),
10763         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10764     ExtractUnqualifiedFunctionTypeFromTargetType();
10765 
10766     if (TargetFunctionType->isFunctionType()) {
10767       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10768         if (!UME->isImplicitAccess() &&
10769             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10770           StaticMemberFunctionFromBoundPointer = true;
10771     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10772       DeclAccessPair dap;
10773       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10774               OvlExpr, false, &dap)) {
10775         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10776           if (!Method->isStatic()) {
10777             // If the target type is a non-function type and the function found
10778             // is a non-static member function, pretend as if that was the
10779             // target, it's the only possible type to end up with.
10780             TargetTypeIsNonStaticMemberFunction = true;
10781 
10782             // And skip adding the function if its not in the proper form.
10783             // We'll diagnose this due to an empty set of functions.
10784             if (!OvlExprInfo.HasFormOfMemberPointer)
10785               return;
10786           }
10787 
10788         Matches.push_back(std::make_pair(dap, Fn));
10789       }
10790       return;
10791     }
10792 
10793     if (OvlExpr->hasExplicitTemplateArgs())
10794       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10795 
10796     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10797       // C++ [over.over]p4:
10798       //   If more than one function is selected, [...]
10799       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10800         if (FoundNonTemplateFunction)
10801           EliminateAllTemplateMatches();
10802         else
10803           EliminateAllExceptMostSpecializedTemplate();
10804       }
10805     }
10806 
10807     if (S.getLangOpts().CUDA && Matches.size() > 1)
10808       EliminateSuboptimalCudaMatches();
10809   }
10810 
10811   bool hasComplained() const { return HasComplained; }
10812 
10813 private:
10814   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10815     QualType Discard;
10816     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10817            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10818   }
10819 
10820   /// \return true if A is considered a better overload candidate for the
10821   /// desired type than B.
10822   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10823     // If A doesn't have exactly the correct type, we don't want to classify it
10824     // as "better" than anything else. This way, the user is required to
10825     // disambiguate for us if there are multiple candidates and no exact match.
10826     return candidateHasExactlyCorrectType(A) &&
10827            (!candidateHasExactlyCorrectType(B) ||
10828             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10829   }
10830 
10831   /// \return true if we were able to eliminate all but one overload candidate,
10832   /// false otherwise.
10833   bool eliminiateSuboptimalOverloadCandidates() {
10834     // Same algorithm as overload resolution -- one pass to pick the "best",
10835     // another pass to be sure that nothing is better than the best.
10836     auto Best = Matches.begin();
10837     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10838       if (isBetterCandidate(I->second, Best->second))
10839         Best = I;
10840 
10841     const FunctionDecl *BestFn = Best->second;
10842     auto IsBestOrInferiorToBest = [this, BestFn](
10843         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10844       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10845     };
10846 
10847     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10848     // option, so we can potentially give the user a better error
10849     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10850       return false;
10851     Matches[0] = *Best;
10852     Matches.resize(1);
10853     return true;
10854   }
10855 
10856   bool isTargetTypeAFunction() const {
10857     return TargetFunctionType->isFunctionType();
10858   }
10859 
10860   // [ToType]     [Return]
10861 
10862   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10863   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10864   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10865   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10866     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10867   }
10868 
10869   // return true if any matching specializations were found
10870   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10871                                    const DeclAccessPair& CurAccessFunPair) {
10872     if (CXXMethodDecl *Method
10873               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10874       // Skip non-static function templates when converting to pointer, and
10875       // static when converting to member pointer.
10876       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10877         return false;
10878     }
10879     else if (TargetTypeIsNonStaticMemberFunction)
10880       return false;
10881 
10882     // C++ [over.over]p2:
10883     //   If the name is a function template, template argument deduction is
10884     //   done (14.8.2.2), and if the argument deduction succeeds, the
10885     //   resulting template argument list is used to generate a single
10886     //   function template specialization, which is added to the set of
10887     //   overloaded functions considered.
10888     FunctionDecl *Specialization = nullptr;
10889     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10890     if (Sema::TemplateDeductionResult Result
10891           = S.DeduceTemplateArguments(FunctionTemplate,
10892                                       &OvlExplicitTemplateArgs,
10893                                       TargetFunctionType, Specialization,
10894                                       Info, /*IsAddressOfFunction*/true)) {
10895       // Make a note of the failed deduction for diagnostics.
10896       FailedCandidates.addCandidate()
10897           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10898                MakeDeductionFailureInfo(Context, Result, Info));
10899       return false;
10900     }
10901 
10902     // Template argument deduction ensures that we have an exact match or
10903     // compatible pointer-to-function arguments that would be adjusted by ICS.
10904     // This function template specicalization works.
10905     assert(S.isSameOrCompatibleFunctionType(
10906               Context.getCanonicalType(Specialization->getType()),
10907               Context.getCanonicalType(TargetFunctionType)));
10908 
10909     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10910       return false;
10911 
10912     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10913     return true;
10914   }
10915 
10916   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10917                                       const DeclAccessPair& CurAccessFunPair) {
10918     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10919       // Skip non-static functions when converting to pointer, and static
10920       // when converting to member pointer.
10921       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10922         return false;
10923     }
10924     else if (TargetTypeIsNonStaticMemberFunction)
10925       return false;
10926 
10927     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10928       if (S.getLangOpts().CUDA)
10929         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10930           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10931             return false;
10932 
10933       // If any candidate has a placeholder return type, trigger its deduction
10934       // now.
10935       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10936                                Complain)) {
10937         HasComplained |= Complain;
10938         return false;
10939       }
10940 
10941       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10942         return false;
10943 
10944       // If we're in C, we need to support types that aren't exactly identical.
10945       if (!S.getLangOpts().CPlusPlus ||
10946           candidateHasExactlyCorrectType(FunDecl)) {
10947         Matches.push_back(std::make_pair(
10948             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10949         FoundNonTemplateFunction = true;
10950         return true;
10951       }
10952     }
10953 
10954     return false;
10955   }
10956 
10957   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10958     bool Ret = false;
10959 
10960     // If the overload expression doesn't have the form of a pointer to
10961     // member, don't try to convert it to a pointer-to-member type.
10962     if (IsInvalidFormOfPointerToMemberFunction())
10963       return false;
10964 
10965     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10966                                E = OvlExpr->decls_end();
10967          I != E; ++I) {
10968       // Look through any using declarations to find the underlying function.
10969       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10970 
10971       // C++ [over.over]p3:
10972       //   Non-member functions and static member functions match
10973       //   targets of type "pointer-to-function" or "reference-to-function."
10974       //   Nonstatic member functions match targets of
10975       //   type "pointer-to-member-function."
10976       // Note that according to DR 247, the containing class does not matter.
10977       if (FunctionTemplateDecl *FunctionTemplate
10978                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10979         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10980           Ret = true;
10981       }
10982       // If we have explicit template arguments supplied, skip non-templates.
10983       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10984                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10985         Ret = true;
10986     }
10987     assert(Ret || Matches.empty());
10988     return Ret;
10989   }
10990 
10991   void EliminateAllExceptMostSpecializedTemplate() {
10992     //   [...] and any given function template specialization F1 is
10993     //   eliminated if the set contains a second function template
10994     //   specialization whose function template is more specialized
10995     //   than the function template of F1 according to the partial
10996     //   ordering rules of 14.5.5.2.
10997 
10998     // The algorithm specified above is quadratic. We instead use a
10999     // two-pass algorithm (similar to the one used to identify the
11000     // best viable function in an overload set) that identifies the
11001     // best function template (if it exists).
11002 
11003     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11004     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11005       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11006 
11007     // TODO: It looks like FailedCandidates does not serve much purpose
11008     // here, since the no_viable diagnostic has index 0.
11009     UnresolvedSetIterator Result = S.getMostSpecialized(
11010         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11011         SourceExpr->getLocStart(), S.PDiag(),
11012         S.PDiag(diag::err_addr_ovl_ambiguous)
11013           << Matches[0].second->getDeclName(),
11014         S.PDiag(diag::note_ovl_candidate)
11015           << (unsigned)oc_function_template,
11016         Complain, TargetFunctionType);
11017 
11018     if (Result != MatchesCopy.end()) {
11019       // Make it the first and only element
11020       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11021       Matches[0].second = cast<FunctionDecl>(*Result);
11022       Matches.resize(1);
11023     } else
11024       HasComplained |= Complain;
11025   }
11026 
11027   void EliminateAllTemplateMatches() {
11028     //   [...] any function template specializations in the set are
11029     //   eliminated if the set also contains a non-template function, [...]
11030     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11031       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11032         ++I;
11033       else {
11034         Matches[I] = Matches[--N];
11035         Matches.resize(N);
11036       }
11037     }
11038   }
11039 
11040   void EliminateSuboptimalCudaMatches() {
11041     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11042   }
11043 
11044 public:
11045   void ComplainNoMatchesFound() const {
11046     assert(Matches.empty());
11047     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11048         << OvlExpr->getName() << TargetFunctionType
11049         << OvlExpr->getSourceRange();
11050     if (FailedCandidates.empty())
11051       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11052                                   /*TakingAddress=*/true);
11053     else {
11054       // We have some deduction failure messages. Use them to diagnose
11055       // the function templates, and diagnose the non-template candidates
11056       // normally.
11057       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11058                                  IEnd = OvlExpr->decls_end();
11059            I != IEnd; ++I)
11060         if (FunctionDecl *Fun =
11061                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11062           if (!functionHasPassObjectSizeParams(Fun))
11063             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11064                                     /*TakingAddress=*/true);
11065       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11066     }
11067   }
11068 
11069   bool IsInvalidFormOfPointerToMemberFunction() const {
11070     return TargetTypeIsNonStaticMemberFunction &&
11071       !OvlExprInfo.HasFormOfMemberPointer;
11072   }
11073 
11074   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11075       // TODO: Should we condition this on whether any functions might
11076       // have matched, or is it more appropriate to do that in callers?
11077       // TODO: a fixit wouldn't hurt.
11078       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11079         << TargetType << OvlExpr->getSourceRange();
11080   }
11081 
11082   bool IsStaticMemberFunctionFromBoundPointer() const {
11083     return StaticMemberFunctionFromBoundPointer;
11084   }
11085 
11086   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11087     S.Diag(OvlExpr->getLocStart(),
11088            diag::err_invalid_form_pointer_member_function)
11089       << OvlExpr->getSourceRange();
11090   }
11091 
11092   void ComplainOfInvalidConversion() const {
11093     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11094       << OvlExpr->getName() << TargetType;
11095   }
11096 
11097   void ComplainMultipleMatchesFound() const {
11098     assert(Matches.size() > 1);
11099     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11100       << OvlExpr->getName()
11101       << OvlExpr->getSourceRange();
11102     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11103                                 /*TakingAddress=*/true);
11104   }
11105 
11106   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11107 
11108   int getNumMatches() const { return Matches.size(); }
11109 
11110   FunctionDecl* getMatchingFunctionDecl() const {
11111     if (Matches.size() != 1) return nullptr;
11112     return Matches[0].second;
11113   }
11114 
11115   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11116     if (Matches.size() != 1) return nullptr;
11117     return &Matches[0].first;
11118   }
11119 };
11120 }
11121 
11122 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11123 /// an overloaded function (C++ [over.over]), where @p From is an
11124 /// expression with overloaded function type and @p ToType is the type
11125 /// we're trying to resolve to. For example:
11126 ///
11127 /// @code
11128 /// int f(double);
11129 /// int f(int);
11130 ///
11131 /// int (*pfd)(double) = f; // selects f(double)
11132 /// @endcode
11133 ///
11134 /// This routine returns the resulting FunctionDecl if it could be
11135 /// resolved, and NULL otherwise. When @p Complain is true, this
11136 /// routine will emit diagnostics if there is an error.
11137 FunctionDecl *
11138 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11139                                          QualType TargetType,
11140                                          bool Complain,
11141                                          DeclAccessPair &FoundResult,
11142                                          bool *pHadMultipleCandidates) {
11143   assert(AddressOfExpr->getType() == Context.OverloadTy);
11144 
11145   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11146                                      Complain);
11147   int NumMatches = Resolver.getNumMatches();
11148   FunctionDecl *Fn = nullptr;
11149   bool ShouldComplain = Complain && !Resolver.hasComplained();
11150   if (NumMatches == 0 && ShouldComplain) {
11151     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11152       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11153     else
11154       Resolver.ComplainNoMatchesFound();
11155   }
11156   else if (NumMatches > 1 && ShouldComplain)
11157     Resolver.ComplainMultipleMatchesFound();
11158   else if (NumMatches == 1) {
11159     Fn = Resolver.getMatchingFunctionDecl();
11160     assert(Fn);
11161     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11162       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11163     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11164     if (Complain) {
11165       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11166         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11167       else
11168         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11169     }
11170   }
11171 
11172   if (pHadMultipleCandidates)
11173     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11174   return Fn;
11175 }
11176 
11177 /// \brief Given an expression that refers to an overloaded function, try to
11178 /// resolve that function to a single function that can have its address taken.
11179 /// This will modify `Pair` iff it returns non-null.
11180 ///
11181 /// This routine can only realistically succeed if all but one candidates in the
11182 /// overload set for SrcExpr cannot have their addresses taken.
11183 FunctionDecl *
11184 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11185                                                   DeclAccessPair &Pair) {
11186   OverloadExpr::FindResult R = OverloadExpr::find(E);
11187   OverloadExpr *Ovl = R.Expression;
11188   FunctionDecl *Result = nullptr;
11189   DeclAccessPair DAP;
11190   // Don't use the AddressOfResolver because we're specifically looking for
11191   // cases where we have one overload candidate that lacks
11192   // enable_if/pass_object_size/...
11193   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11194     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11195     if (!FD)
11196       return nullptr;
11197 
11198     if (!checkAddressOfFunctionIsAvailable(FD))
11199       continue;
11200 
11201     // We have more than one result; quit.
11202     if (Result)
11203       return nullptr;
11204     DAP = I.getPair();
11205     Result = FD;
11206   }
11207 
11208   if (Result)
11209     Pair = DAP;
11210   return Result;
11211 }
11212 
11213 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11214 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11215 /// will perform access checks, diagnose the use of the resultant decl, and, if
11216 /// requested, potentially perform a function-to-pointer decay.
11217 ///
11218 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11219 /// Otherwise, returns true. This may emit diagnostics and return true.
11220 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11221     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11222   Expr *E = SrcExpr.get();
11223   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11224 
11225   DeclAccessPair DAP;
11226   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11227   if (!Found)
11228     return false;
11229 
11230   // Emitting multiple diagnostics for a function that is both inaccessible and
11231   // unavailable is consistent with our behavior elsewhere. So, always check
11232   // for both.
11233   DiagnoseUseOfDecl(Found, E->getExprLoc());
11234   CheckAddressOfMemberAccess(E, DAP);
11235   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11236   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11237     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11238   else
11239     SrcExpr = Fixed;
11240   return true;
11241 }
11242 
11243 /// \brief Given an expression that refers to an overloaded function, try to
11244 /// resolve that overloaded function expression down to a single function.
11245 ///
11246 /// This routine can only resolve template-ids that refer to a single function
11247 /// template, where that template-id refers to a single template whose template
11248 /// arguments are either provided by the template-id or have defaults,
11249 /// as described in C++0x [temp.arg.explicit]p3.
11250 ///
11251 /// If no template-ids are found, no diagnostics are emitted and NULL is
11252 /// returned.
11253 FunctionDecl *
11254 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11255                                                   bool Complain,
11256                                                   DeclAccessPair *FoundResult) {
11257   // C++ [over.over]p1:
11258   //   [...] [Note: any redundant set of parentheses surrounding the
11259   //   overloaded function name is ignored (5.1). ]
11260   // C++ [over.over]p1:
11261   //   [...] The overloaded function name can be preceded by the &
11262   //   operator.
11263 
11264   // If we didn't actually find any template-ids, we're done.
11265   if (!ovl->hasExplicitTemplateArgs())
11266     return nullptr;
11267 
11268   TemplateArgumentListInfo ExplicitTemplateArgs;
11269   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11270   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11271 
11272   // Look through all of the overloaded functions, searching for one
11273   // whose type matches exactly.
11274   FunctionDecl *Matched = nullptr;
11275   for (UnresolvedSetIterator I = ovl->decls_begin(),
11276          E = ovl->decls_end(); I != E; ++I) {
11277     // C++0x [temp.arg.explicit]p3:
11278     //   [...] In contexts where deduction is done and fails, or in contexts
11279     //   where deduction is not done, if a template argument list is
11280     //   specified and it, along with any default template arguments,
11281     //   identifies a single function template specialization, then the
11282     //   template-id is an lvalue for the function template specialization.
11283     FunctionTemplateDecl *FunctionTemplate
11284       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11285 
11286     // C++ [over.over]p2:
11287     //   If the name is a function template, template argument deduction is
11288     //   done (14.8.2.2), and if the argument deduction succeeds, the
11289     //   resulting template argument list is used to generate a single
11290     //   function template specialization, which is added to the set of
11291     //   overloaded functions considered.
11292     FunctionDecl *Specialization = nullptr;
11293     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11294     if (TemplateDeductionResult Result
11295           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11296                                     Specialization, Info,
11297                                     /*IsAddressOfFunction*/true)) {
11298       // Make a note of the failed deduction for diagnostics.
11299       // TODO: Actually use the failed-deduction info?
11300       FailedCandidates.addCandidate()
11301           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11302                MakeDeductionFailureInfo(Context, Result, Info));
11303       continue;
11304     }
11305 
11306     assert(Specialization && "no specialization and no error?");
11307 
11308     // Multiple matches; we can't resolve to a single declaration.
11309     if (Matched) {
11310       if (Complain) {
11311         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11312           << ovl->getName();
11313         NoteAllOverloadCandidates(ovl);
11314       }
11315       return nullptr;
11316     }
11317 
11318     Matched = Specialization;
11319     if (FoundResult) *FoundResult = I.getPair();
11320   }
11321 
11322   if (Matched &&
11323       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11324     return nullptr;
11325 
11326   return Matched;
11327 }
11328 
11329 // Resolve and fix an overloaded expression that can be resolved
11330 // because it identifies a single function template specialization.
11331 //
11332 // Last three arguments should only be supplied if Complain = true
11333 //
11334 // Return true if it was logically possible to so resolve the
11335 // expression, regardless of whether or not it succeeded.  Always
11336 // returns true if 'complain' is set.
11337 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11338                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11339                       bool complain, SourceRange OpRangeForComplaining,
11340                                            QualType DestTypeForComplaining,
11341                                             unsigned DiagIDForComplaining) {
11342   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11343 
11344   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11345 
11346   DeclAccessPair found;
11347   ExprResult SingleFunctionExpression;
11348   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11349                            ovl.Expression, /*complain*/ false, &found)) {
11350     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11351       SrcExpr = ExprError();
11352       return true;
11353     }
11354 
11355     // It is only correct to resolve to an instance method if we're
11356     // resolving a form that's permitted to be a pointer to member.
11357     // Otherwise we'll end up making a bound member expression, which
11358     // is illegal in all the contexts we resolve like this.
11359     if (!ovl.HasFormOfMemberPointer &&
11360         isa<CXXMethodDecl>(fn) &&
11361         cast<CXXMethodDecl>(fn)->isInstance()) {
11362       if (!complain) return false;
11363 
11364       Diag(ovl.Expression->getExprLoc(),
11365            diag::err_bound_member_function)
11366         << 0 << ovl.Expression->getSourceRange();
11367 
11368       // TODO: I believe we only end up here if there's a mix of
11369       // static and non-static candidates (otherwise the expression
11370       // would have 'bound member' type, not 'overload' type).
11371       // Ideally we would note which candidate was chosen and why
11372       // the static candidates were rejected.
11373       SrcExpr = ExprError();
11374       return true;
11375     }
11376 
11377     // Fix the expression to refer to 'fn'.
11378     SingleFunctionExpression =
11379         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11380 
11381     // If desired, do function-to-pointer decay.
11382     if (doFunctionPointerConverion) {
11383       SingleFunctionExpression =
11384         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11385       if (SingleFunctionExpression.isInvalid()) {
11386         SrcExpr = ExprError();
11387         return true;
11388       }
11389     }
11390   }
11391 
11392   if (!SingleFunctionExpression.isUsable()) {
11393     if (complain) {
11394       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11395         << ovl.Expression->getName()
11396         << DestTypeForComplaining
11397         << OpRangeForComplaining
11398         << ovl.Expression->getQualifierLoc().getSourceRange();
11399       NoteAllOverloadCandidates(SrcExpr.get());
11400 
11401       SrcExpr = ExprError();
11402       return true;
11403     }
11404 
11405     return false;
11406   }
11407 
11408   SrcExpr = SingleFunctionExpression;
11409   return true;
11410 }
11411 
11412 /// \brief Add a single candidate to the overload set.
11413 static void AddOverloadedCallCandidate(Sema &S,
11414                                        DeclAccessPair FoundDecl,
11415                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11416                                        ArrayRef<Expr *> Args,
11417                                        OverloadCandidateSet &CandidateSet,
11418                                        bool PartialOverloading,
11419                                        bool KnownValid) {
11420   NamedDecl *Callee = FoundDecl.getDecl();
11421   if (isa<UsingShadowDecl>(Callee))
11422     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11423 
11424   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11425     if (ExplicitTemplateArgs) {
11426       assert(!KnownValid && "Explicit template arguments?");
11427       return;
11428     }
11429     // Prevent ill-formed function decls to be added as overload candidates.
11430     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11431       return;
11432 
11433     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11434                            /*SuppressUsedConversions=*/false,
11435                            PartialOverloading);
11436     return;
11437   }
11438 
11439   if (FunctionTemplateDecl *FuncTemplate
11440       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11441     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11442                                    ExplicitTemplateArgs, Args, CandidateSet,
11443                                    /*SuppressUsedConversions=*/false,
11444                                    PartialOverloading);
11445     return;
11446   }
11447 
11448   assert(!KnownValid && "unhandled case in overloaded call candidate");
11449 }
11450 
11451 /// \brief Add the overload candidates named by callee and/or found by argument
11452 /// dependent lookup to the given overload set.
11453 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11454                                        ArrayRef<Expr *> Args,
11455                                        OverloadCandidateSet &CandidateSet,
11456                                        bool PartialOverloading) {
11457 
11458 #ifndef NDEBUG
11459   // Verify that ArgumentDependentLookup is consistent with the rules
11460   // in C++0x [basic.lookup.argdep]p3:
11461   //
11462   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11463   //   and let Y be the lookup set produced by argument dependent
11464   //   lookup (defined as follows). If X contains
11465   //
11466   //     -- a declaration of a class member, or
11467   //
11468   //     -- a block-scope function declaration that is not a
11469   //        using-declaration, or
11470   //
11471   //     -- a declaration that is neither a function or a function
11472   //        template
11473   //
11474   //   then Y is empty.
11475 
11476   if (ULE->requiresADL()) {
11477     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11478            E = ULE->decls_end(); I != E; ++I) {
11479       assert(!(*I)->getDeclContext()->isRecord());
11480       assert(isa<UsingShadowDecl>(*I) ||
11481              !(*I)->getDeclContext()->isFunctionOrMethod());
11482       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11483     }
11484   }
11485 #endif
11486 
11487   // It would be nice to avoid this copy.
11488   TemplateArgumentListInfo TABuffer;
11489   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11490   if (ULE->hasExplicitTemplateArgs()) {
11491     ULE->copyTemplateArgumentsInto(TABuffer);
11492     ExplicitTemplateArgs = &TABuffer;
11493   }
11494 
11495   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11496          E = ULE->decls_end(); I != E; ++I)
11497     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11498                                CandidateSet, PartialOverloading,
11499                                /*KnownValid*/ true);
11500 
11501   if (ULE->requiresADL())
11502     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11503                                          Args, ExplicitTemplateArgs,
11504                                          CandidateSet, PartialOverloading);
11505 }
11506 
11507 /// Determine whether a declaration with the specified name could be moved into
11508 /// a different namespace.
11509 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11510   switch (Name.getCXXOverloadedOperator()) {
11511   case OO_New: case OO_Array_New:
11512   case OO_Delete: case OO_Array_Delete:
11513     return false;
11514 
11515   default:
11516     return true;
11517   }
11518 }
11519 
11520 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11521 /// template, where the non-dependent name was declared after the template
11522 /// was defined. This is common in code written for a compilers which do not
11523 /// correctly implement two-stage name lookup.
11524 ///
11525 /// Returns true if a viable candidate was found and a diagnostic was issued.
11526 static bool
11527 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11528                        const CXXScopeSpec &SS, LookupResult &R,
11529                        OverloadCandidateSet::CandidateSetKind CSK,
11530                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11531                        ArrayRef<Expr *> Args,
11532                        bool *DoDiagnoseEmptyLookup = nullptr) {
11533   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11534     return false;
11535 
11536   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11537     if (DC->isTransparentContext())
11538       continue;
11539 
11540     SemaRef.LookupQualifiedName(R, DC);
11541 
11542     if (!R.empty()) {
11543       R.suppressDiagnostics();
11544 
11545       if (isa<CXXRecordDecl>(DC)) {
11546         // Don't diagnose names we find in classes; we get much better
11547         // diagnostics for these from DiagnoseEmptyLookup.
11548         R.clear();
11549         if (DoDiagnoseEmptyLookup)
11550           *DoDiagnoseEmptyLookup = true;
11551         return false;
11552       }
11553 
11554       OverloadCandidateSet Candidates(FnLoc, CSK);
11555       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11556         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11557                                    ExplicitTemplateArgs, Args,
11558                                    Candidates, false, /*KnownValid*/ false);
11559 
11560       OverloadCandidateSet::iterator Best;
11561       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11562         // No viable functions. Don't bother the user with notes for functions
11563         // which don't work and shouldn't be found anyway.
11564         R.clear();
11565         return false;
11566       }
11567 
11568       // Find the namespaces where ADL would have looked, and suggest
11569       // declaring the function there instead.
11570       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11571       Sema::AssociatedClassSet AssociatedClasses;
11572       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11573                                                  AssociatedNamespaces,
11574                                                  AssociatedClasses);
11575       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11576       if (canBeDeclaredInNamespace(R.getLookupName())) {
11577         DeclContext *Std = SemaRef.getStdNamespace();
11578         for (Sema::AssociatedNamespaceSet::iterator
11579                it = AssociatedNamespaces.begin(),
11580                end = AssociatedNamespaces.end(); it != end; ++it) {
11581           // Never suggest declaring a function within namespace 'std'.
11582           if (Std && Std->Encloses(*it))
11583             continue;
11584 
11585           // Never suggest declaring a function within a namespace with a
11586           // reserved name, like __gnu_cxx.
11587           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11588           if (NS &&
11589               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11590             continue;
11591 
11592           SuggestedNamespaces.insert(*it);
11593         }
11594       }
11595 
11596       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11597         << R.getLookupName();
11598       if (SuggestedNamespaces.empty()) {
11599         SemaRef.Diag(Best->Function->getLocation(),
11600                      diag::note_not_found_by_two_phase_lookup)
11601           << R.getLookupName() << 0;
11602       } else if (SuggestedNamespaces.size() == 1) {
11603         SemaRef.Diag(Best->Function->getLocation(),
11604                      diag::note_not_found_by_two_phase_lookup)
11605           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11606       } else {
11607         // FIXME: It would be useful to list the associated namespaces here,
11608         // but the diagnostics infrastructure doesn't provide a way to produce
11609         // a localized representation of a list of items.
11610         SemaRef.Diag(Best->Function->getLocation(),
11611                      diag::note_not_found_by_two_phase_lookup)
11612           << R.getLookupName() << 2;
11613       }
11614 
11615       // Try to recover by calling this function.
11616       return true;
11617     }
11618 
11619     R.clear();
11620   }
11621 
11622   return false;
11623 }
11624 
11625 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11626 /// template, where the non-dependent operator was declared after the template
11627 /// was defined.
11628 ///
11629 /// Returns true if a viable candidate was found and a diagnostic was issued.
11630 static bool
11631 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11632                                SourceLocation OpLoc,
11633                                ArrayRef<Expr *> Args) {
11634   DeclarationName OpName =
11635     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11636   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11637   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11638                                 OverloadCandidateSet::CSK_Operator,
11639                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11640 }
11641 
11642 namespace {
11643 class BuildRecoveryCallExprRAII {
11644   Sema &SemaRef;
11645 public:
11646   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11647     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11648     SemaRef.IsBuildingRecoveryCallExpr = true;
11649   }
11650 
11651   ~BuildRecoveryCallExprRAII() {
11652     SemaRef.IsBuildingRecoveryCallExpr = false;
11653   }
11654 };
11655 
11656 }
11657 
11658 static std::unique_ptr<CorrectionCandidateCallback>
11659 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11660               bool HasTemplateArgs, bool AllowTypoCorrection) {
11661   if (!AllowTypoCorrection)
11662     return llvm::make_unique<NoTypoCorrectionCCC>();
11663   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11664                                                   HasTemplateArgs, ME);
11665 }
11666 
11667 /// Attempts to recover from a call where no functions were found.
11668 ///
11669 /// Returns true if new candidates were found.
11670 static ExprResult
11671 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11672                       UnresolvedLookupExpr *ULE,
11673                       SourceLocation LParenLoc,
11674                       MutableArrayRef<Expr *> Args,
11675                       SourceLocation RParenLoc,
11676                       bool EmptyLookup, bool AllowTypoCorrection) {
11677   // Do not try to recover if it is already building a recovery call.
11678   // This stops infinite loops for template instantiations like
11679   //
11680   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11681   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11682   //
11683   if (SemaRef.IsBuildingRecoveryCallExpr)
11684     return ExprError();
11685   BuildRecoveryCallExprRAII RCE(SemaRef);
11686 
11687   CXXScopeSpec SS;
11688   SS.Adopt(ULE->getQualifierLoc());
11689   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11690 
11691   TemplateArgumentListInfo TABuffer;
11692   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11693   if (ULE->hasExplicitTemplateArgs()) {
11694     ULE->copyTemplateArgumentsInto(TABuffer);
11695     ExplicitTemplateArgs = &TABuffer;
11696   }
11697 
11698   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11699                  Sema::LookupOrdinaryName);
11700   bool DoDiagnoseEmptyLookup = EmptyLookup;
11701   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11702                               OverloadCandidateSet::CSK_Normal,
11703                               ExplicitTemplateArgs, Args,
11704                               &DoDiagnoseEmptyLookup) &&
11705     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11706         S, SS, R,
11707         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11708                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11709         ExplicitTemplateArgs, Args)))
11710     return ExprError();
11711 
11712   assert(!R.empty() && "lookup results empty despite recovery");
11713 
11714   // If recovery created an ambiguity, just bail out.
11715   if (R.isAmbiguous()) {
11716     R.suppressDiagnostics();
11717     return ExprError();
11718   }
11719 
11720   // Build an implicit member call if appropriate.  Just drop the
11721   // casts and such from the call, we don't really care.
11722   ExprResult NewFn = ExprError();
11723   if ((*R.begin())->isCXXClassMember())
11724     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11725                                                     ExplicitTemplateArgs, S);
11726   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11727     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11728                                         ExplicitTemplateArgs);
11729   else
11730     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11731 
11732   if (NewFn.isInvalid())
11733     return ExprError();
11734 
11735   // This shouldn't cause an infinite loop because we're giving it
11736   // an expression with viable lookup results, which should never
11737   // end up here.
11738   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11739                                MultiExprArg(Args.data(), Args.size()),
11740                                RParenLoc);
11741 }
11742 
11743 /// \brief Constructs and populates an OverloadedCandidateSet from
11744 /// the given function.
11745 /// \returns true when an the ExprResult output parameter has been set.
11746 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11747                                   UnresolvedLookupExpr *ULE,
11748                                   MultiExprArg Args,
11749                                   SourceLocation RParenLoc,
11750                                   OverloadCandidateSet *CandidateSet,
11751                                   ExprResult *Result) {
11752 #ifndef NDEBUG
11753   if (ULE->requiresADL()) {
11754     // To do ADL, we must have found an unqualified name.
11755     assert(!ULE->getQualifier() && "qualified name with ADL");
11756 
11757     // We don't perform ADL for implicit declarations of builtins.
11758     // Verify that this was correctly set up.
11759     FunctionDecl *F;
11760     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11761         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11762         F->getBuiltinID() && F->isImplicit())
11763       llvm_unreachable("performing ADL for builtin");
11764 
11765     // We don't perform ADL in C.
11766     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11767   }
11768 #endif
11769 
11770   UnbridgedCastsSet UnbridgedCasts;
11771   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11772     *Result = ExprError();
11773     return true;
11774   }
11775 
11776   // Add the functions denoted by the callee to the set of candidate
11777   // functions, including those from argument-dependent lookup.
11778   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11779 
11780   if (getLangOpts().MSVCCompat &&
11781       CurContext->isDependentContext() && !isSFINAEContext() &&
11782       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11783 
11784     OverloadCandidateSet::iterator Best;
11785     if (CandidateSet->empty() ||
11786         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11787             OR_No_Viable_Function) {
11788       // In Microsoft mode, if we are inside a template class member function then
11789       // create a type dependent CallExpr. The goal is to postpone name lookup
11790       // to instantiation time to be able to search into type dependent base
11791       // classes.
11792       CallExpr *CE = new (Context) CallExpr(
11793           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11794       CE->setTypeDependent(true);
11795       CE->setValueDependent(true);
11796       CE->setInstantiationDependent(true);
11797       *Result = CE;
11798       return true;
11799     }
11800   }
11801 
11802   if (CandidateSet->empty())
11803     return false;
11804 
11805   UnbridgedCasts.restore();
11806   return false;
11807 }
11808 
11809 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11810 /// the completed call expression. If overload resolution fails, emits
11811 /// diagnostics and returns ExprError()
11812 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11813                                            UnresolvedLookupExpr *ULE,
11814                                            SourceLocation LParenLoc,
11815                                            MultiExprArg Args,
11816                                            SourceLocation RParenLoc,
11817                                            Expr *ExecConfig,
11818                                            OverloadCandidateSet *CandidateSet,
11819                                            OverloadCandidateSet::iterator *Best,
11820                                            OverloadingResult OverloadResult,
11821                                            bool AllowTypoCorrection) {
11822   if (CandidateSet->empty())
11823     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11824                                  RParenLoc, /*EmptyLookup=*/true,
11825                                  AllowTypoCorrection);
11826 
11827   switch (OverloadResult) {
11828   case OR_Success: {
11829     FunctionDecl *FDecl = (*Best)->Function;
11830     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11831     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11832       return ExprError();
11833     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11834     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11835                                          ExecConfig);
11836   }
11837 
11838   case OR_No_Viable_Function: {
11839     // Try to recover by looking for viable functions which the user might
11840     // have meant to call.
11841     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11842                                                 Args, RParenLoc,
11843                                                 /*EmptyLookup=*/false,
11844                                                 AllowTypoCorrection);
11845     if (!Recovery.isInvalid())
11846       return Recovery;
11847 
11848     // If the user passes in a function that we can't take the address of, we
11849     // generally end up emitting really bad error messages. Here, we attempt to
11850     // emit better ones.
11851     for (const Expr *Arg : Args) {
11852       if (!Arg->getType()->isFunctionType())
11853         continue;
11854       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11855         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11856         if (FD &&
11857             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11858                                                        Arg->getExprLoc()))
11859           return ExprError();
11860       }
11861     }
11862 
11863     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11864         << ULE->getName() << Fn->getSourceRange();
11865     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11866     break;
11867   }
11868 
11869   case OR_Ambiguous:
11870     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11871       << ULE->getName() << Fn->getSourceRange();
11872     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11873     break;
11874 
11875   case OR_Deleted: {
11876     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11877       << (*Best)->Function->isDeleted()
11878       << ULE->getName()
11879       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11880       << Fn->getSourceRange();
11881     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11882 
11883     // We emitted an error for the unvailable/deleted function call but keep
11884     // the call in the AST.
11885     FunctionDecl *FDecl = (*Best)->Function;
11886     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11887     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11888                                          ExecConfig);
11889   }
11890   }
11891 
11892   // Overload resolution failed.
11893   return ExprError();
11894 }
11895 
11896 static void markUnaddressableCandidatesUnviable(Sema &S,
11897                                                 OverloadCandidateSet &CS) {
11898   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11899     if (I->Viable &&
11900         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11901       I->Viable = false;
11902       I->FailureKind = ovl_fail_addr_not_available;
11903     }
11904   }
11905 }
11906 
11907 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11908 /// (which eventually refers to the declaration Func) and the call
11909 /// arguments Args/NumArgs, attempt to resolve the function call down
11910 /// to a specific function. If overload resolution succeeds, returns
11911 /// the call expression produced by overload resolution.
11912 /// Otherwise, emits diagnostics and returns ExprError.
11913 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11914                                          UnresolvedLookupExpr *ULE,
11915                                          SourceLocation LParenLoc,
11916                                          MultiExprArg Args,
11917                                          SourceLocation RParenLoc,
11918                                          Expr *ExecConfig,
11919                                          bool AllowTypoCorrection,
11920                                          bool CalleesAddressIsTaken) {
11921   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11922                                     OverloadCandidateSet::CSK_Normal);
11923   ExprResult result;
11924 
11925   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11926                              &result))
11927     return result;
11928 
11929   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11930   // functions that aren't addressible are considered unviable.
11931   if (CalleesAddressIsTaken)
11932     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11933 
11934   OverloadCandidateSet::iterator Best;
11935   OverloadingResult OverloadResult =
11936       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11937 
11938   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11939                                   RParenLoc, ExecConfig, &CandidateSet,
11940                                   &Best, OverloadResult,
11941                                   AllowTypoCorrection);
11942 }
11943 
11944 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11945   return Functions.size() > 1 ||
11946     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11947 }
11948 
11949 /// \brief Create a unary operation that may resolve to an overloaded
11950 /// operator.
11951 ///
11952 /// \param OpLoc The location of the operator itself (e.g., '*').
11953 ///
11954 /// \param Opc The UnaryOperatorKind that describes this operator.
11955 ///
11956 /// \param Fns The set of non-member functions that will be
11957 /// considered by overload resolution. The caller needs to build this
11958 /// set based on the context using, e.g.,
11959 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11960 /// set should not contain any member functions; those will be added
11961 /// by CreateOverloadedUnaryOp().
11962 ///
11963 /// \param Input The input argument.
11964 ExprResult
11965 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11966                               const UnresolvedSetImpl &Fns,
11967                               Expr *Input, bool PerformADL) {
11968   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11969   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11970   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11971   // TODO: provide better source location info.
11972   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11973 
11974   if (checkPlaceholderForOverload(*this, Input))
11975     return ExprError();
11976 
11977   Expr *Args[2] = { Input, nullptr };
11978   unsigned NumArgs = 1;
11979 
11980   // For post-increment and post-decrement, add the implicit '0' as
11981   // the second argument, so that we know this is a post-increment or
11982   // post-decrement.
11983   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11984     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11985     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11986                                      SourceLocation());
11987     NumArgs = 2;
11988   }
11989 
11990   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11991 
11992   if (Input->isTypeDependent()) {
11993     if (Fns.empty())
11994       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11995                                          VK_RValue, OK_Ordinary, OpLoc);
11996 
11997     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11998     UnresolvedLookupExpr *Fn
11999       = UnresolvedLookupExpr::Create(Context, NamingClass,
12000                                      NestedNameSpecifierLoc(), OpNameInfo,
12001                                      /*ADL*/ true, IsOverloaded(Fns),
12002                                      Fns.begin(), Fns.end());
12003     return new (Context)
12004         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12005                             VK_RValue, OpLoc, FPOptions());
12006   }
12007 
12008   // Build an empty overload set.
12009   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12010 
12011   // Add the candidates from the given function set.
12012   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12013 
12014   // Add operator candidates that are member functions.
12015   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12016 
12017   // Add candidates from ADL.
12018   if (PerformADL) {
12019     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12020                                          /*ExplicitTemplateArgs*/nullptr,
12021                                          CandidateSet);
12022   }
12023 
12024   // Add builtin operator candidates.
12025   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12026 
12027   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12028 
12029   // Perform overload resolution.
12030   OverloadCandidateSet::iterator Best;
12031   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12032   case OR_Success: {
12033     // We found a built-in operator or an overloaded operator.
12034     FunctionDecl *FnDecl = Best->Function;
12035 
12036     if (FnDecl) {
12037       Expr *Base = nullptr;
12038       // We matched an overloaded operator. Build a call to that
12039       // operator.
12040 
12041       // Convert the arguments.
12042       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12043         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12044 
12045         ExprResult InputRes =
12046           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12047                                               Best->FoundDecl, Method);
12048         if (InputRes.isInvalid())
12049           return ExprError();
12050         Base = Input = InputRes.get();
12051       } else {
12052         // Convert the arguments.
12053         ExprResult InputInit
12054           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12055                                                       Context,
12056                                                       FnDecl->getParamDecl(0)),
12057                                       SourceLocation(),
12058                                       Input);
12059         if (InputInit.isInvalid())
12060           return ExprError();
12061         Input = InputInit.get();
12062       }
12063 
12064       // Build the actual expression node.
12065       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12066                                                 Base, HadMultipleCandidates,
12067                                                 OpLoc);
12068       if (FnExpr.isInvalid())
12069         return ExprError();
12070 
12071       // Determine the result type.
12072       QualType ResultTy = FnDecl->getReturnType();
12073       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12074       ResultTy = ResultTy.getNonLValueExprType(Context);
12075 
12076       Args[0] = Input;
12077       CallExpr *TheCall =
12078         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12079                                           ResultTy, VK, OpLoc, FPOptions());
12080 
12081       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12082         return ExprError();
12083 
12084       if (CheckFunctionCall(FnDecl, TheCall,
12085                             FnDecl->getType()->castAs<FunctionProtoType>()))
12086         return ExprError();
12087 
12088       return MaybeBindToTemporary(TheCall);
12089     } else {
12090       // We matched a built-in operator. Convert the arguments, then
12091       // break out so that we will build the appropriate built-in
12092       // operator node.
12093       ExprResult InputRes = PerformImplicitConversion(
12094           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12095       if (InputRes.isInvalid())
12096         return ExprError();
12097       Input = InputRes.get();
12098       break;
12099     }
12100   }
12101 
12102   case OR_No_Viable_Function:
12103     // This is an erroneous use of an operator which can be overloaded by
12104     // a non-member function. Check for non-member operators which were
12105     // defined too late to be candidates.
12106     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12107       // FIXME: Recover by calling the found function.
12108       return ExprError();
12109 
12110     // No viable function; fall through to handling this as a
12111     // built-in operator, which will produce an error message for us.
12112     break;
12113 
12114   case OR_Ambiguous:
12115     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12116         << UnaryOperator::getOpcodeStr(Opc)
12117         << Input->getType()
12118         << Input->getSourceRange();
12119     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12120                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12121     return ExprError();
12122 
12123   case OR_Deleted:
12124     Diag(OpLoc, diag::err_ovl_deleted_oper)
12125       << Best->Function->isDeleted()
12126       << UnaryOperator::getOpcodeStr(Opc)
12127       << getDeletedOrUnavailableSuffix(Best->Function)
12128       << Input->getSourceRange();
12129     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12130                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12131     return ExprError();
12132   }
12133 
12134   // Either we found no viable overloaded operator or we matched a
12135   // built-in operator. In either case, fall through to trying to
12136   // build a built-in operation.
12137   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12138 }
12139 
12140 /// \brief Create a binary operation that may resolve to an overloaded
12141 /// operator.
12142 ///
12143 /// \param OpLoc The location of the operator itself (e.g., '+').
12144 ///
12145 /// \param Opc The BinaryOperatorKind that describes this operator.
12146 ///
12147 /// \param Fns The set of non-member functions that will be
12148 /// considered by overload resolution. The caller needs to build this
12149 /// set based on the context using, e.g.,
12150 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12151 /// set should not contain any member functions; those will be added
12152 /// by CreateOverloadedBinOp().
12153 ///
12154 /// \param LHS Left-hand argument.
12155 /// \param RHS Right-hand argument.
12156 ExprResult
12157 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12158                             BinaryOperatorKind Opc,
12159                             const UnresolvedSetImpl &Fns,
12160                             Expr *LHS, Expr *RHS, bool PerformADL) {
12161   Expr *Args[2] = { LHS, RHS };
12162   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12163 
12164   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12165   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12166 
12167   // If either side is type-dependent, create an appropriate dependent
12168   // expression.
12169   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12170     if (Fns.empty()) {
12171       // If there are no functions to store, just build a dependent
12172       // BinaryOperator or CompoundAssignment.
12173       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12174         return new (Context) BinaryOperator(
12175             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12176             OpLoc, FPFeatures);
12177 
12178       return new (Context) CompoundAssignOperator(
12179           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12180           Context.DependentTy, Context.DependentTy, OpLoc,
12181           FPFeatures);
12182     }
12183 
12184     // FIXME: save results of ADL from here?
12185     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12186     // TODO: provide better source location info in DNLoc component.
12187     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12188     UnresolvedLookupExpr *Fn
12189       = UnresolvedLookupExpr::Create(Context, NamingClass,
12190                                      NestedNameSpecifierLoc(), OpNameInfo,
12191                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12192                                      Fns.begin(), Fns.end());
12193     return new (Context)
12194         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12195                             VK_RValue, OpLoc, FPFeatures);
12196   }
12197 
12198   // Always do placeholder-like conversions on the RHS.
12199   if (checkPlaceholderForOverload(*this, Args[1]))
12200     return ExprError();
12201 
12202   // Do placeholder-like conversion on the LHS; note that we should
12203   // not get here with a PseudoObject LHS.
12204   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12205   if (checkPlaceholderForOverload(*this, Args[0]))
12206     return ExprError();
12207 
12208   // If this is the assignment operator, we only perform overload resolution
12209   // if the left-hand side is a class or enumeration type. This is actually
12210   // a hack. The standard requires that we do overload resolution between the
12211   // various built-in candidates, but as DR507 points out, this can lead to
12212   // problems. So we do it this way, which pretty much follows what GCC does.
12213   // Note that we go the traditional code path for compound assignment forms.
12214   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12215     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12216 
12217   // If this is the .* operator, which is not overloadable, just
12218   // create a built-in binary operator.
12219   if (Opc == BO_PtrMemD)
12220     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12221 
12222   // Build an empty overload set.
12223   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12224 
12225   // Add the candidates from the given function set.
12226   AddFunctionCandidates(Fns, Args, CandidateSet);
12227 
12228   // Add operator candidates that are member functions.
12229   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12230 
12231   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12232   // performed for an assignment operator (nor for operator[] nor operator->,
12233   // which don't get here).
12234   if (Opc != BO_Assign && PerformADL)
12235     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12236                                          /*ExplicitTemplateArgs*/ nullptr,
12237                                          CandidateSet);
12238 
12239   // Add builtin operator candidates.
12240   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12241 
12242   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12243 
12244   // Perform overload resolution.
12245   OverloadCandidateSet::iterator Best;
12246   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12247     case OR_Success: {
12248       // We found a built-in operator or an overloaded operator.
12249       FunctionDecl *FnDecl = Best->Function;
12250 
12251       if (FnDecl) {
12252         Expr *Base = nullptr;
12253         // We matched an overloaded operator. Build a call to that
12254         // operator.
12255 
12256         // Convert the arguments.
12257         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12258           // Best->Access is only meaningful for class members.
12259           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12260 
12261           ExprResult Arg1 =
12262             PerformCopyInitialization(
12263               InitializedEntity::InitializeParameter(Context,
12264                                                      FnDecl->getParamDecl(0)),
12265               SourceLocation(), Args[1]);
12266           if (Arg1.isInvalid())
12267             return ExprError();
12268 
12269           ExprResult Arg0 =
12270             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12271                                                 Best->FoundDecl, Method);
12272           if (Arg0.isInvalid())
12273             return ExprError();
12274           Base = Args[0] = Arg0.getAs<Expr>();
12275           Args[1] = RHS = Arg1.getAs<Expr>();
12276         } else {
12277           // Convert the arguments.
12278           ExprResult Arg0 = PerformCopyInitialization(
12279             InitializedEntity::InitializeParameter(Context,
12280                                                    FnDecl->getParamDecl(0)),
12281             SourceLocation(), Args[0]);
12282           if (Arg0.isInvalid())
12283             return ExprError();
12284 
12285           ExprResult Arg1 =
12286             PerformCopyInitialization(
12287               InitializedEntity::InitializeParameter(Context,
12288                                                      FnDecl->getParamDecl(1)),
12289               SourceLocation(), Args[1]);
12290           if (Arg1.isInvalid())
12291             return ExprError();
12292           Args[0] = LHS = Arg0.getAs<Expr>();
12293           Args[1] = RHS = Arg1.getAs<Expr>();
12294         }
12295 
12296         // Build the actual expression node.
12297         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12298                                                   Best->FoundDecl, Base,
12299                                                   HadMultipleCandidates, OpLoc);
12300         if (FnExpr.isInvalid())
12301           return ExprError();
12302 
12303         // Determine the result type.
12304         QualType ResultTy = FnDecl->getReturnType();
12305         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12306         ResultTy = ResultTy.getNonLValueExprType(Context);
12307 
12308         CXXOperatorCallExpr *TheCall =
12309           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12310                                             Args, ResultTy, VK, OpLoc,
12311                                             FPFeatures);
12312 
12313         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12314                                 FnDecl))
12315           return ExprError();
12316 
12317         ArrayRef<const Expr *> ArgsArray(Args, 2);
12318         const Expr *ImplicitThis = nullptr;
12319         // Cut off the implicit 'this'.
12320         if (isa<CXXMethodDecl>(FnDecl)) {
12321           ImplicitThis = ArgsArray[0];
12322           ArgsArray = ArgsArray.slice(1);
12323         }
12324 
12325         // Check for a self move.
12326         if (Op == OO_Equal)
12327           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12328 
12329         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12330                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12331                   VariadicDoesNotApply);
12332 
12333         return MaybeBindToTemporary(TheCall);
12334       } else {
12335         // We matched a built-in operator. Convert the arguments, then
12336         // break out so that we will build the appropriate built-in
12337         // operator node.
12338         ExprResult ArgsRes0 =
12339             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12340                                       Best->Conversions[0], AA_Passing);
12341         if (ArgsRes0.isInvalid())
12342           return ExprError();
12343         Args[0] = ArgsRes0.get();
12344 
12345         ExprResult ArgsRes1 =
12346             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12347                                       Best->Conversions[1], AA_Passing);
12348         if (ArgsRes1.isInvalid())
12349           return ExprError();
12350         Args[1] = ArgsRes1.get();
12351         break;
12352       }
12353     }
12354 
12355     case OR_No_Viable_Function: {
12356       // C++ [over.match.oper]p9:
12357       //   If the operator is the operator , [...] and there are no
12358       //   viable functions, then the operator is assumed to be the
12359       //   built-in operator and interpreted according to clause 5.
12360       if (Opc == BO_Comma)
12361         break;
12362 
12363       // For class as left operand for assignment or compound assigment
12364       // operator do not fall through to handling in built-in, but report that
12365       // no overloaded assignment operator found
12366       ExprResult Result = ExprError();
12367       if (Args[0]->getType()->isRecordType() &&
12368           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12369         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12370              << BinaryOperator::getOpcodeStr(Opc)
12371              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12372         if (Args[0]->getType()->isIncompleteType()) {
12373           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12374             << Args[0]->getType()
12375             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12376         }
12377       } else {
12378         // This is an erroneous use of an operator which can be overloaded by
12379         // a non-member function. Check for non-member operators which were
12380         // defined too late to be candidates.
12381         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12382           // FIXME: Recover by calling the found function.
12383           return ExprError();
12384 
12385         // No viable function; try to create a built-in operation, which will
12386         // produce an error. Then, show the non-viable candidates.
12387         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12388       }
12389       assert(Result.isInvalid() &&
12390              "C++ binary operator overloading is missing candidates!");
12391       if (Result.isInvalid())
12392         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12393                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12394       return Result;
12395     }
12396 
12397     case OR_Ambiguous:
12398       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12399           << BinaryOperator::getOpcodeStr(Opc)
12400           << Args[0]->getType() << Args[1]->getType()
12401           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12402       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12403                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12404       return ExprError();
12405 
12406     case OR_Deleted:
12407       if (isImplicitlyDeleted(Best->Function)) {
12408         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12409         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12410           << Context.getRecordType(Method->getParent())
12411           << getSpecialMember(Method);
12412 
12413         // The user probably meant to call this special member. Just
12414         // explain why it's deleted.
12415         NoteDeletedFunction(Method);
12416         return ExprError();
12417       } else {
12418         Diag(OpLoc, diag::err_ovl_deleted_oper)
12419           << Best->Function->isDeleted()
12420           << BinaryOperator::getOpcodeStr(Opc)
12421           << getDeletedOrUnavailableSuffix(Best->Function)
12422           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12423       }
12424       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12425                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12426       return ExprError();
12427   }
12428 
12429   // We matched a built-in operator; build it.
12430   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12431 }
12432 
12433 ExprResult
12434 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12435                                          SourceLocation RLoc,
12436                                          Expr *Base, Expr *Idx) {
12437   Expr *Args[2] = { Base, Idx };
12438   DeclarationName OpName =
12439       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12440 
12441   // If either side is type-dependent, create an appropriate dependent
12442   // expression.
12443   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12444 
12445     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12446     // CHECKME: no 'operator' keyword?
12447     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12448     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12449     UnresolvedLookupExpr *Fn
12450       = UnresolvedLookupExpr::Create(Context, NamingClass,
12451                                      NestedNameSpecifierLoc(), OpNameInfo,
12452                                      /*ADL*/ true, /*Overloaded*/ false,
12453                                      UnresolvedSetIterator(),
12454                                      UnresolvedSetIterator());
12455     // Can't add any actual overloads yet
12456 
12457     return new (Context)
12458         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12459                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12460   }
12461 
12462   // Handle placeholders on both operands.
12463   if (checkPlaceholderForOverload(*this, Args[0]))
12464     return ExprError();
12465   if (checkPlaceholderForOverload(*this, Args[1]))
12466     return ExprError();
12467 
12468   // Build an empty overload set.
12469   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12470 
12471   // Subscript can only be overloaded as a member function.
12472 
12473   // Add operator candidates that are member functions.
12474   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12475 
12476   // Add builtin operator candidates.
12477   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12478 
12479   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12480 
12481   // Perform overload resolution.
12482   OverloadCandidateSet::iterator Best;
12483   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12484     case OR_Success: {
12485       // We found a built-in operator or an overloaded operator.
12486       FunctionDecl *FnDecl = Best->Function;
12487 
12488       if (FnDecl) {
12489         // We matched an overloaded operator. Build a call to that
12490         // operator.
12491 
12492         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12493 
12494         // Convert the arguments.
12495         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12496         ExprResult Arg0 =
12497           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12498                                               Best->FoundDecl, Method);
12499         if (Arg0.isInvalid())
12500           return ExprError();
12501         Args[0] = Arg0.get();
12502 
12503         // Convert the arguments.
12504         ExprResult InputInit
12505           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12506                                                       Context,
12507                                                       FnDecl->getParamDecl(0)),
12508                                       SourceLocation(),
12509                                       Args[1]);
12510         if (InputInit.isInvalid())
12511           return ExprError();
12512 
12513         Args[1] = InputInit.getAs<Expr>();
12514 
12515         // Build the actual expression node.
12516         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12517         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12518         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12519                                                   Best->FoundDecl,
12520                                                   Base,
12521                                                   HadMultipleCandidates,
12522                                                   OpLocInfo.getLoc(),
12523                                                   OpLocInfo.getInfo());
12524         if (FnExpr.isInvalid())
12525           return ExprError();
12526 
12527         // Determine the result type
12528         QualType ResultTy = FnDecl->getReturnType();
12529         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12530         ResultTy = ResultTy.getNonLValueExprType(Context);
12531 
12532         CXXOperatorCallExpr *TheCall =
12533           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12534                                             FnExpr.get(), Args,
12535                                             ResultTy, VK, RLoc,
12536                                             FPOptions());
12537 
12538         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12539           return ExprError();
12540 
12541         if (CheckFunctionCall(Method, TheCall,
12542                               Method->getType()->castAs<FunctionProtoType>()))
12543           return ExprError();
12544 
12545         return MaybeBindToTemporary(TheCall);
12546       } else {
12547         // We matched a built-in operator. Convert the arguments, then
12548         // break out so that we will build the appropriate built-in
12549         // operator node.
12550         ExprResult ArgsRes0 =
12551             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12552                                       Best->Conversions[0], AA_Passing);
12553         if (ArgsRes0.isInvalid())
12554           return ExprError();
12555         Args[0] = ArgsRes0.get();
12556 
12557         ExprResult ArgsRes1 =
12558             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12559                                       Best->Conversions[1], AA_Passing);
12560         if (ArgsRes1.isInvalid())
12561           return ExprError();
12562         Args[1] = ArgsRes1.get();
12563 
12564         break;
12565       }
12566     }
12567 
12568     case OR_No_Viable_Function: {
12569       if (CandidateSet.empty())
12570         Diag(LLoc, diag::err_ovl_no_oper)
12571           << Args[0]->getType() << /*subscript*/ 0
12572           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12573       else
12574         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12575           << Args[0]->getType()
12576           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12577       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12578                                   "[]", LLoc);
12579       return ExprError();
12580     }
12581 
12582     case OR_Ambiguous:
12583       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12584           << "[]"
12585           << Args[0]->getType() << Args[1]->getType()
12586           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12587       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12588                                   "[]", LLoc);
12589       return ExprError();
12590 
12591     case OR_Deleted:
12592       Diag(LLoc, diag::err_ovl_deleted_oper)
12593         << Best->Function->isDeleted() << "[]"
12594         << getDeletedOrUnavailableSuffix(Best->Function)
12595         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12596       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12597                                   "[]", LLoc);
12598       return ExprError();
12599     }
12600 
12601   // We matched a built-in operator; build it.
12602   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12603 }
12604 
12605 /// BuildCallToMemberFunction - Build a call to a member
12606 /// function. MemExpr is the expression that refers to the member
12607 /// function (and includes the object parameter), Args/NumArgs are the
12608 /// arguments to the function call (not including the object
12609 /// parameter). The caller needs to validate that the member
12610 /// expression refers to a non-static member function or an overloaded
12611 /// member function.
12612 ExprResult
12613 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12614                                 SourceLocation LParenLoc,
12615                                 MultiExprArg Args,
12616                                 SourceLocation RParenLoc) {
12617   assert(MemExprE->getType() == Context.BoundMemberTy ||
12618          MemExprE->getType() == Context.OverloadTy);
12619 
12620   // Dig out the member expression. This holds both the object
12621   // argument and the member function we're referring to.
12622   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12623 
12624   // Determine whether this is a call to a pointer-to-member function.
12625   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12626     assert(op->getType() == Context.BoundMemberTy);
12627     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12628 
12629     QualType fnType =
12630       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12631 
12632     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12633     QualType resultType = proto->getCallResultType(Context);
12634     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12635 
12636     // Check that the object type isn't more qualified than the
12637     // member function we're calling.
12638     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12639 
12640     QualType objectType = op->getLHS()->getType();
12641     if (op->getOpcode() == BO_PtrMemI)
12642       objectType = objectType->castAs<PointerType>()->getPointeeType();
12643     Qualifiers objectQuals = objectType.getQualifiers();
12644 
12645     Qualifiers difference = objectQuals - funcQuals;
12646     difference.removeObjCGCAttr();
12647     difference.removeAddressSpace();
12648     if (difference) {
12649       std::string qualsString = difference.getAsString();
12650       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12651         << fnType.getUnqualifiedType()
12652         << qualsString
12653         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12654     }
12655 
12656     CXXMemberCallExpr *call
12657       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12658                                         resultType, valueKind, RParenLoc);
12659 
12660     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12661                             call, nullptr))
12662       return ExprError();
12663 
12664     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12665       return ExprError();
12666 
12667     if (CheckOtherCall(call, proto))
12668       return ExprError();
12669 
12670     return MaybeBindToTemporary(call);
12671   }
12672 
12673   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12674     return new (Context)
12675         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12676 
12677   UnbridgedCastsSet UnbridgedCasts;
12678   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12679     return ExprError();
12680 
12681   MemberExpr *MemExpr;
12682   CXXMethodDecl *Method = nullptr;
12683   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12684   NestedNameSpecifier *Qualifier = nullptr;
12685   if (isa<MemberExpr>(NakedMemExpr)) {
12686     MemExpr = cast<MemberExpr>(NakedMemExpr);
12687     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12688     FoundDecl = MemExpr->getFoundDecl();
12689     Qualifier = MemExpr->getQualifier();
12690     UnbridgedCasts.restore();
12691   } else {
12692     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12693     Qualifier = UnresExpr->getQualifier();
12694 
12695     QualType ObjectType = UnresExpr->getBaseType();
12696     Expr::Classification ObjectClassification
12697       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12698                             : UnresExpr->getBase()->Classify(Context);
12699 
12700     // Add overload candidates
12701     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12702                                       OverloadCandidateSet::CSK_Normal);
12703 
12704     // FIXME: avoid copy.
12705     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12706     if (UnresExpr->hasExplicitTemplateArgs()) {
12707       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12708       TemplateArgs = &TemplateArgsBuffer;
12709     }
12710 
12711     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12712            E = UnresExpr->decls_end(); I != E; ++I) {
12713 
12714       NamedDecl *Func = *I;
12715       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12716       if (isa<UsingShadowDecl>(Func))
12717         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12718 
12719 
12720       // Microsoft supports direct constructor calls.
12721       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12722         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12723                              Args, CandidateSet);
12724       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12725         // If explicit template arguments were provided, we can't call a
12726         // non-template member function.
12727         if (TemplateArgs)
12728           continue;
12729 
12730         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12731                            ObjectClassification, Args, CandidateSet,
12732                            /*SuppressUserConversions=*/false);
12733       } else {
12734         AddMethodTemplateCandidate(
12735             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12736             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12737             /*SuppressUsedConversions=*/false);
12738       }
12739     }
12740 
12741     DeclarationName DeclName = UnresExpr->getMemberName();
12742 
12743     UnbridgedCasts.restore();
12744 
12745     OverloadCandidateSet::iterator Best;
12746     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12747                                             Best)) {
12748     case OR_Success:
12749       Method = cast<CXXMethodDecl>(Best->Function);
12750       FoundDecl = Best->FoundDecl;
12751       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12752       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12753         return ExprError();
12754       // If FoundDecl is different from Method (such as if one is a template
12755       // and the other a specialization), make sure DiagnoseUseOfDecl is
12756       // called on both.
12757       // FIXME: This would be more comprehensively addressed by modifying
12758       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12759       // being used.
12760       if (Method != FoundDecl.getDecl() &&
12761                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12762         return ExprError();
12763       break;
12764 
12765     case OR_No_Viable_Function:
12766       Diag(UnresExpr->getMemberLoc(),
12767            diag::err_ovl_no_viable_member_function_in_call)
12768         << DeclName << MemExprE->getSourceRange();
12769       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12770       // FIXME: Leaking incoming expressions!
12771       return ExprError();
12772 
12773     case OR_Ambiguous:
12774       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12775         << DeclName << MemExprE->getSourceRange();
12776       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12777       // FIXME: Leaking incoming expressions!
12778       return ExprError();
12779 
12780     case OR_Deleted:
12781       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12782         << Best->Function->isDeleted()
12783         << DeclName
12784         << getDeletedOrUnavailableSuffix(Best->Function)
12785         << MemExprE->getSourceRange();
12786       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12787       // FIXME: Leaking incoming expressions!
12788       return ExprError();
12789     }
12790 
12791     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12792 
12793     // If overload resolution picked a static member, build a
12794     // non-member call based on that function.
12795     if (Method->isStatic()) {
12796       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12797                                    RParenLoc);
12798     }
12799 
12800     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12801   }
12802 
12803   QualType ResultType = Method->getReturnType();
12804   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12805   ResultType = ResultType.getNonLValueExprType(Context);
12806 
12807   assert(Method && "Member call to something that isn't a method?");
12808   CXXMemberCallExpr *TheCall =
12809     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12810                                     ResultType, VK, RParenLoc);
12811 
12812   // Check for a valid return type.
12813   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12814                           TheCall, Method))
12815     return ExprError();
12816 
12817   // Convert the object argument (for a non-static member function call).
12818   // We only need to do this if there was actually an overload; otherwise
12819   // it was done at lookup.
12820   if (!Method->isStatic()) {
12821     ExprResult ObjectArg =
12822       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12823                                           FoundDecl, Method);
12824     if (ObjectArg.isInvalid())
12825       return ExprError();
12826     MemExpr->setBase(ObjectArg.get());
12827   }
12828 
12829   // Convert the rest of the arguments
12830   const FunctionProtoType *Proto =
12831     Method->getType()->getAs<FunctionProtoType>();
12832   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12833                               RParenLoc))
12834     return ExprError();
12835 
12836   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12837 
12838   if (CheckFunctionCall(Method, TheCall, Proto))
12839     return ExprError();
12840 
12841   // In the case the method to call was not selected by the overloading
12842   // resolution process, we still need to handle the enable_if attribute. Do
12843   // that here, so it will not hide previous -- and more relevant -- errors.
12844   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12845     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12846       Diag(MemE->getMemberLoc(),
12847            diag::err_ovl_no_viable_member_function_in_call)
12848           << Method << Method->getSourceRange();
12849       Diag(Method->getLocation(),
12850            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12851           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12852       return ExprError();
12853     }
12854   }
12855 
12856   if ((isa<CXXConstructorDecl>(CurContext) ||
12857        isa<CXXDestructorDecl>(CurContext)) &&
12858       TheCall->getMethodDecl()->isPure()) {
12859     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12860 
12861     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12862         MemExpr->performsVirtualDispatch(getLangOpts())) {
12863       Diag(MemExpr->getLocStart(),
12864            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12865         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12866         << MD->getParent()->getDeclName();
12867 
12868       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12869       if (getLangOpts().AppleKext)
12870         Diag(MemExpr->getLocStart(),
12871              diag::note_pure_qualified_call_kext)
12872              << MD->getParent()->getDeclName()
12873              << MD->getDeclName();
12874     }
12875   }
12876 
12877   if (CXXDestructorDecl *DD =
12878           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12879     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12880     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12881     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12882                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12883                          MemExpr->getMemberLoc());
12884   }
12885 
12886   return MaybeBindToTemporary(TheCall);
12887 }
12888 
12889 /// BuildCallToObjectOfClassType - Build a call to an object of class
12890 /// type (C++ [over.call.object]), which can end up invoking an
12891 /// overloaded function call operator (@c operator()) or performing a
12892 /// user-defined conversion on the object argument.
12893 ExprResult
12894 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12895                                    SourceLocation LParenLoc,
12896                                    MultiExprArg Args,
12897                                    SourceLocation RParenLoc) {
12898   if (checkPlaceholderForOverload(*this, Obj))
12899     return ExprError();
12900   ExprResult Object = Obj;
12901 
12902   UnbridgedCastsSet UnbridgedCasts;
12903   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12904     return ExprError();
12905 
12906   assert(Object.get()->getType()->isRecordType() &&
12907          "Requires object type argument");
12908   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12909 
12910   // C++ [over.call.object]p1:
12911   //  If the primary-expression E in the function call syntax
12912   //  evaluates to a class object of type "cv T", then the set of
12913   //  candidate functions includes at least the function call
12914   //  operators of T. The function call operators of T are obtained by
12915   //  ordinary lookup of the name operator() in the context of
12916   //  (E).operator().
12917   OverloadCandidateSet CandidateSet(LParenLoc,
12918                                     OverloadCandidateSet::CSK_Operator);
12919   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12920 
12921   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12922                           diag::err_incomplete_object_call, Object.get()))
12923     return true;
12924 
12925   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12926   LookupQualifiedName(R, Record->getDecl());
12927   R.suppressDiagnostics();
12928 
12929   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12930        Oper != OperEnd; ++Oper) {
12931     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12932                        Object.get()->Classify(Context), Args, CandidateSet,
12933                        /*SuppressUserConversions=*/false);
12934   }
12935 
12936   // C++ [over.call.object]p2:
12937   //   In addition, for each (non-explicit in C++0x) conversion function
12938   //   declared in T of the form
12939   //
12940   //        operator conversion-type-id () cv-qualifier;
12941   //
12942   //   where cv-qualifier is the same cv-qualification as, or a
12943   //   greater cv-qualification than, cv, and where conversion-type-id
12944   //   denotes the type "pointer to function of (P1,...,Pn) returning
12945   //   R", or the type "reference to pointer to function of
12946   //   (P1,...,Pn) returning R", or the type "reference to function
12947   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12948   //   is also considered as a candidate function. Similarly,
12949   //   surrogate call functions are added to the set of candidate
12950   //   functions for each conversion function declared in an
12951   //   accessible base class provided the function is not hidden
12952   //   within T by another intervening declaration.
12953   const auto &Conversions =
12954       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12955   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12956     NamedDecl *D = *I;
12957     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12958     if (isa<UsingShadowDecl>(D))
12959       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12960 
12961     // Skip over templated conversion functions; they aren't
12962     // surrogates.
12963     if (isa<FunctionTemplateDecl>(D))
12964       continue;
12965 
12966     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12967     if (!Conv->isExplicit()) {
12968       // Strip the reference type (if any) and then the pointer type (if
12969       // any) to get down to what might be a function type.
12970       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12971       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12972         ConvType = ConvPtrType->getPointeeType();
12973 
12974       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12975       {
12976         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12977                               Object.get(), Args, CandidateSet);
12978       }
12979     }
12980   }
12981 
12982   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12983 
12984   // Perform overload resolution.
12985   OverloadCandidateSet::iterator Best;
12986   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12987                                           Best)) {
12988   case OR_Success:
12989     // Overload resolution succeeded; we'll build the appropriate call
12990     // below.
12991     break;
12992 
12993   case OR_No_Viable_Function:
12994     if (CandidateSet.empty())
12995       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12996         << Object.get()->getType() << /*call*/ 1
12997         << Object.get()->getSourceRange();
12998     else
12999       Diag(Object.get()->getLocStart(),
13000            diag::err_ovl_no_viable_object_call)
13001         << Object.get()->getType() << Object.get()->getSourceRange();
13002     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13003     break;
13004 
13005   case OR_Ambiguous:
13006     Diag(Object.get()->getLocStart(),
13007          diag::err_ovl_ambiguous_object_call)
13008       << Object.get()->getType() << Object.get()->getSourceRange();
13009     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13010     break;
13011 
13012   case OR_Deleted:
13013     Diag(Object.get()->getLocStart(),
13014          diag::err_ovl_deleted_object_call)
13015       << Best->Function->isDeleted()
13016       << Object.get()->getType()
13017       << getDeletedOrUnavailableSuffix(Best->Function)
13018       << Object.get()->getSourceRange();
13019     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13020     break;
13021   }
13022 
13023   if (Best == CandidateSet.end())
13024     return true;
13025 
13026   UnbridgedCasts.restore();
13027 
13028   if (Best->Function == nullptr) {
13029     // Since there is no function declaration, this is one of the
13030     // surrogate candidates. Dig out the conversion function.
13031     CXXConversionDecl *Conv
13032       = cast<CXXConversionDecl>(
13033                          Best->Conversions[0].UserDefined.ConversionFunction);
13034 
13035     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13036                               Best->FoundDecl);
13037     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13038       return ExprError();
13039     assert(Conv == Best->FoundDecl.getDecl() &&
13040              "Found Decl & conversion-to-functionptr should be same, right?!");
13041     // We selected one of the surrogate functions that converts the
13042     // object parameter to a function pointer. Perform the conversion
13043     // on the object argument, then let ActOnCallExpr finish the job.
13044 
13045     // Create an implicit member expr to refer to the conversion operator.
13046     // and then call it.
13047     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13048                                              Conv, HadMultipleCandidates);
13049     if (Call.isInvalid())
13050       return ExprError();
13051     // Record usage of conversion in an implicit cast.
13052     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13053                                     CK_UserDefinedConversion, Call.get(),
13054                                     nullptr, VK_RValue);
13055 
13056     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13057   }
13058 
13059   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13060 
13061   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13062   // that calls this method, using Object for the implicit object
13063   // parameter and passing along the remaining arguments.
13064   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13065 
13066   // An error diagnostic has already been printed when parsing the declaration.
13067   if (Method->isInvalidDecl())
13068     return ExprError();
13069 
13070   const FunctionProtoType *Proto =
13071     Method->getType()->getAs<FunctionProtoType>();
13072 
13073   unsigned NumParams = Proto->getNumParams();
13074 
13075   DeclarationNameInfo OpLocInfo(
13076                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13077   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13078   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13079                                            Obj, HadMultipleCandidates,
13080                                            OpLocInfo.getLoc(),
13081                                            OpLocInfo.getInfo());
13082   if (NewFn.isInvalid())
13083     return true;
13084 
13085   // Build the full argument list for the method call (the implicit object
13086   // parameter is placed at the beginning of the list).
13087   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13088   MethodArgs[0] = Object.get();
13089   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13090 
13091   // Once we've built TheCall, all of the expressions are properly
13092   // owned.
13093   QualType ResultTy = Method->getReturnType();
13094   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13095   ResultTy = ResultTy.getNonLValueExprType(Context);
13096 
13097   CXXOperatorCallExpr *TheCall = new (Context)
13098       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13099                           VK, RParenLoc, FPOptions());
13100 
13101   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13102     return true;
13103 
13104   // We may have default arguments. If so, we need to allocate more
13105   // slots in the call for them.
13106   if (Args.size() < NumParams)
13107     TheCall->setNumArgs(Context, NumParams + 1);
13108 
13109   bool IsError = false;
13110 
13111   // Initialize the implicit object parameter.
13112   ExprResult ObjRes =
13113     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13114                                         Best->FoundDecl, Method);
13115   if (ObjRes.isInvalid())
13116     IsError = true;
13117   else
13118     Object = ObjRes;
13119   TheCall->setArg(0, Object.get());
13120 
13121   // Check the argument types.
13122   for (unsigned i = 0; i != NumParams; i++) {
13123     Expr *Arg;
13124     if (i < Args.size()) {
13125       Arg = Args[i];
13126 
13127       // Pass the argument.
13128 
13129       ExprResult InputInit
13130         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13131                                                     Context,
13132                                                     Method->getParamDecl(i)),
13133                                     SourceLocation(), Arg);
13134 
13135       IsError |= InputInit.isInvalid();
13136       Arg = InputInit.getAs<Expr>();
13137     } else {
13138       ExprResult DefArg
13139         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13140       if (DefArg.isInvalid()) {
13141         IsError = true;
13142         break;
13143       }
13144 
13145       Arg = DefArg.getAs<Expr>();
13146     }
13147 
13148     TheCall->setArg(i + 1, Arg);
13149   }
13150 
13151   // If this is a variadic call, handle args passed through "...".
13152   if (Proto->isVariadic()) {
13153     // Promote the arguments (C99 6.5.2.2p7).
13154     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13155       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13156                                                         nullptr);
13157       IsError |= Arg.isInvalid();
13158       TheCall->setArg(i + 1, Arg.get());
13159     }
13160   }
13161 
13162   if (IsError) return true;
13163 
13164   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13165 
13166   if (CheckFunctionCall(Method, TheCall, Proto))
13167     return true;
13168 
13169   return MaybeBindToTemporary(TheCall);
13170 }
13171 
13172 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13173 ///  (if one exists), where @c Base is an expression of class type and
13174 /// @c Member is the name of the member we're trying to find.
13175 ExprResult
13176 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13177                                bool *NoArrowOperatorFound) {
13178   assert(Base->getType()->isRecordType() &&
13179          "left-hand side must have class type");
13180 
13181   if (checkPlaceholderForOverload(*this, Base))
13182     return ExprError();
13183 
13184   SourceLocation Loc = Base->getExprLoc();
13185 
13186   // C++ [over.ref]p1:
13187   //
13188   //   [...] An expression x->m is interpreted as (x.operator->())->m
13189   //   for a class object x of type T if T::operator->() exists and if
13190   //   the operator is selected as the best match function by the
13191   //   overload resolution mechanism (13.3).
13192   DeclarationName OpName =
13193     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13194   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13195   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13196 
13197   if (RequireCompleteType(Loc, Base->getType(),
13198                           diag::err_typecheck_incomplete_tag, Base))
13199     return ExprError();
13200 
13201   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13202   LookupQualifiedName(R, BaseRecord->getDecl());
13203   R.suppressDiagnostics();
13204 
13205   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13206        Oper != OperEnd; ++Oper) {
13207     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13208                        None, CandidateSet, /*SuppressUserConversions=*/false);
13209   }
13210 
13211   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13212 
13213   // Perform overload resolution.
13214   OverloadCandidateSet::iterator Best;
13215   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13216   case OR_Success:
13217     // Overload resolution succeeded; we'll build the call below.
13218     break;
13219 
13220   case OR_No_Viable_Function:
13221     if (CandidateSet.empty()) {
13222       QualType BaseType = Base->getType();
13223       if (NoArrowOperatorFound) {
13224         // Report this specific error to the caller instead of emitting a
13225         // diagnostic, as requested.
13226         *NoArrowOperatorFound = true;
13227         return ExprError();
13228       }
13229       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13230         << BaseType << Base->getSourceRange();
13231       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13232         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13233           << FixItHint::CreateReplacement(OpLoc, ".");
13234       }
13235     } else
13236       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13237         << "operator->" << Base->getSourceRange();
13238     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13239     return ExprError();
13240 
13241   case OR_Ambiguous:
13242     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13243       << "->" << Base->getType() << Base->getSourceRange();
13244     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13245     return ExprError();
13246 
13247   case OR_Deleted:
13248     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13249       << Best->Function->isDeleted()
13250       << "->"
13251       << getDeletedOrUnavailableSuffix(Best->Function)
13252       << Base->getSourceRange();
13253     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13254     return ExprError();
13255   }
13256 
13257   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13258 
13259   // Convert the object parameter.
13260   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13261   ExprResult BaseResult =
13262     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13263                                         Best->FoundDecl, Method);
13264   if (BaseResult.isInvalid())
13265     return ExprError();
13266   Base = BaseResult.get();
13267 
13268   // Build the operator call.
13269   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13270                                             Base, HadMultipleCandidates, OpLoc);
13271   if (FnExpr.isInvalid())
13272     return ExprError();
13273 
13274   QualType ResultTy = Method->getReturnType();
13275   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13276   ResultTy = ResultTy.getNonLValueExprType(Context);
13277   CXXOperatorCallExpr *TheCall =
13278     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13279                                       Base, ResultTy, VK, OpLoc, FPOptions());
13280 
13281   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13282     return ExprError();
13283 
13284   if (CheckFunctionCall(Method, TheCall,
13285                         Method->getType()->castAs<FunctionProtoType>()))
13286     return ExprError();
13287 
13288   return MaybeBindToTemporary(TheCall);
13289 }
13290 
13291 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13292 /// a literal operator described by the provided lookup results.
13293 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13294                                           DeclarationNameInfo &SuffixInfo,
13295                                           ArrayRef<Expr*> Args,
13296                                           SourceLocation LitEndLoc,
13297                                        TemplateArgumentListInfo *TemplateArgs) {
13298   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13299 
13300   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13301                                     OverloadCandidateSet::CSK_Normal);
13302   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13303                         /*SuppressUserConversions=*/true);
13304 
13305   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13306 
13307   // Perform overload resolution. This will usually be trivial, but might need
13308   // to perform substitutions for a literal operator template.
13309   OverloadCandidateSet::iterator Best;
13310   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13311   case OR_Success:
13312   case OR_Deleted:
13313     break;
13314 
13315   case OR_No_Viable_Function:
13316     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13317       << R.getLookupName();
13318     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13319     return ExprError();
13320 
13321   case OR_Ambiguous:
13322     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13323     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13324     return ExprError();
13325   }
13326 
13327   FunctionDecl *FD = Best->Function;
13328   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13329                                         nullptr, HadMultipleCandidates,
13330                                         SuffixInfo.getLoc(),
13331                                         SuffixInfo.getInfo());
13332   if (Fn.isInvalid())
13333     return true;
13334 
13335   // Check the argument types. This should almost always be a no-op, except
13336   // that array-to-pointer decay is applied to string literals.
13337   Expr *ConvArgs[2];
13338   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13339     ExprResult InputInit = PerformCopyInitialization(
13340       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13341       SourceLocation(), Args[ArgIdx]);
13342     if (InputInit.isInvalid())
13343       return true;
13344     ConvArgs[ArgIdx] = InputInit.get();
13345   }
13346 
13347   QualType ResultTy = FD->getReturnType();
13348   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13349   ResultTy = ResultTy.getNonLValueExprType(Context);
13350 
13351   UserDefinedLiteral *UDL =
13352     new (Context) UserDefinedLiteral(Context, Fn.get(),
13353                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13354                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13355 
13356   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13357     return ExprError();
13358 
13359   if (CheckFunctionCall(FD, UDL, nullptr))
13360     return ExprError();
13361 
13362   return MaybeBindToTemporary(UDL);
13363 }
13364 
13365 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13366 /// given LookupResult is non-empty, it is assumed to describe a member which
13367 /// will be invoked. Otherwise, the function will be found via argument
13368 /// dependent lookup.
13369 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13370 /// otherwise CallExpr is set to ExprError() and some non-success value
13371 /// is returned.
13372 Sema::ForRangeStatus
13373 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13374                                 SourceLocation RangeLoc,
13375                                 const DeclarationNameInfo &NameInfo,
13376                                 LookupResult &MemberLookup,
13377                                 OverloadCandidateSet *CandidateSet,
13378                                 Expr *Range, ExprResult *CallExpr) {
13379   Scope *S = nullptr;
13380 
13381   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13382   if (!MemberLookup.empty()) {
13383     ExprResult MemberRef =
13384         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13385                                  /*IsPtr=*/false, CXXScopeSpec(),
13386                                  /*TemplateKWLoc=*/SourceLocation(),
13387                                  /*FirstQualifierInScope=*/nullptr,
13388                                  MemberLookup,
13389                                  /*TemplateArgs=*/nullptr, S);
13390     if (MemberRef.isInvalid()) {
13391       *CallExpr = ExprError();
13392       return FRS_DiagnosticIssued;
13393     }
13394     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13395     if (CallExpr->isInvalid()) {
13396       *CallExpr = ExprError();
13397       return FRS_DiagnosticIssued;
13398     }
13399   } else {
13400     UnresolvedSet<0> FoundNames;
13401     UnresolvedLookupExpr *Fn =
13402       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13403                                    NestedNameSpecifierLoc(), NameInfo,
13404                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13405                                    FoundNames.begin(), FoundNames.end());
13406 
13407     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13408                                                     CandidateSet, CallExpr);
13409     if (CandidateSet->empty() || CandidateSetError) {
13410       *CallExpr = ExprError();
13411       return FRS_NoViableFunction;
13412     }
13413     OverloadCandidateSet::iterator Best;
13414     OverloadingResult OverloadResult =
13415         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13416 
13417     if (OverloadResult == OR_No_Viable_Function) {
13418       *CallExpr = ExprError();
13419       return FRS_NoViableFunction;
13420     }
13421     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13422                                          Loc, nullptr, CandidateSet, &Best,
13423                                          OverloadResult,
13424                                          /*AllowTypoCorrection=*/false);
13425     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13426       *CallExpr = ExprError();
13427       return FRS_DiagnosticIssued;
13428     }
13429   }
13430   return FRS_Success;
13431 }
13432 
13433 
13434 /// FixOverloadedFunctionReference - E is an expression that refers to
13435 /// a C++ overloaded function (possibly with some parentheses and
13436 /// perhaps a '&' around it). We have resolved the overloaded function
13437 /// to the function declaration Fn, so patch up the expression E to
13438 /// refer (possibly indirectly) to Fn. Returns the new expr.
13439 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13440                                            FunctionDecl *Fn) {
13441   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13442     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13443                                                    Found, Fn);
13444     if (SubExpr == PE->getSubExpr())
13445       return PE;
13446 
13447     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13448   }
13449 
13450   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13451     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13452                                                    Found, Fn);
13453     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13454                                SubExpr->getType()) &&
13455            "Implicit cast type cannot be determined from overload");
13456     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13457     if (SubExpr == ICE->getSubExpr())
13458       return ICE;
13459 
13460     return ImplicitCastExpr::Create(Context, ICE->getType(),
13461                                     ICE->getCastKind(),
13462                                     SubExpr, nullptr,
13463                                     ICE->getValueKind());
13464   }
13465 
13466   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13467     if (!GSE->isResultDependent()) {
13468       Expr *SubExpr =
13469           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13470       if (SubExpr == GSE->getResultExpr())
13471         return GSE;
13472 
13473       // Replace the resulting type information before rebuilding the generic
13474       // selection expression.
13475       ArrayRef<Expr *> A = GSE->getAssocExprs();
13476       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13477       unsigned ResultIdx = GSE->getResultIndex();
13478       AssocExprs[ResultIdx] = SubExpr;
13479 
13480       return new (Context) GenericSelectionExpr(
13481           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13482           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13483           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13484           ResultIdx);
13485     }
13486     // Rather than fall through to the unreachable, return the original generic
13487     // selection expression.
13488     return GSE;
13489   }
13490 
13491   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13492     assert(UnOp->getOpcode() == UO_AddrOf &&
13493            "Can only take the address of an overloaded function");
13494     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13495       if (Method->isStatic()) {
13496         // Do nothing: static member functions aren't any different
13497         // from non-member functions.
13498       } else {
13499         // Fix the subexpression, which really has to be an
13500         // UnresolvedLookupExpr holding an overloaded member function
13501         // or template.
13502         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13503                                                        Found, Fn);
13504         if (SubExpr == UnOp->getSubExpr())
13505           return UnOp;
13506 
13507         assert(isa<DeclRefExpr>(SubExpr)
13508                && "fixed to something other than a decl ref");
13509         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13510                && "fixed to a member ref with no nested name qualifier");
13511 
13512         // We have taken the address of a pointer to member
13513         // function. Perform the computation here so that we get the
13514         // appropriate pointer to member type.
13515         QualType ClassType
13516           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13517         QualType MemPtrType
13518           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13519         // Under the MS ABI, lock down the inheritance model now.
13520         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13521           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13522 
13523         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13524                                            VK_RValue, OK_Ordinary,
13525                                            UnOp->getOperatorLoc());
13526       }
13527     }
13528     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13529                                                    Found, Fn);
13530     if (SubExpr == UnOp->getSubExpr())
13531       return UnOp;
13532 
13533     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13534                                      Context.getPointerType(SubExpr->getType()),
13535                                        VK_RValue, OK_Ordinary,
13536                                        UnOp->getOperatorLoc());
13537   }
13538 
13539   // C++ [except.spec]p17:
13540   //   An exception-specification is considered to be needed when:
13541   //   - in an expression the function is the unique lookup result or the
13542   //     selected member of a set of overloaded functions
13543   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13544     ResolveExceptionSpec(E->getExprLoc(), FPT);
13545 
13546   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13547     // FIXME: avoid copy.
13548     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13549     if (ULE->hasExplicitTemplateArgs()) {
13550       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13551       TemplateArgs = &TemplateArgsBuffer;
13552     }
13553 
13554     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13555                                            ULE->getQualifierLoc(),
13556                                            ULE->getTemplateKeywordLoc(),
13557                                            Fn,
13558                                            /*enclosing*/ false, // FIXME?
13559                                            ULE->getNameLoc(),
13560                                            Fn->getType(),
13561                                            VK_LValue,
13562                                            Found.getDecl(),
13563                                            TemplateArgs);
13564     MarkDeclRefReferenced(DRE);
13565     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13566     return DRE;
13567   }
13568 
13569   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13570     // FIXME: avoid copy.
13571     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13572     if (MemExpr->hasExplicitTemplateArgs()) {
13573       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13574       TemplateArgs = &TemplateArgsBuffer;
13575     }
13576 
13577     Expr *Base;
13578 
13579     // If we're filling in a static method where we used to have an
13580     // implicit member access, rewrite to a simple decl ref.
13581     if (MemExpr->isImplicitAccess()) {
13582       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13583         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13584                                                MemExpr->getQualifierLoc(),
13585                                                MemExpr->getTemplateKeywordLoc(),
13586                                                Fn,
13587                                                /*enclosing*/ false,
13588                                                MemExpr->getMemberLoc(),
13589                                                Fn->getType(),
13590                                                VK_LValue,
13591                                                Found.getDecl(),
13592                                                TemplateArgs);
13593         MarkDeclRefReferenced(DRE);
13594         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13595         return DRE;
13596       } else {
13597         SourceLocation Loc = MemExpr->getMemberLoc();
13598         if (MemExpr->getQualifier())
13599           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13600         CheckCXXThisCapture(Loc);
13601         Base = new (Context) CXXThisExpr(Loc,
13602                                          MemExpr->getBaseType(),
13603                                          /*isImplicit=*/true);
13604       }
13605     } else
13606       Base = MemExpr->getBase();
13607 
13608     ExprValueKind valueKind;
13609     QualType type;
13610     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13611       valueKind = VK_LValue;
13612       type = Fn->getType();
13613     } else {
13614       valueKind = VK_RValue;
13615       type = Context.BoundMemberTy;
13616     }
13617 
13618     MemberExpr *ME = MemberExpr::Create(
13619         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13620         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13621         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13622         OK_Ordinary);
13623     ME->setHadMultipleCandidates(true);
13624     MarkMemberReferenced(ME);
13625     return ME;
13626   }
13627 
13628   llvm_unreachable("Invalid reference to overloaded function");
13629 }
13630 
13631 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13632                                                 DeclAccessPair Found,
13633                                                 FunctionDecl *Fn) {
13634   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13635 }
13636