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 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) 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->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_Inconsistent:
632   case Sema::TDK_Underqualified: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
635     Saved->Param = Info.Param;
636     Saved->FirstArg = Info.FirstArg;
637     Saved->SecondArg = Info.SecondArg;
638     Result.Data = Saved;
639     break;
640   }
641 
642   case Sema::TDK_SubstitutionFailure:
643     Result.Data = Info.take();
644     if (Info.hasSFINAEDiagnostic()) {
645       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
646           SourceLocation(), PartialDiagnostic::NullDiagnostic());
647       Info.takeSFINAEDiagnostic(*Diag);
648       Result.HasDiagnostic = true;
649     }
650     break;
651 
652   case Sema::TDK_Success:
653   case Sema::TDK_NonDependentConversionFailure:
654     llvm_unreachable("not a deduction failure");
655   }
656 
657   return Result;
658 }
659 
660 void DeductionFailureInfo::Destroy() {
661   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662   case Sema::TDK_Success:
663   case Sema::TDK_Invalid:
664   case Sema::TDK_InstantiationDepth:
665   case Sema::TDK_Incomplete:
666   case Sema::TDK_TooManyArguments:
667   case Sema::TDK_TooFewArguments:
668   case Sema::TDK_InvalidExplicitArguments:
669   case Sema::TDK_CUDATargetMismatch:
670   case Sema::TDK_NonDependentConversionFailure:
671     break;
672 
673   case Sema::TDK_Inconsistent:
674   case Sema::TDK_Underqualified:
675   case Sema::TDK_DeducedMismatch:
676   case Sema::TDK_DeducedMismatchNested:
677   case Sema::TDK_NonDeducedMismatch:
678     // FIXME: Destroy the data?
679     Data = nullptr;
680     break;
681 
682   case Sema::TDK_SubstitutionFailure:
683     // FIXME: Destroy the template argument list?
684     Data = nullptr;
685     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
686       Diag->~PartialDiagnosticAt();
687       HasDiagnostic = false;
688     }
689     break;
690 
691   // Unhandled
692   case Sema::TDK_MiscellaneousDeductionFailure:
693     break;
694   }
695 }
696 
697 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
698   if (HasDiagnostic)
699     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
700   return nullptr;
701 }
702 
703 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
704   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
705   case Sema::TDK_Success:
706   case Sema::TDK_Invalid:
707   case Sema::TDK_InstantiationDepth:
708   case Sema::TDK_TooManyArguments:
709   case Sema::TDK_TooFewArguments:
710   case Sema::TDK_SubstitutionFailure:
711   case Sema::TDK_DeducedMismatch:
712   case Sema::TDK_DeducedMismatchNested:
713   case Sema::TDK_NonDeducedMismatch:
714   case Sema::TDK_CUDATargetMismatch:
715   case Sema::TDK_NonDependentConversionFailure:
716     return TemplateParameter();
717 
718   case Sema::TDK_Incomplete:
719   case Sema::TDK_InvalidExplicitArguments:
720     return TemplateParameter::getFromOpaqueValue(Data);
721 
722   case Sema::TDK_Inconsistent:
723   case Sema::TDK_Underqualified:
724     return static_cast<DFIParamWithArguments*>(Data)->Param;
725 
726   // Unhandled
727   case Sema::TDK_MiscellaneousDeductionFailure:
728     break;
729   }
730 
731   return TemplateParameter();
732 }
733 
734 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
735   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736   case Sema::TDK_Success:
737   case Sema::TDK_Invalid:
738   case Sema::TDK_InstantiationDepth:
739   case Sema::TDK_TooManyArguments:
740   case Sema::TDK_TooFewArguments:
741   case Sema::TDK_Incomplete:
742   case Sema::TDK_InvalidExplicitArguments:
743   case Sema::TDK_Inconsistent:
744   case Sema::TDK_Underqualified:
745   case Sema::TDK_NonDeducedMismatch:
746   case Sema::TDK_CUDATargetMismatch:
747   case Sema::TDK_NonDependentConversionFailure:
748     return nullptr;
749 
750   case Sema::TDK_DeducedMismatch:
751   case Sema::TDK_DeducedMismatchNested:
752     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
753 
754   case Sema::TDK_SubstitutionFailure:
755     return static_cast<TemplateArgumentList*>(Data);
756 
757   // Unhandled
758   case Sema::TDK_MiscellaneousDeductionFailure:
759     break;
760   }
761 
762   return nullptr;
763 }
764 
765 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
766   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
767   case Sema::TDK_Success:
768   case Sema::TDK_Invalid:
769   case Sema::TDK_InstantiationDepth:
770   case Sema::TDK_Incomplete:
771   case Sema::TDK_TooManyArguments:
772   case Sema::TDK_TooFewArguments:
773   case Sema::TDK_InvalidExplicitArguments:
774   case Sema::TDK_SubstitutionFailure:
775   case Sema::TDK_CUDATargetMismatch:
776   case Sema::TDK_NonDependentConversionFailure:
777     return nullptr;
778 
779   case Sema::TDK_Inconsistent:
780   case Sema::TDK_Underqualified:
781   case Sema::TDK_DeducedMismatch:
782   case Sema::TDK_DeducedMismatchNested:
783   case Sema::TDK_NonDeducedMismatch:
784     return &static_cast<DFIArguments*>(Data)->FirstArg;
785 
786   // Unhandled
787   case Sema::TDK_MiscellaneousDeductionFailure:
788     break;
789   }
790 
791   return nullptr;
792 }
793 
794 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
795   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
796   case Sema::TDK_Success:
797   case Sema::TDK_Invalid:
798   case Sema::TDK_InstantiationDepth:
799   case Sema::TDK_Incomplete:
800   case Sema::TDK_TooManyArguments:
801   case Sema::TDK_TooFewArguments:
802   case Sema::TDK_InvalidExplicitArguments:
803   case Sema::TDK_SubstitutionFailure:
804   case Sema::TDK_CUDATargetMismatch:
805   case Sema::TDK_NonDependentConversionFailure:
806     return nullptr;
807 
808   case Sema::TDK_Inconsistent:
809   case Sema::TDK_Underqualified:
810   case Sema::TDK_DeducedMismatch:
811   case Sema::TDK_DeducedMismatchNested:
812   case Sema::TDK_NonDeducedMismatch:
813     return &static_cast<DFIArguments*>(Data)->SecondArg;
814 
815   // Unhandled
816   case Sema::TDK_MiscellaneousDeductionFailure:
817     break;
818   }
819 
820   return nullptr;
821 }
822 
823 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
824   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
825   case Sema::TDK_DeducedMismatch:
826   case Sema::TDK_DeducedMismatchNested:
827     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
828 
829   default:
830     return llvm::None;
831   }
832 }
833 
834 void OverloadCandidateSet::destroyCandidates() {
835   for (iterator i = begin(), e = end(); i != e; ++i) {
836     for (auto &C : i->Conversions)
837       C.~ImplicitConversionSequence();
838     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
839       i->DeductionFailure.Destroy();
840   }
841 }
842 
843 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
844   destroyCandidates();
845   SlabAllocator.Reset();
846   NumInlineBytesUsed = 0;
847   Candidates.clear();
848   Functions.clear();
849   Kind = CSK;
850 }
851 
852 namespace {
853   class UnbridgedCastsSet {
854     struct Entry {
855       Expr **Addr;
856       Expr *Saved;
857     };
858     SmallVector<Entry, 2> Entries;
859 
860   public:
861     void save(Sema &S, Expr *&E) {
862       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
863       Entry entry = { &E, E };
864       Entries.push_back(entry);
865       E = S.stripARCUnbridgedCast(E);
866     }
867 
868     void restore() {
869       for (SmallVectorImpl<Entry>::iterator
870              i = Entries.begin(), e = Entries.end(); i != e; ++i)
871         *i->Addr = i->Saved;
872     }
873   };
874 }
875 
876 /// checkPlaceholderForOverload - Do any interesting placeholder-like
877 /// preprocessing on the given expression.
878 ///
879 /// \param unbridgedCasts a collection to which to add unbridged casts;
880 ///   without this, they will be immediately diagnosed as errors
881 ///
882 /// Return true on unrecoverable error.
883 static bool
884 checkPlaceholderForOverload(Sema &S, Expr *&E,
885                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
886   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
887     // We can't handle overloaded expressions here because overload
888     // resolution might reasonably tweak them.
889     if (placeholder->getKind() == BuiltinType::Overload) return false;
890 
891     // If the context potentially accepts unbridged ARC casts, strip
892     // the unbridged cast and add it to the collection for later restoration.
893     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
894         unbridgedCasts) {
895       unbridgedCasts->save(S, E);
896       return false;
897     }
898 
899     // Go ahead and check everything else.
900     ExprResult result = S.CheckPlaceholderExpr(E);
901     if (result.isInvalid())
902       return true;
903 
904     E = result.get();
905     return false;
906   }
907 
908   // Nothing to do.
909   return false;
910 }
911 
912 /// checkArgPlaceholdersForOverload - Check a set of call operands for
913 /// placeholders.
914 static bool checkArgPlaceholdersForOverload(Sema &S,
915                                             MultiExprArg Args,
916                                             UnbridgedCastsSet &unbridged) {
917   for (unsigned i = 0, e = Args.size(); i != e; ++i)
918     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
919       return true;
920 
921   return false;
922 }
923 
924 /// Determine whether the given New declaration is an overload of the
925 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
926 /// New and Old cannot be overloaded, e.g., if New has the same signature as
927 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
928 /// functions (or function templates) at all. When it does return Ovl_Match or
929 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
930 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
931 /// declaration.
932 ///
933 /// Example: Given the following input:
934 ///
935 ///   void f(int, float); // #1
936 ///   void f(int, int); // #2
937 ///   int f(int, int); // #3
938 ///
939 /// When we process #1, there is no previous declaration of "f", so IsOverload
940 /// will not be used.
941 ///
942 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
943 /// the parameter types, we see that #1 and #2 are overloaded (since they have
944 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
945 /// unchanged.
946 ///
947 /// When we process #3, Old is an overload set containing #1 and #2. We compare
948 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
949 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
950 /// functions are not part of the signature), IsOverload returns Ovl_Match and
951 /// MatchedDecl will be set to point to the FunctionDecl for #2.
952 ///
953 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
954 /// by a using declaration. The rules for whether to hide shadow declarations
955 /// ignore some properties which otherwise figure into a function template's
956 /// signature.
957 Sema::OverloadKind
958 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
959                     NamedDecl *&Match, bool NewIsUsingDecl) {
960   for (LookupResult::iterator I = Old.begin(), E = Old.end();
961          I != E; ++I) {
962     NamedDecl *OldD = *I;
963 
964     bool OldIsUsingDecl = false;
965     if (isa<UsingShadowDecl>(OldD)) {
966       OldIsUsingDecl = true;
967 
968       // We can always introduce two using declarations into the same
969       // context, even if they have identical signatures.
970       if (NewIsUsingDecl) continue;
971 
972       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
973     }
974 
975     // A using-declaration does not conflict with another declaration
976     // if one of them is hidden.
977     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
978       continue;
979 
980     // If either declaration was introduced by a using declaration,
981     // we'll need to use slightly different rules for matching.
982     // Essentially, these rules are the normal rules, except that
983     // function templates hide function templates with different
984     // return types or template parameter lists.
985     bool UseMemberUsingDeclRules =
986       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
987       !New->getFriendObjectKind();
988 
989     if (FunctionDecl *OldF = OldD->getAsFunction()) {
990       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
991         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
992           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
993           continue;
994         }
995 
996         if (!isa<FunctionTemplateDecl>(OldD) &&
997             !shouldLinkPossiblyHiddenDecl(*I, New))
998           continue;
999 
1000         Match = *I;
1001         return Ovl_Match;
1002       }
1003 
1004       // Builtins that have custom typechecking or have a reference should
1005       // not be overloadable or redeclarable.
1006       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1007         Match = *I;
1008         return Ovl_NonFunction;
1009       }
1010     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1011       // We can overload with these, which can show up when doing
1012       // redeclaration checks for UsingDecls.
1013       assert(Old.getLookupKind() == LookupUsingDeclName);
1014     } else if (isa<TagDecl>(OldD)) {
1015       // We can always overload with tags by hiding them.
1016     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1017       // Optimistically assume that an unresolved using decl will
1018       // overload; if it doesn't, we'll have to diagnose during
1019       // template instantiation.
1020       //
1021       // Exception: if the scope is dependent and this is not a class
1022       // member, the using declaration can only introduce an enumerator.
1023       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1024         Match = *I;
1025         return Ovl_NonFunction;
1026       }
1027     } else {
1028       // (C++ 13p1):
1029       //   Only function declarations can be overloaded; object and type
1030       //   declarations cannot be overloaded.
1031       Match = *I;
1032       return Ovl_NonFunction;
1033     }
1034   }
1035 
1036   return Ovl_Overload;
1037 }
1038 
1039 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1040                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1041   // C++ [basic.start.main]p2: This function shall not be overloaded.
1042   if (New->isMain())
1043     return false;
1044 
1045   // MSVCRT user defined entry points cannot be overloaded.
1046   if (New->isMSVCRTEntryPoint())
1047     return false;
1048 
1049   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1050   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1051 
1052   // C++ [temp.fct]p2:
1053   //   A function template can be overloaded with other function templates
1054   //   and with normal (non-template) functions.
1055   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1056     return true;
1057 
1058   // Is the function New an overload of the function Old?
1059   QualType OldQType = Context.getCanonicalType(Old->getType());
1060   QualType NewQType = Context.getCanonicalType(New->getType());
1061 
1062   // Compare the signatures (C++ 1.3.10) of the two functions to
1063   // determine whether they are overloads. If we find any mismatch
1064   // in the signature, they are overloads.
1065 
1066   // If either of these functions is a K&R-style function (no
1067   // prototype), then we consider them to have matching signatures.
1068   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1069       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1070     return false;
1071 
1072   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1073   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1074 
1075   // The signature of a function includes the types of its
1076   // parameters (C++ 1.3.10), which includes the presence or absence
1077   // of the ellipsis; see C++ DR 357).
1078   if (OldQType != NewQType &&
1079       (OldType->getNumParams() != NewType->getNumParams() ||
1080        OldType->isVariadic() != NewType->isVariadic() ||
1081        !FunctionParamTypesAreEqual(OldType, NewType)))
1082     return true;
1083 
1084   // C++ [temp.over.link]p4:
1085   //   The signature of a function template consists of its function
1086   //   signature, its return type and its template parameter list. The names
1087   //   of the template parameters are significant only for establishing the
1088   //   relationship between the template parameters and the rest of the
1089   //   signature.
1090   //
1091   // We check the return type and template parameter lists for function
1092   // templates first; the remaining checks follow.
1093   //
1094   // However, we don't consider either of these when deciding whether
1095   // a member introduced by a shadow declaration is hidden.
1096   if (!UseMemberUsingDeclRules && NewTemplate &&
1097       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1098                                        OldTemplate->getTemplateParameters(),
1099                                        false, TPL_TemplateMatch) ||
1100        OldType->getReturnType() != NewType->getReturnType()))
1101     return true;
1102 
1103   // If the function is a class member, its signature includes the
1104   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1105   //
1106   // As part of this, also check whether one of the member functions
1107   // is static, in which case they are not overloads (C++
1108   // 13.1p2). While not part of the definition of the signature,
1109   // this check is important to determine whether these functions
1110   // can be overloaded.
1111   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1112   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1113   if (OldMethod && NewMethod &&
1114       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1115     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1116       if (!UseMemberUsingDeclRules &&
1117           (OldMethod->getRefQualifier() == RQ_None ||
1118            NewMethod->getRefQualifier() == RQ_None)) {
1119         // C++0x [over.load]p2:
1120         //   - Member function declarations with the same name and the same
1121         //     parameter-type-list as well as member function template
1122         //     declarations with the same name, the same parameter-type-list, and
1123         //     the same template parameter lists cannot be overloaded if any of
1124         //     them, but not all, have a ref-qualifier (8.3.5).
1125         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1126           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1127         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1128       }
1129       return true;
1130     }
1131 
1132     // We may not have applied the implicit const for a constexpr member
1133     // function yet (because we haven't yet resolved whether this is a static
1134     // or non-static member function). Add it now, on the assumption that this
1135     // is a redeclaration of OldMethod.
1136     unsigned OldQuals = OldMethod->getTypeQualifiers();
1137     unsigned NewQuals = NewMethod->getTypeQualifiers();
1138     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1139         !isa<CXXConstructorDecl>(NewMethod))
1140       NewQuals |= Qualifiers::Const;
1141 
1142     // We do not allow overloading based off of '__restrict'.
1143     OldQuals &= ~Qualifiers::Restrict;
1144     NewQuals &= ~Qualifiers::Restrict;
1145     if (OldQuals != NewQuals)
1146       return true;
1147   }
1148 
1149   // Though pass_object_size is placed on parameters and takes an argument, we
1150   // consider it to be a function-level modifier for the sake of function
1151   // identity. Either the function has one or more parameters with
1152   // pass_object_size or it doesn't.
1153   if (functionHasPassObjectSizeParams(New) !=
1154       functionHasPassObjectSizeParams(Old))
1155     return true;
1156 
1157   // enable_if attributes are an order-sensitive part of the signature.
1158   for (specific_attr_iterator<EnableIfAttr>
1159          NewI = New->specific_attr_begin<EnableIfAttr>(),
1160          NewE = New->specific_attr_end<EnableIfAttr>(),
1161          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1162          OldE = Old->specific_attr_end<EnableIfAttr>();
1163        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1164     if (NewI == NewE || OldI == OldE)
1165       return true;
1166     llvm::FoldingSetNodeID NewID, OldID;
1167     NewI->getCond()->Profile(NewID, Context, true);
1168     OldI->getCond()->Profile(OldID, Context, true);
1169     if (NewID != OldID)
1170       return true;
1171   }
1172 
1173   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1174     // Don't allow overloading of destructors.  (In theory we could, but it
1175     // would be a giant change to clang.)
1176     if (isa<CXXDestructorDecl>(New))
1177       return false;
1178 
1179     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1180                        OldTarget = IdentifyCUDATarget(Old);
1181     if (NewTarget == CFT_InvalidTarget)
1182       return false;
1183 
1184     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1185 
1186     // Allow overloading of functions with same signature and different CUDA
1187     // target attributes.
1188     return NewTarget != OldTarget;
1189   }
1190 
1191   // The signatures match; this is not an overload.
1192   return false;
1193 }
1194 
1195 /// Checks availability of the function depending on the current
1196 /// function context. Inside an unavailable function, unavailability is ignored.
1197 ///
1198 /// \returns true if \arg FD is unavailable and current context is inside
1199 /// an available function, false otherwise.
1200 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1201   if (!FD->isUnavailable())
1202     return false;
1203 
1204   // Walk up the context of the caller.
1205   Decl *C = cast<Decl>(CurContext);
1206   do {
1207     if (C->isUnavailable())
1208       return false;
1209   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1210   return true;
1211 }
1212 
1213 /// Tries a user-defined conversion from From to ToType.
1214 ///
1215 /// Produces an implicit conversion sequence for when a standard conversion
1216 /// is not an option. See TryImplicitConversion for more information.
1217 static ImplicitConversionSequence
1218 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1219                          bool SuppressUserConversions,
1220                          bool AllowExplicit,
1221                          bool InOverloadResolution,
1222                          bool CStyle,
1223                          bool AllowObjCWritebackConversion,
1224                          bool AllowObjCConversionOnExplicit) {
1225   ImplicitConversionSequence ICS;
1226 
1227   if (SuppressUserConversions) {
1228     // We're not in the case above, so there is no conversion that
1229     // we can perform.
1230     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1231     return ICS;
1232   }
1233 
1234   // Attempt user-defined conversion.
1235   OverloadCandidateSet Conversions(From->getExprLoc(),
1236                                    OverloadCandidateSet::CSK_Normal);
1237   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1238                                   Conversions, AllowExplicit,
1239                                   AllowObjCConversionOnExplicit)) {
1240   case OR_Success:
1241   case OR_Deleted:
1242     ICS.setUserDefined();
1243     // C++ [over.ics.user]p4:
1244     //   A conversion of an expression of class type to the same class
1245     //   type is given Exact Match rank, and a conversion of an
1246     //   expression of class type to a base class of that type is
1247     //   given Conversion rank, in spite of the fact that a copy
1248     //   constructor (i.e., a user-defined conversion function) is
1249     //   called for those cases.
1250     if (CXXConstructorDecl *Constructor
1251           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1252       QualType FromCanon
1253         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1254       QualType ToCanon
1255         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1256       if (Constructor->isCopyConstructor() &&
1257           (FromCanon == ToCanon ||
1258            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1259         // Turn this into a "standard" conversion sequence, so that it
1260         // gets ranked with standard conversion sequences.
1261         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1262         ICS.setStandard();
1263         ICS.Standard.setAsIdentityConversion();
1264         ICS.Standard.setFromType(From->getType());
1265         ICS.Standard.setAllToTypes(ToType);
1266         ICS.Standard.CopyConstructor = Constructor;
1267         ICS.Standard.FoundCopyConstructor = Found;
1268         if (ToCanon != FromCanon)
1269           ICS.Standard.Second = ICK_Derived_To_Base;
1270       }
1271     }
1272     break;
1273 
1274   case OR_Ambiguous:
1275     ICS.setAmbiguous();
1276     ICS.Ambiguous.setFromType(From->getType());
1277     ICS.Ambiguous.setToType(ToType);
1278     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1279          Cand != Conversions.end(); ++Cand)
1280       if (Cand->Viable)
1281         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1282     break;
1283 
1284     // Fall through.
1285   case OR_No_Viable_Function:
1286     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1287     break;
1288   }
1289 
1290   return ICS;
1291 }
1292 
1293 /// TryImplicitConversion - Attempt to perform an implicit conversion
1294 /// from the given expression (Expr) to the given type (ToType). This
1295 /// function returns an implicit conversion sequence that can be used
1296 /// to perform the initialization. Given
1297 ///
1298 ///   void f(float f);
1299 ///   void g(int i) { f(i); }
1300 ///
1301 /// this routine would produce an implicit conversion sequence to
1302 /// describe the initialization of f from i, which will be a standard
1303 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1304 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1305 //
1306 /// Note that this routine only determines how the conversion can be
1307 /// performed; it does not actually perform the conversion. As such,
1308 /// it will not produce any diagnostics if no conversion is available,
1309 /// but will instead return an implicit conversion sequence of kind
1310 /// "BadConversion".
1311 ///
1312 /// If @p SuppressUserConversions, then user-defined conversions are
1313 /// not permitted.
1314 /// If @p AllowExplicit, then explicit user-defined conversions are
1315 /// permitted.
1316 ///
1317 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1318 /// writeback conversion, which allows __autoreleasing id* parameters to
1319 /// be initialized with __strong id* or __weak id* arguments.
1320 static ImplicitConversionSequence
1321 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1322                       bool SuppressUserConversions,
1323                       bool AllowExplicit,
1324                       bool InOverloadResolution,
1325                       bool CStyle,
1326                       bool AllowObjCWritebackConversion,
1327                       bool AllowObjCConversionOnExplicit) {
1328   ImplicitConversionSequence ICS;
1329   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1330                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1331     ICS.setStandard();
1332     return ICS;
1333   }
1334 
1335   if (!S.getLangOpts().CPlusPlus) {
1336     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1337     return ICS;
1338   }
1339 
1340   // C++ [over.ics.user]p4:
1341   //   A conversion of an expression of class type to the same class
1342   //   type is given Exact Match rank, and a conversion of an
1343   //   expression of class type to a base class of that type is
1344   //   given Conversion rank, in spite of the fact that a copy/move
1345   //   constructor (i.e., a user-defined conversion function) is
1346   //   called for those cases.
1347   QualType FromType = From->getType();
1348   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1349       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1350        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1351     ICS.setStandard();
1352     ICS.Standard.setAsIdentityConversion();
1353     ICS.Standard.setFromType(FromType);
1354     ICS.Standard.setAllToTypes(ToType);
1355 
1356     // We don't actually check at this point whether there is a valid
1357     // copy/move constructor, since overloading just assumes that it
1358     // exists. When we actually perform initialization, we'll find the
1359     // appropriate constructor to copy the returned object, if needed.
1360     ICS.Standard.CopyConstructor = nullptr;
1361 
1362     // Determine whether this is considered a derived-to-base conversion.
1363     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1364       ICS.Standard.Second = ICK_Derived_To_Base;
1365 
1366     return ICS;
1367   }
1368 
1369   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1370                                   AllowExplicit, InOverloadResolution, CStyle,
1371                                   AllowObjCWritebackConversion,
1372                                   AllowObjCConversionOnExplicit);
1373 }
1374 
1375 ImplicitConversionSequence
1376 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1377                             bool SuppressUserConversions,
1378                             bool AllowExplicit,
1379                             bool InOverloadResolution,
1380                             bool CStyle,
1381                             bool AllowObjCWritebackConversion) {
1382   return ::TryImplicitConversion(*this, From, ToType,
1383                                  SuppressUserConversions, AllowExplicit,
1384                                  InOverloadResolution, CStyle,
1385                                  AllowObjCWritebackConversion,
1386                                  /*AllowObjCConversionOnExplicit=*/false);
1387 }
1388 
1389 /// PerformImplicitConversion - Perform an implicit conversion of the
1390 /// expression From to the type ToType. Returns the
1391 /// converted expression. Flavor is the kind of conversion we're
1392 /// performing, used in the error message. If @p AllowExplicit,
1393 /// explicit user-defined conversions are permitted.
1394 ExprResult
1395 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1396                                 AssignmentAction Action, bool AllowExplicit) {
1397   ImplicitConversionSequence ICS;
1398   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1399 }
1400 
1401 ExprResult
1402 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1403                                 AssignmentAction Action, bool AllowExplicit,
1404                                 ImplicitConversionSequence& ICS) {
1405   if (checkPlaceholderForOverload(*this, From))
1406     return ExprError();
1407 
1408   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1409   bool AllowObjCWritebackConversion
1410     = getLangOpts().ObjCAutoRefCount &&
1411       (Action == AA_Passing || Action == AA_Sending);
1412   if (getLangOpts().ObjC1)
1413     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1414                                       ToType, From->getType(), From);
1415   ICS = ::TryImplicitConversion(*this, From, ToType,
1416                                 /*SuppressUserConversions=*/false,
1417                                 AllowExplicit,
1418                                 /*InOverloadResolution=*/false,
1419                                 /*CStyle=*/false,
1420                                 AllowObjCWritebackConversion,
1421                                 /*AllowObjCConversionOnExplicit=*/false);
1422   return PerformImplicitConversion(From, ToType, ICS, Action);
1423 }
1424 
1425 /// Determine whether the conversion from FromType to ToType is a valid
1426 /// conversion that strips "noexcept" or "noreturn" off the nested function
1427 /// type.
1428 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1429                                 QualType &ResultTy) {
1430   if (Context.hasSameUnqualifiedType(FromType, ToType))
1431     return false;
1432 
1433   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1434   //                    or F(t noexcept) -> F(t)
1435   // where F adds one of the following at most once:
1436   //   - a pointer
1437   //   - a member pointer
1438   //   - a block pointer
1439   // Changes here need matching changes in FindCompositePointerType.
1440   CanQualType CanTo = Context.getCanonicalType(ToType);
1441   CanQualType CanFrom = Context.getCanonicalType(FromType);
1442   Type::TypeClass TyClass = CanTo->getTypeClass();
1443   if (TyClass != CanFrom->getTypeClass()) return false;
1444   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1445     if (TyClass == Type::Pointer) {
1446       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1447       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1448     } else if (TyClass == Type::BlockPointer) {
1449       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1450       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1451     } else if (TyClass == Type::MemberPointer) {
1452       auto ToMPT = CanTo.getAs<MemberPointerType>();
1453       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1454       // A function pointer conversion cannot change the class of the function.
1455       if (ToMPT->getClass() != FromMPT->getClass())
1456         return false;
1457       CanTo = ToMPT->getPointeeType();
1458       CanFrom = FromMPT->getPointeeType();
1459     } else {
1460       return false;
1461     }
1462 
1463     TyClass = CanTo->getTypeClass();
1464     if (TyClass != CanFrom->getTypeClass()) return false;
1465     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1466       return false;
1467   }
1468 
1469   const auto *FromFn = cast<FunctionType>(CanFrom);
1470   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1471 
1472   const auto *ToFn = cast<FunctionType>(CanTo);
1473   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1474 
1475   bool Changed = false;
1476 
1477   // Drop 'noreturn' if not present in target type.
1478   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1479     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1480     Changed = true;
1481   }
1482 
1483   // Drop 'noexcept' if not present in target type.
1484   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1485     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1486     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1487       FromFn = cast<FunctionType>(
1488           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1489                                                    EST_None)
1490                  .getTypePtr());
1491       Changed = true;
1492     }
1493 
1494     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1495     // only if the ExtParameterInfo lists of the two function prototypes can be
1496     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1497     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1498     bool CanUseToFPT, CanUseFromFPT;
1499     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1500                                       CanUseFromFPT, NewParamInfos) &&
1501         CanUseToFPT && !CanUseFromFPT) {
1502       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1503       ExtInfo.ExtParameterInfos =
1504           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1505       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1506                                             FromFPT->getParamTypes(), ExtInfo);
1507       FromFn = QT->getAs<FunctionType>();
1508       Changed = true;
1509     }
1510   }
1511 
1512   if (!Changed)
1513     return false;
1514 
1515   assert(QualType(FromFn, 0).isCanonical());
1516   if (QualType(FromFn, 0) != CanTo) return false;
1517 
1518   ResultTy = ToType;
1519   return true;
1520 }
1521 
1522 /// Determine whether the conversion from FromType to ToType is a valid
1523 /// vector conversion.
1524 ///
1525 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1526 /// conversion.
1527 static bool IsVectorConversion(Sema &S, QualType FromType,
1528                                QualType ToType, ImplicitConversionKind &ICK) {
1529   // We need at least one of these types to be a vector type to have a vector
1530   // conversion.
1531   if (!ToType->isVectorType() && !FromType->isVectorType())
1532     return false;
1533 
1534   // Identical types require no conversions.
1535   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1536     return false;
1537 
1538   // There are no conversions between extended vector types, only identity.
1539   if (ToType->isExtVectorType()) {
1540     // There are no conversions between extended vector types other than the
1541     // identity conversion.
1542     if (FromType->isExtVectorType())
1543       return false;
1544 
1545     // Vector splat from any arithmetic type to a vector.
1546     if (FromType->isArithmeticType()) {
1547       ICK = ICK_Vector_Splat;
1548       return true;
1549     }
1550   }
1551 
1552   // We can perform the conversion between vector types in the following cases:
1553   // 1)vector types are equivalent AltiVec and GCC vector types
1554   // 2)lax vector conversions are permitted and the vector types are of the
1555   //   same size
1556   if (ToType->isVectorType() && FromType->isVectorType()) {
1557     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1558         S.isLaxVectorConversion(FromType, ToType)) {
1559       ICK = ICK_Vector_Conversion;
1560       return true;
1561     }
1562   }
1563 
1564   return false;
1565 }
1566 
1567 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1568                                 bool InOverloadResolution,
1569                                 StandardConversionSequence &SCS,
1570                                 bool CStyle);
1571 
1572 /// IsStandardConversion - Determines whether there is a standard
1573 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1574 /// expression From to the type ToType. Standard conversion sequences
1575 /// only consider non-class types; for conversions that involve class
1576 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1577 /// contain the standard conversion sequence required to perform this
1578 /// conversion and this routine will return true. Otherwise, this
1579 /// routine will return false and the value of SCS is unspecified.
1580 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1581                                  bool InOverloadResolution,
1582                                  StandardConversionSequence &SCS,
1583                                  bool CStyle,
1584                                  bool AllowObjCWritebackConversion) {
1585   QualType FromType = From->getType();
1586 
1587   // Standard conversions (C++ [conv])
1588   SCS.setAsIdentityConversion();
1589   SCS.IncompatibleObjC = false;
1590   SCS.setFromType(FromType);
1591   SCS.CopyConstructor = nullptr;
1592 
1593   // There are no standard conversions for class types in C++, so
1594   // abort early. When overloading in C, however, we do permit them.
1595   if (S.getLangOpts().CPlusPlus &&
1596       (FromType->isRecordType() || ToType->isRecordType()))
1597     return false;
1598 
1599   // The first conversion can be an lvalue-to-rvalue conversion,
1600   // array-to-pointer conversion, or function-to-pointer conversion
1601   // (C++ 4p1).
1602 
1603   if (FromType == S.Context.OverloadTy) {
1604     DeclAccessPair AccessPair;
1605     if (FunctionDecl *Fn
1606           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1607                                                  AccessPair)) {
1608       // We were able to resolve the address of the overloaded function,
1609       // so we can convert to the type of that function.
1610       FromType = Fn->getType();
1611       SCS.setFromType(FromType);
1612 
1613       // we can sometimes resolve &foo<int> regardless of ToType, so check
1614       // if the type matches (identity) or we are converting to bool
1615       if (!S.Context.hasSameUnqualifiedType(
1616                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1617         QualType resultTy;
1618         // if the function type matches except for [[noreturn]], it's ok
1619         if (!S.IsFunctionConversion(FromType,
1620               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1621           // otherwise, only a boolean conversion is standard
1622           if (!ToType->isBooleanType())
1623             return false;
1624       }
1625 
1626       // Check if the "from" expression is taking the address of an overloaded
1627       // function and recompute the FromType accordingly. Take advantage of the
1628       // fact that non-static member functions *must* have such an address-of
1629       // expression.
1630       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1631       if (Method && !Method->isStatic()) {
1632         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1633                "Non-unary operator on non-static member address");
1634         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1635                == UO_AddrOf &&
1636                "Non-address-of operator on non-static member address");
1637         const Type *ClassType
1638           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1639         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1640       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1641         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1642                UO_AddrOf &&
1643                "Non-address-of operator for overloaded function expression");
1644         FromType = S.Context.getPointerType(FromType);
1645       }
1646 
1647       // Check that we've computed the proper type after overload resolution.
1648       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1649       // be calling it from within an NDEBUG block.
1650       assert(S.Context.hasSameType(
1651         FromType,
1652         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1653     } else {
1654       return false;
1655     }
1656   }
1657   // Lvalue-to-rvalue conversion (C++11 4.1):
1658   //   A glvalue (3.10) of a non-function, non-array type T can
1659   //   be converted to a prvalue.
1660   bool argIsLValue = From->isGLValue();
1661   if (argIsLValue &&
1662       !FromType->isFunctionType() && !FromType->isArrayType() &&
1663       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1664     SCS.First = ICK_Lvalue_To_Rvalue;
1665 
1666     // C11 6.3.2.1p2:
1667     //   ... if the lvalue has atomic type, the value has the non-atomic version
1668     //   of the type of the lvalue ...
1669     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1670       FromType = Atomic->getValueType();
1671 
1672     // If T is a non-class type, the type of the rvalue is the
1673     // cv-unqualified version of T. Otherwise, the type of the rvalue
1674     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1675     // just strip the qualifiers because they don't matter.
1676     FromType = FromType.getUnqualifiedType();
1677   } else if (FromType->isArrayType()) {
1678     // Array-to-pointer conversion (C++ 4.2)
1679     SCS.First = ICK_Array_To_Pointer;
1680 
1681     // An lvalue or rvalue of type "array of N T" or "array of unknown
1682     // bound of T" can be converted to an rvalue of type "pointer to
1683     // T" (C++ 4.2p1).
1684     FromType = S.Context.getArrayDecayedType(FromType);
1685 
1686     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1687       // This conversion is deprecated in C++03 (D.4)
1688       SCS.DeprecatedStringLiteralToCharPtr = true;
1689 
1690       // For the purpose of ranking in overload resolution
1691       // (13.3.3.1.1), this conversion is considered an
1692       // array-to-pointer conversion followed by a qualification
1693       // conversion (4.4). (C++ 4.2p2)
1694       SCS.Second = ICK_Identity;
1695       SCS.Third = ICK_Qualification;
1696       SCS.QualificationIncludesObjCLifetime = false;
1697       SCS.setAllToTypes(FromType);
1698       return true;
1699     }
1700   } else if (FromType->isFunctionType() && argIsLValue) {
1701     // Function-to-pointer conversion (C++ 4.3).
1702     SCS.First = ICK_Function_To_Pointer;
1703 
1704     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1705       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1706         if (!S.checkAddressOfFunctionIsAvailable(FD))
1707           return false;
1708 
1709     // An lvalue of function type T can be converted to an rvalue of
1710     // type "pointer to T." The result is a pointer to the
1711     // function. (C++ 4.3p1).
1712     FromType = S.Context.getPointerType(FromType);
1713   } else {
1714     // We don't require any conversions for the first step.
1715     SCS.First = ICK_Identity;
1716   }
1717   SCS.setToType(0, FromType);
1718 
1719   // The second conversion can be an integral promotion, floating
1720   // point promotion, integral conversion, floating point conversion,
1721   // floating-integral conversion, pointer conversion,
1722   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1723   // For overloading in C, this can also be a "compatible-type"
1724   // conversion.
1725   bool IncompatibleObjC = false;
1726   ImplicitConversionKind SecondICK = ICK_Identity;
1727   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1728     // The unqualified versions of the types are the same: there's no
1729     // conversion to do.
1730     SCS.Second = ICK_Identity;
1731   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1732     // Integral promotion (C++ 4.5).
1733     SCS.Second = ICK_Integral_Promotion;
1734     FromType = ToType.getUnqualifiedType();
1735   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1736     // Floating point promotion (C++ 4.6).
1737     SCS.Second = ICK_Floating_Promotion;
1738     FromType = ToType.getUnqualifiedType();
1739   } else if (S.IsComplexPromotion(FromType, ToType)) {
1740     // Complex promotion (Clang extension)
1741     SCS.Second = ICK_Complex_Promotion;
1742     FromType = ToType.getUnqualifiedType();
1743   } else if (ToType->isBooleanType() &&
1744              (FromType->isArithmeticType() ||
1745               FromType->isAnyPointerType() ||
1746               FromType->isBlockPointerType() ||
1747               FromType->isMemberPointerType() ||
1748               FromType->isNullPtrType())) {
1749     // Boolean conversions (C++ 4.12).
1750     SCS.Second = ICK_Boolean_Conversion;
1751     FromType = S.Context.BoolTy;
1752   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1753              ToType->isIntegralType(S.Context)) {
1754     // Integral conversions (C++ 4.7).
1755     SCS.Second = ICK_Integral_Conversion;
1756     FromType = ToType.getUnqualifiedType();
1757   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1758     // Complex conversions (C99 6.3.1.6)
1759     SCS.Second = ICK_Complex_Conversion;
1760     FromType = ToType.getUnqualifiedType();
1761   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1762              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1763     // Complex-real conversions (C99 6.3.1.7)
1764     SCS.Second = ICK_Complex_Real;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1767     // FIXME: disable conversions between long double and __float128 if
1768     // their representation is different until there is back end support
1769     // We of course allow this conversion if long double is really double.
1770     if (&S.Context.getFloatTypeSemantics(FromType) !=
1771         &S.Context.getFloatTypeSemantics(ToType)) {
1772       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1773                                     ToType == S.Context.LongDoubleTy) ||
1774                                    (FromType == S.Context.LongDoubleTy &&
1775                                     ToType == S.Context.Float128Ty));
1776       if (Float128AndLongDouble &&
1777           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1778            &llvm::APFloat::PPCDoubleDouble()))
1779         return false;
1780     }
1781     // Floating point conversions (C++ 4.8).
1782     SCS.Second = ICK_Floating_Conversion;
1783     FromType = ToType.getUnqualifiedType();
1784   } else if ((FromType->isRealFloatingType() &&
1785               ToType->isIntegralType(S.Context)) ||
1786              (FromType->isIntegralOrUnscopedEnumerationType() &&
1787               ToType->isRealFloatingType())) {
1788     // Floating-integral conversions (C++ 4.9).
1789     SCS.Second = ICK_Floating_Integral;
1790     FromType = ToType.getUnqualifiedType();
1791   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1792     SCS.Second = ICK_Block_Pointer_Conversion;
1793   } else if (AllowObjCWritebackConversion &&
1794              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1795     SCS.Second = ICK_Writeback_Conversion;
1796   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1797                                    FromType, IncompatibleObjC)) {
1798     // Pointer conversions (C++ 4.10).
1799     SCS.Second = ICK_Pointer_Conversion;
1800     SCS.IncompatibleObjC = IncompatibleObjC;
1801     FromType = FromType.getUnqualifiedType();
1802   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1803                                          InOverloadResolution, FromType)) {
1804     // Pointer to member conversions (4.11).
1805     SCS.Second = ICK_Pointer_Member;
1806   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1807     SCS.Second = SecondICK;
1808     FromType = ToType.getUnqualifiedType();
1809   } else if (!S.getLangOpts().CPlusPlus &&
1810              S.Context.typesAreCompatible(ToType, FromType)) {
1811     // Compatible conversions (Clang extension for C function overloading)
1812     SCS.Second = ICK_Compatible_Conversion;
1813     FromType = ToType.getUnqualifiedType();
1814   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1815                                              InOverloadResolution,
1816                                              SCS, CStyle)) {
1817     SCS.Second = ICK_TransparentUnionConversion;
1818     FromType = ToType;
1819   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1820                                  CStyle)) {
1821     // tryAtomicConversion has updated the standard conversion sequence
1822     // appropriately.
1823     return true;
1824   } else if (ToType->isEventT() &&
1825              From->isIntegerConstantExpr(S.getASTContext()) &&
1826              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1827     SCS.Second = ICK_Zero_Event_Conversion;
1828     FromType = ToType;
1829   } else if (ToType->isQueueT() &&
1830              From->isIntegerConstantExpr(S.getASTContext()) &&
1831              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1832     SCS.Second = ICK_Zero_Queue_Conversion;
1833     FromType = ToType;
1834   } else {
1835     // No second conversion required.
1836     SCS.Second = ICK_Identity;
1837   }
1838   SCS.setToType(1, FromType);
1839 
1840   // The third conversion can be a function pointer conversion or a
1841   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1842   bool ObjCLifetimeConversion;
1843   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1844     // Function pointer conversions (removing 'noexcept') including removal of
1845     // 'noreturn' (Clang extension).
1846     SCS.Third = ICK_Function_Conversion;
1847   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1848                                          ObjCLifetimeConversion)) {
1849     SCS.Third = ICK_Qualification;
1850     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1851     FromType = ToType;
1852   } else {
1853     // No conversion required
1854     SCS.Third = ICK_Identity;
1855   }
1856 
1857   // C++ [over.best.ics]p6:
1858   //   [...] Any difference in top-level cv-qualification is
1859   //   subsumed by the initialization itself and does not constitute
1860   //   a conversion. [...]
1861   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1862   QualType CanonTo = S.Context.getCanonicalType(ToType);
1863   if (CanonFrom.getLocalUnqualifiedType()
1864                                      == CanonTo.getLocalUnqualifiedType() &&
1865       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1866     FromType = ToType;
1867     CanonFrom = CanonTo;
1868   }
1869 
1870   SCS.setToType(2, FromType);
1871 
1872   if (CanonFrom == CanonTo)
1873     return true;
1874 
1875   // If we have not converted the argument type to the parameter type,
1876   // this is a bad conversion sequence, unless we're resolving an overload in C.
1877   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1878     return false;
1879 
1880   ExprResult ER = ExprResult{From};
1881   Sema::AssignConvertType Conv =
1882       S.CheckSingleAssignmentConstraints(ToType, ER,
1883                                          /*Diagnose=*/false,
1884                                          /*DiagnoseCFAudited=*/false,
1885                                          /*ConvertRHS=*/false);
1886   ImplicitConversionKind SecondConv;
1887   switch (Conv) {
1888   case Sema::Compatible:
1889     SecondConv = ICK_C_Only_Conversion;
1890     break;
1891   // For our purposes, discarding qualifiers is just as bad as using an
1892   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1893   // qualifiers, as well.
1894   case Sema::CompatiblePointerDiscardsQualifiers:
1895   case Sema::IncompatiblePointer:
1896   case Sema::IncompatiblePointerSign:
1897     SecondConv = ICK_Incompatible_Pointer_Conversion;
1898     break;
1899   default:
1900     return false;
1901   }
1902 
1903   // First can only be an lvalue conversion, so we pretend that this was the
1904   // second conversion. First should already be valid from earlier in the
1905   // function.
1906   SCS.Second = SecondConv;
1907   SCS.setToType(1, ToType);
1908 
1909   // Third is Identity, because Second should rank us worse than any other
1910   // conversion. This could also be ICK_Qualification, but it's simpler to just
1911   // lump everything in with the second conversion, and we don't gain anything
1912   // from making this ICK_Qualification.
1913   SCS.Third = ICK_Identity;
1914   SCS.setToType(2, ToType);
1915   return true;
1916 }
1917 
1918 static bool
1919 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1920                                      QualType &ToType,
1921                                      bool InOverloadResolution,
1922                                      StandardConversionSequence &SCS,
1923                                      bool CStyle) {
1924 
1925   const RecordType *UT = ToType->getAsUnionType();
1926   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1927     return false;
1928   // The field to initialize within the transparent union.
1929   RecordDecl *UD = UT->getDecl();
1930   // It's compatible if the expression matches any of the fields.
1931   for (const auto *it : UD->fields()) {
1932     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1933                              CStyle, /*ObjCWritebackConversion=*/false)) {
1934       ToType = it->getType();
1935       return true;
1936     }
1937   }
1938   return false;
1939 }
1940 
1941 /// IsIntegralPromotion - Determines whether the conversion from the
1942 /// expression From (whose potentially-adjusted type is FromType) to
1943 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1944 /// sets PromotedType to the promoted type.
1945 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1946   const BuiltinType *To = ToType->getAs<BuiltinType>();
1947   // All integers are built-in.
1948   if (!To) {
1949     return false;
1950   }
1951 
1952   // An rvalue of type char, signed char, unsigned char, short int, or
1953   // unsigned short int can be converted to an rvalue of type int if
1954   // int can represent all the values of the source type; otherwise,
1955   // the source rvalue can be converted to an rvalue of type unsigned
1956   // int (C++ 4.5p1).
1957   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1958       !FromType->isEnumeralType()) {
1959     if (// We can promote any signed, promotable integer type to an int
1960         (FromType->isSignedIntegerType() ||
1961          // We can promote any unsigned integer type whose size is
1962          // less than int to an int.
1963          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1964       return To->getKind() == BuiltinType::Int;
1965     }
1966 
1967     return To->getKind() == BuiltinType::UInt;
1968   }
1969 
1970   // C++11 [conv.prom]p3:
1971   //   A prvalue of an unscoped enumeration type whose underlying type is not
1972   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1973   //   following types that can represent all the values of the enumeration
1974   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1975   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1976   //   long long int. If none of the types in that list can represent all the
1977   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1978   //   type can be converted to an rvalue a prvalue of the extended integer type
1979   //   with lowest integer conversion rank (4.13) greater than the rank of long
1980   //   long in which all the values of the enumeration can be represented. If
1981   //   there are two such extended types, the signed one is chosen.
1982   // C++11 [conv.prom]p4:
1983   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1984   //   can be converted to a prvalue of its underlying type. Moreover, if
1985   //   integral promotion can be applied to its underlying type, a prvalue of an
1986   //   unscoped enumeration type whose underlying type is fixed can also be
1987   //   converted to a prvalue of the promoted underlying type.
1988   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1989     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1990     // provided for a scoped enumeration.
1991     if (FromEnumType->getDecl()->isScoped())
1992       return false;
1993 
1994     // We can perform an integral promotion to the underlying type of the enum,
1995     // even if that's not the promoted type. Note that the check for promoting
1996     // the underlying type is based on the type alone, and does not consider
1997     // the bitfield-ness of the actual source expression.
1998     if (FromEnumType->getDecl()->isFixed()) {
1999       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2000       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2001              IsIntegralPromotion(nullptr, Underlying, ToType);
2002     }
2003 
2004     // We have already pre-calculated the promotion type, so this is trivial.
2005     if (ToType->isIntegerType() &&
2006         isCompleteType(From->getLocStart(), FromType))
2007       return Context.hasSameUnqualifiedType(
2008           ToType, FromEnumType->getDecl()->getPromotionType());
2009   }
2010 
2011   // C++0x [conv.prom]p2:
2012   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2013   //   to an rvalue a prvalue of the first of the following types that can
2014   //   represent all the values of its underlying type: int, unsigned int,
2015   //   long int, unsigned long int, long long int, or unsigned long long int.
2016   //   If none of the types in that list can represent all the values of its
2017   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2018   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2019   //   type.
2020   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2021       ToType->isIntegerType()) {
2022     // Determine whether the type we're converting from is signed or
2023     // unsigned.
2024     bool FromIsSigned = FromType->isSignedIntegerType();
2025     uint64_t FromSize = Context.getTypeSize(FromType);
2026 
2027     // The types we'll try to promote to, in the appropriate
2028     // order. Try each of these types.
2029     QualType PromoteTypes[6] = {
2030       Context.IntTy, Context.UnsignedIntTy,
2031       Context.LongTy, Context.UnsignedLongTy ,
2032       Context.LongLongTy, Context.UnsignedLongLongTy
2033     };
2034     for (int Idx = 0; Idx < 6; ++Idx) {
2035       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2036       if (FromSize < ToSize ||
2037           (FromSize == ToSize &&
2038            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2039         // We found the type that we can promote to. If this is the
2040         // type we wanted, we have a promotion. Otherwise, no
2041         // promotion.
2042         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2043       }
2044     }
2045   }
2046 
2047   // An rvalue for an integral bit-field (9.6) can be converted to an
2048   // rvalue of type int if int can represent all the values of the
2049   // bit-field; otherwise, it can be converted to unsigned int if
2050   // unsigned int can represent all the values of the bit-field. If
2051   // the bit-field is larger yet, no integral promotion applies to
2052   // it. If the bit-field has an enumerated type, it is treated as any
2053   // other value of that type for promotion purposes (C++ 4.5p3).
2054   // FIXME: We should delay checking of bit-fields until we actually perform the
2055   // conversion.
2056   if (From) {
2057     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2058       llvm::APSInt BitWidth;
2059       if (FromType->isIntegralType(Context) &&
2060           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2061         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2062         ToSize = Context.getTypeSize(ToType);
2063 
2064         // Are we promoting to an int from a bitfield that fits in an int?
2065         if (BitWidth < ToSize ||
2066             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2067           return To->getKind() == BuiltinType::Int;
2068         }
2069 
2070         // Are we promoting to an unsigned int from an unsigned bitfield
2071         // that fits into an unsigned int?
2072         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2073           return To->getKind() == BuiltinType::UInt;
2074         }
2075 
2076         return false;
2077       }
2078     }
2079   }
2080 
2081   // An rvalue of type bool can be converted to an rvalue of type int,
2082   // with false becoming zero and true becoming one (C++ 4.5p4).
2083   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2084     return true;
2085   }
2086 
2087   return false;
2088 }
2089 
2090 /// IsFloatingPointPromotion - Determines whether the conversion from
2091 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2092 /// returns true and sets PromotedType to the promoted type.
2093 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2094   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2095     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2096       /// An rvalue of type float can be converted to an rvalue of type
2097       /// double. (C++ 4.6p1).
2098       if (FromBuiltin->getKind() == BuiltinType::Float &&
2099           ToBuiltin->getKind() == BuiltinType::Double)
2100         return true;
2101 
2102       // C99 6.3.1.5p1:
2103       //   When a float is promoted to double or long double, or a
2104       //   double is promoted to long double [...].
2105       if (!getLangOpts().CPlusPlus &&
2106           (FromBuiltin->getKind() == BuiltinType::Float ||
2107            FromBuiltin->getKind() == BuiltinType::Double) &&
2108           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2109            ToBuiltin->getKind() == BuiltinType::Float128))
2110         return true;
2111 
2112       // Half can be promoted to float.
2113       if (!getLangOpts().NativeHalfType &&
2114            FromBuiltin->getKind() == BuiltinType::Half &&
2115           ToBuiltin->getKind() == BuiltinType::Float)
2116         return true;
2117     }
2118 
2119   return false;
2120 }
2121 
2122 /// Determine if a conversion is a complex promotion.
2123 ///
2124 /// A complex promotion is defined as a complex -> complex conversion
2125 /// where the conversion between the underlying real types is a
2126 /// floating-point or integral promotion.
2127 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2128   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2129   if (!FromComplex)
2130     return false;
2131 
2132   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2133   if (!ToComplex)
2134     return false;
2135 
2136   return IsFloatingPointPromotion(FromComplex->getElementType(),
2137                                   ToComplex->getElementType()) ||
2138     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2139                         ToComplex->getElementType());
2140 }
2141 
2142 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2143 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2144 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2145 /// if non-empty, will be a pointer to ToType that may or may not have
2146 /// the right set of qualifiers on its pointee.
2147 ///
2148 static QualType
2149 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2150                                    QualType ToPointee, QualType ToType,
2151                                    ASTContext &Context,
2152                                    bool StripObjCLifetime = false) {
2153   assert((FromPtr->getTypeClass() == Type::Pointer ||
2154           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2155          "Invalid similarly-qualified pointer type");
2156 
2157   /// Conversions to 'id' subsume cv-qualifier conversions.
2158   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2159     return ToType.getUnqualifiedType();
2160 
2161   QualType CanonFromPointee
2162     = Context.getCanonicalType(FromPtr->getPointeeType());
2163   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2164   Qualifiers Quals = CanonFromPointee.getQualifiers();
2165 
2166   if (StripObjCLifetime)
2167     Quals.removeObjCLifetime();
2168 
2169   // Exact qualifier match -> return the pointer type we're converting to.
2170   if (CanonToPointee.getLocalQualifiers() == Quals) {
2171     // ToType is exactly what we need. Return it.
2172     if (!ToType.isNull())
2173       return ToType.getUnqualifiedType();
2174 
2175     // Build a pointer to ToPointee. It has the right qualifiers
2176     // already.
2177     if (isa<ObjCObjectPointerType>(ToType))
2178       return Context.getObjCObjectPointerType(ToPointee);
2179     return Context.getPointerType(ToPointee);
2180   }
2181 
2182   // Just build a canonical type that has the right qualifiers.
2183   QualType QualifiedCanonToPointee
2184     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2185 
2186   if (isa<ObjCObjectPointerType>(ToType))
2187     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2188   return Context.getPointerType(QualifiedCanonToPointee);
2189 }
2190 
2191 static bool isNullPointerConstantForConversion(Expr *Expr,
2192                                                bool InOverloadResolution,
2193                                                ASTContext &Context) {
2194   // Handle value-dependent integral null pointer constants correctly.
2195   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2196   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2197       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2198     return !InOverloadResolution;
2199 
2200   return Expr->isNullPointerConstant(Context,
2201                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2202                                         : Expr::NPC_ValueDependentIsNull);
2203 }
2204 
2205 /// IsPointerConversion - Determines whether the conversion of the
2206 /// expression From, which has the (possibly adjusted) type FromType,
2207 /// can be converted to the type ToType via a pointer conversion (C++
2208 /// 4.10). If so, returns true and places the converted type (that
2209 /// might differ from ToType in its cv-qualifiers at some level) into
2210 /// ConvertedType.
2211 ///
2212 /// This routine also supports conversions to and from block pointers
2213 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2214 /// pointers to interfaces. FIXME: Once we've determined the
2215 /// appropriate overloading rules for Objective-C, we may want to
2216 /// split the Objective-C checks into a different routine; however,
2217 /// GCC seems to consider all of these conversions to be pointer
2218 /// conversions, so for now they live here. IncompatibleObjC will be
2219 /// set if the conversion is an allowed Objective-C conversion that
2220 /// should result in a warning.
2221 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2222                                bool InOverloadResolution,
2223                                QualType& ConvertedType,
2224                                bool &IncompatibleObjC) {
2225   IncompatibleObjC = false;
2226   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2227                               IncompatibleObjC))
2228     return true;
2229 
2230   // Conversion from a null pointer constant to any Objective-C pointer type.
2231   if (ToType->isObjCObjectPointerType() &&
2232       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2233     ConvertedType = ToType;
2234     return true;
2235   }
2236 
2237   // Blocks: Block pointers can be converted to void*.
2238   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2239       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2240     ConvertedType = ToType;
2241     return true;
2242   }
2243   // Blocks: A null pointer constant can be converted to a block
2244   // pointer type.
2245   if (ToType->isBlockPointerType() &&
2246       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247     ConvertedType = ToType;
2248     return true;
2249   }
2250 
2251   // If the left-hand-side is nullptr_t, the right side can be a null
2252   // pointer constant.
2253   if (ToType->isNullPtrType() &&
2254       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258 
2259   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2260   if (!ToTypePtr)
2261     return false;
2262 
2263   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2264   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2265     ConvertedType = ToType;
2266     return true;
2267   }
2268 
2269   // Beyond this point, both types need to be pointers
2270   // , including objective-c pointers.
2271   QualType ToPointeeType = ToTypePtr->getPointeeType();
2272   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2273       !getLangOpts().ObjCAutoRefCount) {
2274     ConvertedType = BuildSimilarlyQualifiedPointerType(
2275                                       FromType->getAs<ObjCObjectPointerType>(),
2276                                                        ToPointeeType,
2277                                                        ToType, Context);
2278     return true;
2279   }
2280   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2281   if (!FromTypePtr)
2282     return false;
2283 
2284   QualType FromPointeeType = FromTypePtr->getPointeeType();
2285 
2286   // If the unqualified pointee types are the same, this can't be a
2287   // pointer conversion, so don't do all of the work below.
2288   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2289     return false;
2290 
2291   // An rvalue of type "pointer to cv T," where T is an object type,
2292   // can be converted to an rvalue of type "pointer to cv void" (C++
2293   // 4.10p2).
2294   if (FromPointeeType->isIncompleteOrObjectType() &&
2295       ToPointeeType->isVoidType()) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297                                                        ToPointeeType,
2298                                                        ToType, Context,
2299                                                    /*StripObjCLifetime=*/true);
2300     return true;
2301   }
2302 
2303   // MSVC allows implicit function to void* type conversion.
2304   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2305       ToPointeeType->isVoidType()) {
2306     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2307                                                        ToPointeeType,
2308                                                        ToType, Context);
2309     return true;
2310   }
2311 
2312   // When we're overloading in C, we allow a special kind of pointer
2313   // conversion for compatible-but-not-identical pointee types.
2314   if (!getLangOpts().CPlusPlus &&
2315       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2316     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2317                                                        ToPointeeType,
2318                                                        ToType, Context);
2319     return true;
2320   }
2321 
2322   // C++ [conv.ptr]p3:
2323   //
2324   //   An rvalue of type "pointer to cv D," where D is a class type,
2325   //   can be converted to an rvalue of type "pointer to cv B," where
2326   //   B is a base class (clause 10) of D. If B is an inaccessible
2327   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2328   //   necessitates this conversion is ill-formed. The result of the
2329   //   conversion is a pointer to the base class sub-object of the
2330   //   derived class object. The null pointer value is converted to
2331   //   the null pointer value of the destination type.
2332   //
2333   // Note that we do not check for ambiguity or inaccessibility
2334   // here. That is handled by CheckPointerConversion.
2335   if (getLangOpts().CPlusPlus &&
2336       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2337       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2338       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2339     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340                                                        ToPointeeType,
2341                                                        ToType, Context);
2342     return true;
2343   }
2344 
2345   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2346       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2347     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2348                                                        ToPointeeType,
2349                                                        ToType, Context);
2350     return true;
2351   }
2352 
2353   return false;
2354 }
2355 
2356 /// Adopt the given qualifiers for the given type.
2357 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2358   Qualifiers TQs = T.getQualifiers();
2359 
2360   // Check whether qualifiers already match.
2361   if (TQs == Qs)
2362     return T;
2363 
2364   if (Qs.compatiblyIncludes(TQs))
2365     return Context.getQualifiedType(T, Qs);
2366 
2367   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2368 }
2369 
2370 /// isObjCPointerConversion - Determines whether this is an
2371 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2372 /// with the same arguments and return values.
2373 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2374                                    QualType& ConvertedType,
2375                                    bool &IncompatibleObjC) {
2376   if (!getLangOpts().ObjC1)
2377     return false;
2378 
2379   // The set of qualifiers on the type we're converting from.
2380   Qualifiers FromQualifiers = FromType.getQualifiers();
2381 
2382   // First, we handle all conversions on ObjC object pointer types.
2383   const ObjCObjectPointerType* ToObjCPtr =
2384     ToType->getAs<ObjCObjectPointerType>();
2385   const ObjCObjectPointerType *FromObjCPtr =
2386     FromType->getAs<ObjCObjectPointerType>();
2387 
2388   if (ToObjCPtr && FromObjCPtr) {
2389     // If the pointee types are the same (ignoring qualifications),
2390     // then this is not a pointer conversion.
2391     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2392                                        FromObjCPtr->getPointeeType()))
2393       return false;
2394 
2395     // Conversion between Objective-C pointers.
2396     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2397       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2398       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2399       if (getLangOpts().CPlusPlus && LHS && RHS &&
2400           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2401                                                 FromObjCPtr->getPointeeType()))
2402         return false;
2403       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2404                                                    ToObjCPtr->getPointeeType(),
2405                                                          ToType, Context);
2406       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2407       return true;
2408     }
2409 
2410     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2411       // Okay: this is some kind of implicit downcast of Objective-C
2412       // interfaces, which is permitted. However, we're going to
2413       // complain about it.
2414       IncompatibleObjC = true;
2415       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2416                                                    ToObjCPtr->getPointeeType(),
2417                                                          ToType, Context);
2418       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2419       return true;
2420     }
2421   }
2422   // Beyond this point, both types need to be C pointers or block pointers.
2423   QualType ToPointeeType;
2424   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2425     ToPointeeType = ToCPtr->getPointeeType();
2426   else if (const BlockPointerType *ToBlockPtr =
2427             ToType->getAs<BlockPointerType>()) {
2428     // Objective C++: We're able to convert from a pointer to any object
2429     // to a block pointer type.
2430     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2431       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2432       return true;
2433     }
2434     ToPointeeType = ToBlockPtr->getPointeeType();
2435   }
2436   else if (FromType->getAs<BlockPointerType>() &&
2437            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2438     // Objective C++: We're able to convert from a block pointer type to a
2439     // pointer to any object.
2440     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2441     return true;
2442   }
2443   else
2444     return false;
2445 
2446   QualType FromPointeeType;
2447   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2448     FromPointeeType = FromCPtr->getPointeeType();
2449   else if (const BlockPointerType *FromBlockPtr =
2450            FromType->getAs<BlockPointerType>())
2451     FromPointeeType = FromBlockPtr->getPointeeType();
2452   else
2453     return false;
2454 
2455   // If we have pointers to pointers, recursively check whether this
2456   // is an Objective-C conversion.
2457   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2458       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2459                               IncompatibleObjC)) {
2460     // We always complain about this conversion.
2461     IncompatibleObjC = true;
2462     ConvertedType = Context.getPointerType(ConvertedType);
2463     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2464     return true;
2465   }
2466   // Allow conversion of pointee being objective-c pointer to another one;
2467   // as in I* to id.
2468   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2469       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2470       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2471                               IncompatibleObjC)) {
2472 
2473     ConvertedType = Context.getPointerType(ConvertedType);
2474     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2475     return true;
2476   }
2477 
2478   // If we have pointers to functions or blocks, check whether the only
2479   // differences in the argument and result types are in Objective-C
2480   // pointer conversions. If so, we permit the conversion (but
2481   // complain about it).
2482   const FunctionProtoType *FromFunctionType
2483     = FromPointeeType->getAs<FunctionProtoType>();
2484   const FunctionProtoType *ToFunctionType
2485     = ToPointeeType->getAs<FunctionProtoType>();
2486   if (FromFunctionType && ToFunctionType) {
2487     // If the function types are exactly the same, this isn't an
2488     // Objective-C pointer conversion.
2489     if (Context.getCanonicalType(FromPointeeType)
2490           == Context.getCanonicalType(ToPointeeType))
2491       return false;
2492 
2493     // Perform the quick checks that will tell us whether these
2494     // function types are obviously different.
2495     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2496         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2497         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2498       return false;
2499 
2500     bool HasObjCConversion = false;
2501     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2502         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2503       // Okay, the types match exactly. Nothing to do.
2504     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2505                                        ToFunctionType->getReturnType(),
2506                                        ConvertedType, IncompatibleObjC)) {
2507       // Okay, we have an Objective-C pointer conversion.
2508       HasObjCConversion = true;
2509     } else {
2510       // Function types are too different. Abort.
2511       return false;
2512     }
2513 
2514     // Check argument types.
2515     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2516          ArgIdx != NumArgs; ++ArgIdx) {
2517       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2518       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2519       if (Context.getCanonicalType(FromArgType)
2520             == Context.getCanonicalType(ToArgType)) {
2521         // Okay, the types match exactly. Nothing to do.
2522       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2523                                          ConvertedType, IncompatibleObjC)) {
2524         // Okay, we have an Objective-C pointer conversion.
2525         HasObjCConversion = true;
2526       } else {
2527         // Argument types are too different. Abort.
2528         return false;
2529       }
2530     }
2531 
2532     if (HasObjCConversion) {
2533       // We had an Objective-C conversion. Allow this pointer
2534       // conversion, but complain about it.
2535       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2536       IncompatibleObjC = true;
2537       return true;
2538     }
2539   }
2540 
2541   return false;
2542 }
2543 
2544 /// Determine whether this is an Objective-C writeback conversion,
2545 /// used for parameter passing when performing automatic reference counting.
2546 ///
2547 /// \param FromType The type we're converting form.
2548 ///
2549 /// \param ToType The type we're converting to.
2550 ///
2551 /// \param ConvertedType The type that will be produced after applying
2552 /// this conversion.
2553 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2554                                      QualType &ConvertedType) {
2555   if (!getLangOpts().ObjCAutoRefCount ||
2556       Context.hasSameUnqualifiedType(FromType, ToType))
2557     return false;
2558 
2559   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2560   QualType ToPointee;
2561   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2562     ToPointee = ToPointer->getPointeeType();
2563   else
2564     return false;
2565 
2566   Qualifiers ToQuals = ToPointee.getQualifiers();
2567   if (!ToPointee->isObjCLifetimeType() ||
2568       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2569       !ToQuals.withoutObjCLifetime().empty())
2570     return false;
2571 
2572   // Argument must be a pointer to __strong to __weak.
2573   QualType FromPointee;
2574   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2575     FromPointee = FromPointer->getPointeeType();
2576   else
2577     return false;
2578 
2579   Qualifiers FromQuals = FromPointee.getQualifiers();
2580   if (!FromPointee->isObjCLifetimeType() ||
2581       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2582        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2583     return false;
2584 
2585   // Make sure that we have compatible qualifiers.
2586   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2587   if (!ToQuals.compatiblyIncludes(FromQuals))
2588     return false;
2589 
2590   // Remove qualifiers from the pointee type we're converting from; they
2591   // aren't used in the compatibility check belong, and we'll be adding back
2592   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2593   FromPointee = FromPointee.getUnqualifiedType();
2594 
2595   // The unqualified form of the pointee types must be compatible.
2596   ToPointee = ToPointee.getUnqualifiedType();
2597   bool IncompatibleObjC;
2598   if (Context.typesAreCompatible(FromPointee, ToPointee))
2599     FromPointee = ToPointee;
2600   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2601                                     IncompatibleObjC))
2602     return false;
2603 
2604   /// Construct the type we're converting to, which is a pointer to
2605   /// __autoreleasing pointee.
2606   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2607   ConvertedType = Context.getPointerType(FromPointee);
2608   return true;
2609 }
2610 
2611 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2612                                     QualType& ConvertedType) {
2613   QualType ToPointeeType;
2614   if (const BlockPointerType *ToBlockPtr =
2615         ToType->getAs<BlockPointerType>())
2616     ToPointeeType = ToBlockPtr->getPointeeType();
2617   else
2618     return false;
2619 
2620   QualType FromPointeeType;
2621   if (const BlockPointerType *FromBlockPtr =
2622       FromType->getAs<BlockPointerType>())
2623     FromPointeeType = FromBlockPtr->getPointeeType();
2624   else
2625     return false;
2626   // We have pointer to blocks, check whether the only
2627   // differences in the argument and result types are in Objective-C
2628   // pointer conversions. If so, we permit the conversion.
2629 
2630   const FunctionProtoType *FromFunctionType
2631     = FromPointeeType->getAs<FunctionProtoType>();
2632   const FunctionProtoType *ToFunctionType
2633     = ToPointeeType->getAs<FunctionProtoType>();
2634 
2635   if (!FromFunctionType || !ToFunctionType)
2636     return false;
2637 
2638   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2639     return true;
2640 
2641   // Perform the quick checks that will tell us whether these
2642   // function types are obviously different.
2643   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2644       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2645     return false;
2646 
2647   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2648   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2649   if (FromEInfo != ToEInfo)
2650     return false;
2651 
2652   bool IncompatibleObjC = false;
2653   if (Context.hasSameType(FromFunctionType->getReturnType(),
2654                           ToFunctionType->getReturnType())) {
2655     // Okay, the types match exactly. Nothing to do.
2656   } else {
2657     QualType RHS = FromFunctionType->getReturnType();
2658     QualType LHS = ToFunctionType->getReturnType();
2659     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2660         !RHS.hasQualifiers() && LHS.hasQualifiers())
2661        LHS = LHS.getUnqualifiedType();
2662 
2663      if (Context.hasSameType(RHS,LHS)) {
2664        // OK exact match.
2665      } else if (isObjCPointerConversion(RHS, LHS,
2666                                         ConvertedType, IncompatibleObjC)) {
2667      if (IncompatibleObjC)
2668        return false;
2669      // Okay, we have an Objective-C pointer conversion.
2670      }
2671      else
2672        return false;
2673    }
2674 
2675    // Check argument types.
2676    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2677         ArgIdx != NumArgs; ++ArgIdx) {
2678      IncompatibleObjC = false;
2679      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2680      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2681      if (Context.hasSameType(FromArgType, ToArgType)) {
2682        // Okay, the types match exactly. Nothing to do.
2683      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2684                                         ConvertedType, IncompatibleObjC)) {
2685        if (IncompatibleObjC)
2686          return false;
2687        // Okay, we have an Objective-C pointer conversion.
2688      } else
2689        // Argument types are too different. Abort.
2690        return false;
2691    }
2692 
2693    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2694    bool CanUseToFPT, CanUseFromFPT;
2695    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2696                                       CanUseToFPT, CanUseFromFPT,
2697                                       NewParamInfos))
2698      return false;
2699 
2700    ConvertedType = ToType;
2701    return true;
2702 }
2703 
2704 enum {
2705   ft_default,
2706   ft_different_class,
2707   ft_parameter_arity,
2708   ft_parameter_mismatch,
2709   ft_return_type,
2710   ft_qualifer_mismatch,
2711   ft_noexcept
2712 };
2713 
2714 /// Attempts to get the FunctionProtoType from a Type. Handles
2715 /// MemberFunctionPointers properly.
2716 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2717   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2718     return FPT;
2719 
2720   if (auto *MPT = FromType->getAs<MemberPointerType>())
2721     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2722 
2723   return nullptr;
2724 }
2725 
2726 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2727 /// function types.  Catches different number of parameter, mismatch in
2728 /// parameter types, and different return types.
2729 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2730                                       QualType FromType, QualType ToType) {
2731   // If either type is not valid, include no extra info.
2732   if (FromType.isNull() || ToType.isNull()) {
2733     PDiag << ft_default;
2734     return;
2735   }
2736 
2737   // Get the function type from the pointers.
2738   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2739     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2740                             *ToMember = ToType->getAs<MemberPointerType>();
2741     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2742       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2743             << QualType(FromMember->getClass(), 0);
2744       return;
2745     }
2746     FromType = FromMember->getPointeeType();
2747     ToType = ToMember->getPointeeType();
2748   }
2749 
2750   if (FromType->isPointerType())
2751     FromType = FromType->getPointeeType();
2752   if (ToType->isPointerType())
2753     ToType = ToType->getPointeeType();
2754 
2755   // Remove references.
2756   FromType = FromType.getNonReferenceType();
2757   ToType = ToType.getNonReferenceType();
2758 
2759   // Don't print extra info for non-specialized template functions.
2760   if (FromType->isInstantiationDependentType() &&
2761       !FromType->getAs<TemplateSpecializationType>()) {
2762     PDiag << ft_default;
2763     return;
2764   }
2765 
2766   // No extra info for same types.
2767   if (Context.hasSameType(FromType, ToType)) {
2768     PDiag << ft_default;
2769     return;
2770   }
2771 
2772   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2773                           *ToFunction = tryGetFunctionProtoType(ToType);
2774 
2775   // Both types need to be function types.
2776   if (!FromFunction || !ToFunction) {
2777     PDiag << ft_default;
2778     return;
2779   }
2780 
2781   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2782     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2783           << FromFunction->getNumParams();
2784     return;
2785   }
2786 
2787   // Handle different parameter types.
2788   unsigned ArgPos;
2789   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2790     PDiag << ft_parameter_mismatch << ArgPos + 1
2791           << ToFunction->getParamType(ArgPos)
2792           << FromFunction->getParamType(ArgPos);
2793     return;
2794   }
2795 
2796   // Handle different return type.
2797   if (!Context.hasSameType(FromFunction->getReturnType(),
2798                            ToFunction->getReturnType())) {
2799     PDiag << ft_return_type << ToFunction->getReturnType()
2800           << FromFunction->getReturnType();
2801     return;
2802   }
2803 
2804   unsigned FromQuals = FromFunction->getTypeQuals(),
2805            ToQuals = ToFunction->getTypeQuals();
2806   if (FromQuals != ToQuals) {
2807     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2808     return;
2809   }
2810 
2811   // Handle exception specification differences on canonical type (in C++17
2812   // onwards).
2813   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2814           ->isNothrow() !=
2815       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2816           ->isNothrow()) {
2817     PDiag << ft_noexcept;
2818     return;
2819   }
2820 
2821   // Unable to find a difference, so add no extra info.
2822   PDiag << ft_default;
2823 }
2824 
2825 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2826 /// for equality of their argument types. Caller has already checked that
2827 /// they have same number of arguments.  If the parameters are different,
2828 /// ArgPos will have the parameter index of the first different parameter.
2829 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2830                                       const FunctionProtoType *NewType,
2831                                       unsigned *ArgPos) {
2832   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2833                                               N = NewType->param_type_begin(),
2834                                               E = OldType->param_type_end();
2835        O && (O != E); ++O, ++N) {
2836     if (!Context.hasSameType(O->getUnqualifiedType(),
2837                              N->getUnqualifiedType())) {
2838       if (ArgPos)
2839         *ArgPos = O - OldType->param_type_begin();
2840       return false;
2841     }
2842   }
2843   return true;
2844 }
2845 
2846 /// CheckPointerConversion - Check the pointer conversion from the
2847 /// expression From to the type ToType. This routine checks for
2848 /// ambiguous or inaccessible derived-to-base pointer
2849 /// conversions for which IsPointerConversion has already returned
2850 /// true. It returns true and produces a diagnostic if there was an
2851 /// error, or returns false otherwise.
2852 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2853                                   CastKind &Kind,
2854                                   CXXCastPath& BasePath,
2855                                   bool IgnoreBaseAccess,
2856                                   bool Diagnose) {
2857   QualType FromType = From->getType();
2858   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2859 
2860   Kind = CK_BitCast;
2861 
2862   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2863       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2864           Expr::NPCK_ZeroExpression) {
2865     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2866       DiagRuntimeBehavior(From->getExprLoc(), From,
2867                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2868                             << ToType << From->getSourceRange());
2869     else if (!isUnevaluatedContext())
2870       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2871         << ToType << From->getSourceRange();
2872   }
2873   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2874     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2875       QualType FromPointeeType = FromPtrType->getPointeeType(),
2876                ToPointeeType   = ToPtrType->getPointeeType();
2877 
2878       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2879           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2880         // We must have a derived-to-base conversion. Check an
2881         // ambiguous or inaccessible conversion.
2882         unsigned InaccessibleID = 0;
2883         unsigned AmbigiousID = 0;
2884         if (Diagnose) {
2885           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2886           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2887         }
2888         if (CheckDerivedToBaseConversion(
2889                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2890                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2891                 &BasePath, IgnoreBaseAccess))
2892           return true;
2893 
2894         // The conversion was successful.
2895         Kind = CK_DerivedToBase;
2896       }
2897 
2898       if (Diagnose && !IsCStyleOrFunctionalCast &&
2899           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2900         assert(getLangOpts().MSVCCompat &&
2901                "this should only be possible with MSVCCompat!");
2902         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2903             << From->getSourceRange();
2904       }
2905     }
2906   } else if (const ObjCObjectPointerType *ToPtrType =
2907                ToType->getAs<ObjCObjectPointerType>()) {
2908     if (const ObjCObjectPointerType *FromPtrType =
2909           FromType->getAs<ObjCObjectPointerType>()) {
2910       // Objective-C++ conversions are always okay.
2911       // FIXME: We should have a different class of conversions for the
2912       // Objective-C++ implicit conversions.
2913       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2914         return false;
2915     } else if (FromType->isBlockPointerType()) {
2916       Kind = CK_BlockPointerToObjCPointerCast;
2917     } else {
2918       Kind = CK_CPointerToObjCPointerCast;
2919     }
2920   } else if (ToType->isBlockPointerType()) {
2921     if (!FromType->isBlockPointerType())
2922       Kind = CK_AnyPointerToBlockPointerCast;
2923   }
2924 
2925   // We shouldn't fall into this case unless it's valid for other
2926   // reasons.
2927   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2928     Kind = CK_NullToPointer;
2929 
2930   return false;
2931 }
2932 
2933 /// IsMemberPointerConversion - Determines whether the conversion of the
2934 /// expression From, which has the (possibly adjusted) type FromType, can be
2935 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2936 /// If so, returns true and places the converted type (that might differ from
2937 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2938 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2939                                      QualType ToType,
2940                                      bool InOverloadResolution,
2941                                      QualType &ConvertedType) {
2942   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2943   if (!ToTypePtr)
2944     return false;
2945 
2946   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2947   if (From->isNullPointerConstant(Context,
2948                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2949                                         : Expr::NPC_ValueDependentIsNull)) {
2950     ConvertedType = ToType;
2951     return true;
2952   }
2953 
2954   // Otherwise, both types have to be member pointers.
2955   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2956   if (!FromTypePtr)
2957     return false;
2958 
2959   // A pointer to member of B can be converted to a pointer to member of D,
2960   // where D is derived from B (C++ 4.11p2).
2961   QualType FromClass(FromTypePtr->getClass(), 0);
2962   QualType ToClass(ToTypePtr->getClass(), 0);
2963 
2964   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2965       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2966     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2967                                                  ToClass.getTypePtr());
2968     return true;
2969   }
2970 
2971   return false;
2972 }
2973 
2974 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2975 /// expression From to the type ToType. This routine checks for ambiguous or
2976 /// virtual or inaccessible base-to-derived member pointer conversions
2977 /// for which IsMemberPointerConversion has already returned true. It returns
2978 /// true and produces a diagnostic if there was an error, or returns false
2979 /// otherwise.
2980 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2981                                         CastKind &Kind,
2982                                         CXXCastPath &BasePath,
2983                                         bool IgnoreBaseAccess) {
2984   QualType FromType = From->getType();
2985   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2986   if (!FromPtrType) {
2987     // This must be a null pointer to member pointer conversion
2988     assert(From->isNullPointerConstant(Context,
2989                                        Expr::NPC_ValueDependentIsNull) &&
2990            "Expr must be null pointer constant!");
2991     Kind = CK_NullToMemberPointer;
2992     return false;
2993   }
2994 
2995   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2996   assert(ToPtrType && "No member pointer cast has a target type "
2997                       "that is not a member pointer.");
2998 
2999   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3000   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3001 
3002   // FIXME: What about dependent types?
3003   assert(FromClass->isRecordType() && "Pointer into non-class.");
3004   assert(ToClass->isRecordType() && "Pointer into non-class.");
3005 
3006   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3007                      /*DetectVirtual=*/true);
3008   bool DerivationOkay =
3009       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3010   assert(DerivationOkay &&
3011          "Should not have been called if derivation isn't OK.");
3012   (void)DerivationOkay;
3013 
3014   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3015                                   getUnqualifiedType())) {
3016     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3017     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3018       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3019     return true;
3020   }
3021 
3022   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3023     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3024       << FromClass << ToClass << QualType(VBase, 0)
3025       << From->getSourceRange();
3026     return true;
3027   }
3028 
3029   if (!IgnoreBaseAccess)
3030     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3031                          Paths.front(),
3032                          diag::err_downcast_from_inaccessible_base);
3033 
3034   // Must be a base to derived member conversion.
3035   BuildBasePathArray(Paths, BasePath);
3036   Kind = CK_BaseToDerivedMemberPointer;
3037   return false;
3038 }
3039 
3040 /// Determine whether the lifetime conversion between the two given
3041 /// qualifiers sets is nontrivial.
3042 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3043                                                Qualifiers ToQuals) {
3044   // Converting anything to const __unsafe_unretained is trivial.
3045   if (ToQuals.hasConst() &&
3046       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3047     return false;
3048 
3049   return true;
3050 }
3051 
3052 /// IsQualificationConversion - Determines whether the conversion from
3053 /// an rvalue of type FromType to ToType is a qualification conversion
3054 /// (C++ 4.4).
3055 ///
3056 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3057 /// when the qualification conversion involves a change in the Objective-C
3058 /// object lifetime.
3059 bool
3060 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3061                                 bool CStyle, bool &ObjCLifetimeConversion) {
3062   FromType = Context.getCanonicalType(FromType);
3063   ToType = Context.getCanonicalType(ToType);
3064   ObjCLifetimeConversion = false;
3065 
3066   // If FromType and ToType are the same type, this is not a
3067   // qualification conversion.
3068   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3069     return false;
3070 
3071   // (C++ 4.4p4):
3072   //   A conversion can add cv-qualifiers at levels other than the first
3073   //   in multi-level pointers, subject to the following rules: [...]
3074   bool PreviousToQualsIncludeConst = true;
3075   bool UnwrappedAnyPointer = false;
3076   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3077     // Within each iteration of the loop, we check the qualifiers to
3078     // determine if this still looks like a qualification
3079     // conversion. Then, if all is well, we unwrap one more level of
3080     // pointers or pointers-to-members and do it all again
3081     // until there are no more pointers or pointers-to-members left to
3082     // unwrap.
3083     UnwrappedAnyPointer = true;
3084 
3085     Qualifiers FromQuals = FromType.getQualifiers();
3086     Qualifiers ToQuals = ToType.getQualifiers();
3087 
3088     // Ignore __unaligned qualifier if this type is void.
3089     if (ToType.getUnqualifiedType()->isVoidType())
3090       FromQuals.removeUnaligned();
3091 
3092     // Objective-C ARC:
3093     //   Check Objective-C lifetime conversions.
3094     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3095         UnwrappedAnyPointer) {
3096       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3097         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3098           ObjCLifetimeConversion = true;
3099         FromQuals.removeObjCLifetime();
3100         ToQuals.removeObjCLifetime();
3101       } else {
3102         // Qualification conversions cannot cast between different
3103         // Objective-C lifetime qualifiers.
3104         return false;
3105       }
3106     }
3107 
3108     // Allow addition/removal of GC attributes but not changing GC attributes.
3109     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3110         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3111       FromQuals.removeObjCGCAttr();
3112       ToQuals.removeObjCGCAttr();
3113     }
3114 
3115     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3116     //      2,j, and similarly for volatile.
3117     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3118       return false;
3119 
3120     //   -- if the cv 1,j and cv 2,j are different, then const is in
3121     //      every cv for 0 < k < j.
3122     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3123         && !PreviousToQualsIncludeConst)
3124       return false;
3125 
3126     // Keep track of whether all prior cv-qualifiers in the "to" type
3127     // include const.
3128     PreviousToQualsIncludeConst
3129       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3130   }
3131 
3132   // We are left with FromType and ToType being the pointee types
3133   // after unwrapping the original FromType and ToType the same number
3134   // of types. If we unwrapped any pointers, and if FromType and
3135   // ToType have the same unqualified type (since we checked
3136   // qualifiers above), then this is a qualification conversion.
3137   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3138 }
3139 
3140 /// - Determine whether this is a conversion from a scalar type to an
3141 /// atomic type.
3142 ///
3143 /// If successful, updates \c SCS's second and third steps in the conversion
3144 /// sequence to finish the conversion.
3145 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3146                                 bool InOverloadResolution,
3147                                 StandardConversionSequence &SCS,
3148                                 bool CStyle) {
3149   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3150   if (!ToAtomic)
3151     return false;
3152 
3153   StandardConversionSequence InnerSCS;
3154   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3155                             InOverloadResolution, InnerSCS,
3156                             CStyle, /*AllowObjCWritebackConversion=*/false))
3157     return false;
3158 
3159   SCS.Second = InnerSCS.Second;
3160   SCS.setToType(1, InnerSCS.getToType(1));
3161   SCS.Third = InnerSCS.Third;
3162   SCS.QualificationIncludesObjCLifetime
3163     = InnerSCS.QualificationIncludesObjCLifetime;
3164   SCS.setToType(2, InnerSCS.getToType(2));
3165   return true;
3166 }
3167 
3168 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3169                                               CXXConstructorDecl *Constructor,
3170                                               QualType Type) {
3171   const FunctionProtoType *CtorType =
3172       Constructor->getType()->getAs<FunctionProtoType>();
3173   if (CtorType->getNumParams() > 0) {
3174     QualType FirstArg = CtorType->getParamType(0);
3175     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3176       return true;
3177   }
3178   return false;
3179 }
3180 
3181 static OverloadingResult
3182 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3183                                        CXXRecordDecl *To,
3184                                        UserDefinedConversionSequence &User,
3185                                        OverloadCandidateSet &CandidateSet,
3186                                        bool AllowExplicit) {
3187   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3188   for (auto *D : S.LookupConstructors(To)) {
3189     auto Info = getConstructorInfo(D);
3190     if (!Info)
3191       continue;
3192 
3193     bool Usable = !Info.Constructor->isInvalidDecl() &&
3194                   S.isInitListConstructor(Info.Constructor) &&
3195                   (AllowExplicit || !Info.Constructor->isExplicit());
3196     if (Usable) {
3197       // If the first argument is (a reference to) the target type,
3198       // suppress conversions.
3199       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3200           S.Context, Info.Constructor, ToType);
3201       if (Info.ConstructorTmpl)
3202         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3203                                        /*ExplicitArgs*/ nullptr, From,
3204                                        CandidateSet, SuppressUserConversions);
3205       else
3206         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3207                                CandidateSet, SuppressUserConversions);
3208     }
3209   }
3210 
3211   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3212 
3213   OverloadCandidateSet::iterator Best;
3214   switch (auto Result =
3215             CandidateSet.BestViableFunction(S, From->getLocStart(),
3216                                             Best)) {
3217   case OR_Deleted:
3218   case OR_Success: {
3219     // Record the standard conversion we used and the conversion function.
3220     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3221     QualType ThisType = Constructor->getThisType(S.Context);
3222     // Initializer lists don't have conversions as such.
3223     User.Before.setAsIdentityConversion();
3224     User.HadMultipleCandidates = HadMultipleCandidates;
3225     User.ConversionFunction = Constructor;
3226     User.FoundConversionFunction = Best->FoundDecl;
3227     User.After.setAsIdentityConversion();
3228     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3229     User.After.setAllToTypes(ToType);
3230     return Result;
3231   }
3232 
3233   case OR_No_Viable_Function:
3234     return OR_No_Viable_Function;
3235   case OR_Ambiguous:
3236     return OR_Ambiguous;
3237   }
3238 
3239   llvm_unreachable("Invalid OverloadResult!");
3240 }
3241 
3242 /// Determines whether there is a user-defined conversion sequence
3243 /// (C++ [over.ics.user]) that converts expression From to the type
3244 /// ToType. If such a conversion exists, User will contain the
3245 /// user-defined conversion sequence that performs such a conversion
3246 /// and this routine will return true. Otherwise, this routine returns
3247 /// false and User is unspecified.
3248 ///
3249 /// \param AllowExplicit  true if the conversion should consider C++0x
3250 /// "explicit" conversion functions as well as non-explicit conversion
3251 /// functions (C++0x [class.conv.fct]p2).
3252 ///
3253 /// \param AllowObjCConversionOnExplicit true if the conversion should
3254 /// allow an extra Objective-C pointer conversion on uses of explicit
3255 /// constructors. Requires \c AllowExplicit to also be set.
3256 static OverloadingResult
3257 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3258                         UserDefinedConversionSequence &User,
3259                         OverloadCandidateSet &CandidateSet,
3260                         bool AllowExplicit,
3261                         bool AllowObjCConversionOnExplicit) {
3262   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3263   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3264 
3265   // Whether we will only visit constructors.
3266   bool ConstructorsOnly = false;
3267 
3268   // If the type we are conversion to is a class type, enumerate its
3269   // constructors.
3270   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3271     // C++ [over.match.ctor]p1:
3272     //   When objects of class type are direct-initialized (8.5), or
3273     //   copy-initialized from an expression of the same or a
3274     //   derived class type (8.5), overload resolution selects the
3275     //   constructor. [...] For copy-initialization, the candidate
3276     //   functions are all the converting constructors (12.3.1) of
3277     //   that class. The argument list is the expression-list within
3278     //   the parentheses of the initializer.
3279     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3280         (From->getType()->getAs<RecordType>() &&
3281          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3282       ConstructorsOnly = true;
3283 
3284     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3285       // We're not going to find any constructors.
3286     } else if (CXXRecordDecl *ToRecordDecl
3287                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3288 
3289       Expr **Args = &From;
3290       unsigned NumArgs = 1;
3291       bool ListInitializing = false;
3292       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3293         // But first, see if there is an init-list-constructor that will work.
3294         OverloadingResult Result = IsInitializerListConstructorConversion(
3295             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3296         if (Result != OR_No_Viable_Function)
3297           return Result;
3298         // Never mind.
3299         CandidateSet.clear(
3300             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3301 
3302         // If we're list-initializing, we pass the individual elements as
3303         // arguments, not the entire list.
3304         Args = InitList->getInits();
3305         NumArgs = InitList->getNumInits();
3306         ListInitializing = true;
3307       }
3308 
3309       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3310         auto Info = getConstructorInfo(D);
3311         if (!Info)
3312           continue;
3313 
3314         bool Usable = !Info.Constructor->isInvalidDecl();
3315         if (ListInitializing)
3316           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3317         else
3318           Usable = Usable &&
3319                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3320         if (Usable) {
3321           bool SuppressUserConversions = !ConstructorsOnly;
3322           if (SuppressUserConversions && ListInitializing) {
3323             SuppressUserConversions = false;
3324             if (NumArgs == 1) {
3325               // If the first argument is (a reference to) the target type,
3326               // suppress conversions.
3327               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3328                   S.Context, Info.Constructor, ToType);
3329             }
3330           }
3331           if (Info.ConstructorTmpl)
3332             S.AddTemplateOverloadCandidate(
3333                 Info.ConstructorTmpl, Info.FoundDecl,
3334                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3335                 CandidateSet, SuppressUserConversions);
3336           else
3337             // Allow one user-defined conversion when user specifies a
3338             // From->ToType conversion via an static cast (c-style, etc).
3339             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3340                                    llvm::makeArrayRef(Args, NumArgs),
3341                                    CandidateSet, SuppressUserConversions);
3342         }
3343       }
3344     }
3345   }
3346 
3347   // Enumerate conversion functions, if we're allowed to.
3348   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3349   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3350     // No conversion functions from incomplete types.
3351   } else if (const RecordType *FromRecordType
3352                                    = From->getType()->getAs<RecordType>()) {
3353     if (CXXRecordDecl *FromRecordDecl
3354          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3355       // Add all of the conversion functions as candidates.
3356       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3357       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3358         DeclAccessPair FoundDecl = I.getPair();
3359         NamedDecl *D = FoundDecl.getDecl();
3360         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3361         if (isa<UsingShadowDecl>(D))
3362           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3363 
3364         CXXConversionDecl *Conv;
3365         FunctionTemplateDecl *ConvTemplate;
3366         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3367           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3368         else
3369           Conv = cast<CXXConversionDecl>(D);
3370 
3371         if (AllowExplicit || !Conv->isExplicit()) {
3372           if (ConvTemplate)
3373             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3374                                              ActingContext, From, ToType,
3375                                              CandidateSet,
3376                                              AllowObjCConversionOnExplicit);
3377           else
3378             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3379                                      From, ToType, CandidateSet,
3380                                      AllowObjCConversionOnExplicit);
3381         }
3382       }
3383     }
3384   }
3385 
3386   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3387 
3388   OverloadCandidateSet::iterator Best;
3389   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3390                                                         Best)) {
3391   case OR_Success:
3392   case OR_Deleted:
3393     // Record the standard conversion we used and the conversion function.
3394     if (CXXConstructorDecl *Constructor
3395           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3396       // C++ [over.ics.user]p1:
3397       //   If the user-defined conversion is specified by a
3398       //   constructor (12.3.1), the initial standard conversion
3399       //   sequence converts the source type to the type required by
3400       //   the argument of the constructor.
3401       //
3402       QualType ThisType = Constructor->getThisType(S.Context);
3403       if (isa<InitListExpr>(From)) {
3404         // Initializer lists don't have conversions as such.
3405         User.Before.setAsIdentityConversion();
3406       } else {
3407         if (Best->Conversions[0].isEllipsis())
3408           User.EllipsisConversion = true;
3409         else {
3410           User.Before = Best->Conversions[0].Standard;
3411           User.EllipsisConversion = false;
3412         }
3413       }
3414       User.HadMultipleCandidates = HadMultipleCandidates;
3415       User.ConversionFunction = Constructor;
3416       User.FoundConversionFunction = Best->FoundDecl;
3417       User.After.setAsIdentityConversion();
3418       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3419       User.After.setAllToTypes(ToType);
3420       return Result;
3421     }
3422     if (CXXConversionDecl *Conversion
3423                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3424       // C++ [over.ics.user]p1:
3425       //
3426       //   [...] If the user-defined conversion is specified by a
3427       //   conversion function (12.3.2), the initial standard
3428       //   conversion sequence converts the source type to the
3429       //   implicit object parameter of the conversion function.
3430       User.Before = Best->Conversions[0].Standard;
3431       User.HadMultipleCandidates = HadMultipleCandidates;
3432       User.ConversionFunction = Conversion;
3433       User.FoundConversionFunction = Best->FoundDecl;
3434       User.EllipsisConversion = false;
3435 
3436       // C++ [over.ics.user]p2:
3437       //   The second standard conversion sequence converts the
3438       //   result of the user-defined conversion to the target type
3439       //   for the sequence. Since an implicit conversion sequence
3440       //   is an initialization, the special rules for
3441       //   initialization by user-defined conversion apply when
3442       //   selecting the best user-defined conversion for a
3443       //   user-defined conversion sequence (see 13.3.3 and
3444       //   13.3.3.1).
3445       User.After = Best->FinalConversion;
3446       return Result;
3447     }
3448     llvm_unreachable("Not a constructor or conversion function?");
3449 
3450   case OR_No_Viable_Function:
3451     return OR_No_Viable_Function;
3452 
3453   case OR_Ambiguous:
3454     return OR_Ambiguous;
3455   }
3456 
3457   llvm_unreachable("Invalid OverloadResult!");
3458 }
3459 
3460 bool
3461 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3462   ImplicitConversionSequence ICS;
3463   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3464                                     OverloadCandidateSet::CSK_Normal);
3465   OverloadingResult OvResult =
3466     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3467                             CandidateSet, false, false);
3468   if (OvResult == OR_Ambiguous)
3469     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3470         << From->getType() << ToType << From->getSourceRange();
3471   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3472     if (!RequireCompleteType(From->getLocStart(), ToType,
3473                              diag::err_typecheck_nonviable_condition_incomplete,
3474                              From->getType(), From->getSourceRange()))
3475       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3476           << false << From->getType() << From->getSourceRange() << ToType;
3477   } else
3478     return false;
3479   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3480   return true;
3481 }
3482 
3483 /// Compare the user-defined conversion functions or constructors
3484 /// of two user-defined conversion sequences to determine whether any ordering
3485 /// is possible.
3486 static ImplicitConversionSequence::CompareKind
3487 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3488                            FunctionDecl *Function2) {
3489   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3490     return ImplicitConversionSequence::Indistinguishable;
3491 
3492   // Objective-C++:
3493   //   If both conversion functions are implicitly-declared conversions from
3494   //   a lambda closure type to a function pointer and a block pointer,
3495   //   respectively, always prefer the conversion to a function pointer,
3496   //   because the function pointer is more lightweight and is more likely
3497   //   to keep code working.
3498   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3499   if (!Conv1)
3500     return ImplicitConversionSequence::Indistinguishable;
3501 
3502   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3503   if (!Conv2)
3504     return ImplicitConversionSequence::Indistinguishable;
3505 
3506   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3507     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3508     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3509     if (Block1 != Block2)
3510       return Block1 ? ImplicitConversionSequence::Worse
3511                     : ImplicitConversionSequence::Better;
3512   }
3513 
3514   return ImplicitConversionSequence::Indistinguishable;
3515 }
3516 
3517 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3518     const ImplicitConversionSequence &ICS) {
3519   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3520          (ICS.isUserDefined() &&
3521           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3522 }
3523 
3524 /// CompareImplicitConversionSequences - Compare two implicit
3525 /// conversion sequences to determine whether one is better than the
3526 /// other or if they are indistinguishable (C++ 13.3.3.2).
3527 static ImplicitConversionSequence::CompareKind
3528 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3529                                    const ImplicitConversionSequence& ICS1,
3530                                    const ImplicitConversionSequence& ICS2)
3531 {
3532   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3533   // conversion sequences (as defined in 13.3.3.1)
3534   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3535   //      conversion sequence than a user-defined conversion sequence or
3536   //      an ellipsis conversion sequence, and
3537   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3538   //      conversion sequence than an ellipsis conversion sequence
3539   //      (13.3.3.1.3).
3540   //
3541   // C++0x [over.best.ics]p10:
3542   //   For the purpose of ranking implicit conversion sequences as
3543   //   described in 13.3.3.2, the ambiguous conversion sequence is
3544   //   treated as a user-defined sequence that is indistinguishable
3545   //   from any other user-defined conversion sequence.
3546 
3547   // String literal to 'char *' conversion has been deprecated in C++03. It has
3548   // been removed from C++11. We still accept this conversion, if it happens at
3549   // the best viable function. Otherwise, this conversion is considered worse
3550   // than ellipsis conversion. Consider this as an extension; this is not in the
3551   // standard. For example:
3552   //
3553   // int &f(...);    // #1
3554   // void f(char*);  // #2
3555   // void g() { int &r = f("foo"); }
3556   //
3557   // In C++03, we pick #2 as the best viable function.
3558   // In C++11, we pick #1 as the best viable function, because ellipsis
3559   // conversion is better than string-literal to char* conversion (since there
3560   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3561   // convert arguments, #2 would be the best viable function in C++11.
3562   // If the best viable function has this conversion, a warning will be issued
3563   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3564 
3565   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3566       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3567       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3568     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3569                ? ImplicitConversionSequence::Worse
3570                : ImplicitConversionSequence::Better;
3571 
3572   if (ICS1.getKindRank() < ICS2.getKindRank())
3573     return ImplicitConversionSequence::Better;
3574   if (ICS2.getKindRank() < ICS1.getKindRank())
3575     return ImplicitConversionSequence::Worse;
3576 
3577   // The following checks require both conversion sequences to be of
3578   // the same kind.
3579   if (ICS1.getKind() != ICS2.getKind())
3580     return ImplicitConversionSequence::Indistinguishable;
3581 
3582   ImplicitConversionSequence::CompareKind Result =
3583       ImplicitConversionSequence::Indistinguishable;
3584 
3585   // Two implicit conversion sequences of the same form are
3586   // indistinguishable conversion sequences unless one of the
3587   // following rules apply: (C++ 13.3.3.2p3):
3588 
3589   // List-initialization sequence L1 is a better conversion sequence than
3590   // list-initialization sequence L2 if:
3591   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3592   //   if not that,
3593   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3594   //   and N1 is smaller than N2.,
3595   // even if one of the other rules in this paragraph would otherwise apply.
3596   if (!ICS1.isBad()) {
3597     if (ICS1.isStdInitializerListElement() &&
3598         !ICS2.isStdInitializerListElement())
3599       return ImplicitConversionSequence::Better;
3600     if (!ICS1.isStdInitializerListElement() &&
3601         ICS2.isStdInitializerListElement())
3602       return ImplicitConversionSequence::Worse;
3603   }
3604 
3605   if (ICS1.isStandard())
3606     // Standard conversion sequence S1 is a better conversion sequence than
3607     // standard conversion sequence S2 if [...]
3608     Result = CompareStandardConversionSequences(S, Loc,
3609                                                 ICS1.Standard, ICS2.Standard);
3610   else if (ICS1.isUserDefined()) {
3611     // User-defined conversion sequence U1 is a better conversion
3612     // sequence than another user-defined conversion sequence U2 if
3613     // they contain the same user-defined conversion function or
3614     // constructor and if the second standard conversion sequence of
3615     // U1 is better than the second standard conversion sequence of
3616     // U2 (C++ 13.3.3.2p3).
3617     if (ICS1.UserDefined.ConversionFunction ==
3618           ICS2.UserDefined.ConversionFunction)
3619       Result = CompareStandardConversionSequences(S, Loc,
3620                                                   ICS1.UserDefined.After,
3621                                                   ICS2.UserDefined.After);
3622     else
3623       Result = compareConversionFunctions(S,
3624                                           ICS1.UserDefined.ConversionFunction,
3625                                           ICS2.UserDefined.ConversionFunction);
3626   }
3627 
3628   return Result;
3629 }
3630 
3631 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3632   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3633     Qualifiers Quals;
3634     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3635     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3636   }
3637 
3638   return Context.hasSameUnqualifiedType(T1, T2);
3639 }
3640 
3641 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3642 // determine if one is a proper subset of the other.
3643 static ImplicitConversionSequence::CompareKind
3644 compareStandardConversionSubsets(ASTContext &Context,
3645                                  const StandardConversionSequence& SCS1,
3646                                  const StandardConversionSequence& SCS2) {
3647   ImplicitConversionSequence::CompareKind Result
3648     = ImplicitConversionSequence::Indistinguishable;
3649 
3650   // the identity conversion sequence is considered to be a subsequence of
3651   // any non-identity conversion sequence
3652   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3653     return ImplicitConversionSequence::Better;
3654   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3655     return ImplicitConversionSequence::Worse;
3656 
3657   if (SCS1.Second != SCS2.Second) {
3658     if (SCS1.Second == ICK_Identity)
3659       Result = ImplicitConversionSequence::Better;
3660     else if (SCS2.Second == ICK_Identity)
3661       Result = ImplicitConversionSequence::Worse;
3662     else
3663       return ImplicitConversionSequence::Indistinguishable;
3664   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3665     return ImplicitConversionSequence::Indistinguishable;
3666 
3667   if (SCS1.Third == SCS2.Third) {
3668     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3669                              : ImplicitConversionSequence::Indistinguishable;
3670   }
3671 
3672   if (SCS1.Third == ICK_Identity)
3673     return Result == ImplicitConversionSequence::Worse
3674              ? ImplicitConversionSequence::Indistinguishable
3675              : ImplicitConversionSequence::Better;
3676 
3677   if (SCS2.Third == ICK_Identity)
3678     return Result == ImplicitConversionSequence::Better
3679              ? ImplicitConversionSequence::Indistinguishable
3680              : ImplicitConversionSequence::Worse;
3681 
3682   return ImplicitConversionSequence::Indistinguishable;
3683 }
3684 
3685 /// Determine whether one of the given reference bindings is better
3686 /// than the other based on what kind of bindings they are.
3687 static bool
3688 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3689                              const StandardConversionSequence &SCS2) {
3690   // C++0x [over.ics.rank]p3b4:
3691   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3692   //      implicit object parameter of a non-static member function declared
3693   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3694   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3695   //      lvalue reference to a function lvalue and S2 binds an rvalue
3696   //      reference*.
3697   //
3698   // FIXME: Rvalue references. We're going rogue with the above edits,
3699   // because the semantics in the current C++0x working paper (N3225 at the
3700   // time of this writing) break the standard definition of std::forward
3701   // and std::reference_wrapper when dealing with references to functions.
3702   // Proposed wording changes submitted to CWG for consideration.
3703   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3704       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3705     return false;
3706 
3707   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3708           SCS2.IsLvalueReference) ||
3709          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3710           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3711 }
3712 
3713 /// CompareStandardConversionSequences - Compare two standard
3714 /// conversion sequences to determine whether one is better than the
3715 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3716 static ImplicitConversionSequence::CompareKind
3717 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3718                                    const StandardConversionSequence& SCS1,
3719                                    const StandardConversionSequence& SCS2)
3720 {
3721   // Standard conversion sequence S1 is a better conversion sequence
3722   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3723 
3724   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3725   //     sequences in the canonical form defined by 13.3.3.1.1,
3726   //     excluding any Lvalue Transformation; the identity conversion
3727   //     sequence is considered to be a subsequence of any
3728   //     non-identity conversion sequence) or, if not that,
3729   if (ImplicitConversionSequence::CompareKind CK
3730         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3731     return CK;
3732 
3733   //  -- the rank of S1 is better than the rank of S2 (by the rules
3734   //     defined below), or, if not that,
3735   ImplicitConversionRank Rank1 = SCS1.getRank();
3736   ImplicitConversionRank Rank2 = SCS2.getRank();
3737   if (Rank1 < Rank2)
3738     return ImplicitConversionSequence::Better;
3739   else if (Rank2 < Rank1)
3740     return ImplicitConversionSequence::Worse;
3741 
3742   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3743   // are indistinguishable unless one of the following rules
3744   // applies:
3745 
3746   //   A conversion that is not a conversion of a pointer, or
3747   //   pointer to member, to bool is better than another conversion
3748   //   that is such a conversion.
3749   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3750     return SCS2.isPointerConversionToBool()
3751              ? ImplicitConversionSequence::Better
3752              : ImplicitConversionSequence::Worse;
3753 
3754   // C++ [over.ics.rank]p4b2:
3755   //
3756   //   If class B is derived directly or indirectly from class A,
3757   //   conversion of B* to A* is better than conversion of B* to
3758   //   void*, and conversion of A* to void* is better than conversion
3759   //   of B* to void*.
3760   bool SCS1ConvertsToVoid
3761     = SCS1.isPointerConversionToVoidPointer(S.Context);
3762   bool SCS2ConvertsToVoid
3763     = SCS2.isPointerConversionToVoidPointer(S.Context);
3764   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3765     // Exactly one of the conversion sequences is a conversion to
3766     // a void pointer; it's the worse conversion.
3767     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3768                               : ImplicitConversionSequence::Worse;
3769   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3770     // Neither conversion sequence converts to a void pointer; compare
3771     // their derived-to-base conversions.
3772     if (ImplicitConversionSequence::CompareKind DerivedCK
3773           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3774       return DerivedCK;
3775   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3776              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3777     // Both conversion sequences are conversions to void
3778     // pointers. Compare the source types to determine if there's an
3779     // inheritance relationship in their sources.
3780     QualType FromType1 = SCS1.getFromType();
3781     QualType FromType2 = SCS2.getFromType();
3782 
3783     // Adjust the types we're converting from via the array-to-pointer
3784     // conversion, if we need to.
3785     if (SCS1.First == ICK_Array_To_Pointer)
3786       FromType1 = S.Context.getArrayDecayedType(FromType1);
3787     if (SCS2.First == ICK_Array_To_Pointer)
3788       FromType2 = S.Context.getArrayDecayedType(FromType2);
3789 
3790     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3791     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3792 
3793     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3794       return ImplicitConversionSequence::Better;
3795     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3796       return ImplicitConversionSequence::Worse;
3797 
3798     // Objective-C++: If one interface is more specific than the
3799     // other, it is the better one.
3800     const ObjCObjectPointerType* FromObjCPtr1
3801       = FromType1->getAs<ObjCObjectPointerType>();
3802     const ObjCObjectPointerType* FromObjCPtr2
3803       = FromType2->getAs<ObjCObjectPointerType>();
3804     if (FromObjCPtr1 && FromObjCPtr2) {
3805       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3806                                                           FromObjCPtr2);
3807       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3808                                                            FromObjCPtr1);
3809       if (AssignLeft != AssignRight) {
3810         return AssignLeft? ImplicitConversionSequence::Better
3811                          : ImplicitConversionSequence::Worse;
3812       }
3813     }
3814   }
3815 
3816   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3817   // bullet 3).
3818   if (ImplicitConversionSequence::CompareKind QualCK
3819         = CompareQualificationConversions(S, SCS1, SCS2))
3820     return QualCK;
3821 
3822   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3823     // Check for a better reference binding based on the kind of bindings.
3824     if (isBetterReferenceBindingKind(SCS1, SCS2))
3825       return ImplicitConversionSequence::Better;
3826     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3827       return ImplicitConversionSequence::Worse;
3828 
3829     // C++ [over.ics.rank]p3b4:
3830     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3831     //      which the references refer are the same type except for
3832     //      top-level cv-qualifiers, and the type to which the reference
3833     //      initialized by S2 refers is more cv-qualified than the type
3834     //      to which the reference initialized by S1 refers.
3835     QualType T1 = SCS1.getToType(2);
3836     QualType T2 = SCS2.getToType(2);
3837     T1 = S.Context.getCanonicalType(T1);
3838     T2 = S.Context.getCanonicalType(T2);
3839     Qualifiers T1Quals, T2Quals;
3840     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3841     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3842     if (UnqualT1 == UnqualT2) {
3843       // Objective-C++ ARC: If the references refer to objects with different
3844       // lifetimes, prefer bindings that don't change lifetime.
3845       if (SCS1.ObjCLifetimeConversionBinding !=
3846                                           SCS2.ObjCLifetimeConversionBinding) {
3847         return SCS1.ObjCLifetimeConversionBinding
3848                                            ? ImplicitConversionSequence::Worse
3849                                            : ImplicitConversionSequence::Better;
3850       }
3851 
3852       // If the type is an array type, promote the element qualifiers to the
3853       // type for comparison.
3854       if (isa<ArrayType>(T1) && T1Quals)
3855         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3856       if (isa<ArrayType>(T2) && T2Quals)
3857         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3858       if (T2.isMoreQualifiedThan(T1))
3859         return ImplicitConversionSequence::Better;
3860       else if (T1.isMoreQualifiedThan(T2))
3861         return ImplicitConversionSequence::Worse;
3862     }
3863   }
3864 
3865   // In Microsoft mode, prefer an integral conversion to a
3866   // floating-to-integral conversion if the integral conversion
3867   // is between types of the same size.
3868   // For example:
3869   // void f(float);
3870   // void f(int);
3871   // int main {
3872   //    long a;
3873   //    f(a);
3874   // }
3875   // Here, MSVC will call f(int) instead of generating a compile error
3876   // as clang will do in standard mode.
3877   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3878       SCS2.Second == ICK_Floating_Integral &&
3879       S.Context.getTypeSize(SCS1.getFromType()) ==
3880           S.Context.getTypeSize(SCS1.getToType(2)))
3881     return ImplicitConversionSequence::Better;
3882 
3883   return ImplicitConversionSequence::Indistinguishable;
3884 }
3885 
3886 /// CompareQualificationConversions - Compares two standard conversion
3887 /// sequences to determine whether they can be ranked based on their
3888 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3889 static ImplicitConversionSequence::CompareKind
3890 CompareQualificationConversions(Sema &S,
3891                                 const StandardConversionSequence& SCS1,
3892                                 const StandardConversionSequence& SCS2) {
3893   // C++ 13.3.3.2p3:
3894   //  -- S1 and S2 differ only in their qualification conversion and
3895   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3896   //     cv-qualification signature of type T1 is a proper subset of
3897   //     the cv-qualification signature of type T2, and S1 is not the
3898   //     deprecated string literal array-to-pointer conversion (4.2).
3899   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3900       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3901     return ImplicitConversionSequence::Indistinguishable;
3902 
3903   // FIXME: the example in the standard doesn't use a qualification
3904   // conversion (!)
3905   QualType T1 = SCS1.getToType(2);
3906   QualType T2 = SCS2.getToType(2);
3907   T1 = S.Context.getCanonicalType(T1);
3908   T2 = S.Context.getCanonicalType(T2);
3909   Qualifiers T1Quals, T2Quals;
3910   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3911   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3912 
3913   // If the types are the same, we won't learn anything by unwrapped
3914   // them.
3915   if (UnqualT1 == UnqualT2)
3916     return ImplicitConversionSequence::Indistinguishable;
3917 
3918   // If the type is an array type, promote the element qualifiers to the type
3919   // for comparison.
3920   if (isa<ArrayType>(T1) && T1Quals)
3921     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3922   if (isa<ArrayType>(T2) && T2Quals)
3923     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3924 
3925   ImplicitConversionSequence::CompareKind Result
3926     = ImplicitConversionSequence::Indistinguishable;
3927 
3928   // Objective-C++ ARC:
3929   //   Prefer qualification conversions not involving a change in lifetime
3930   //   to qualification conversions that do not change lifetime.
3931   if (SCS1.QualificationIncludesObjCLifetime !=
3932                                       SCS2.QualificationIncludesObjCLifetime) {
3933     Result = SCS1.QualificationIncludesObjCLifetime
3934                ? ImplicitConversionSequence::Worse
3935                : ImplicitConversionSequence::Better;
3936   }
3937 
3938   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3939     // Within each iteration of the loop, we check the qualifiers to
3940     // determine if this still looks like a qualification
3941     // conversion. Then, if all is well, we unwrap one more level of
3942     // pointers or pointers-to-members and do it all again
3943     // until there are no more pointers or pointers-to-members left
3944     // to unwrap. This essentially mimics what
3945     // IsQualificationConversion does, but here we're checking for a
3946     // strict subset of qualifiers.
3947     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3948       // The qualifiers are the same, so this doesn't tell us anything
3949       // about how the sequences rank.
3950       ;
3951     else if (T2.isMoreQualifiedThan(T1)) {
3952       // T1 has fewer qualifiers, so it could be the better sequence.
3953       if (Result == ImplicitConversionSequence::Worse)
3954         // Neither has qualifiers that are a subset of the other's
3955         // qualifiers.
3956         return ImplicitConversionSequence::Indistinguishable;
3957 
3958       Result = ImplicitConversionSequence::Better;
3959     } else if (T1.isMoreQualifiedThan(T2)) {
3960       // T2 has fewer qualifiers, so it could be the better sequence.
3961       if (Result == ImplicitConversionSequence::Better)
3962         // Neither has qualifiers that are a subset of the other's
3963         // qualifiers.
3964         return ImplicitConversionSequence::Indistinguishable;
3965 
3966       Result = ImplicitConversionSequence::Worse;
3967     } else {
3968       // Qualifiers are disjoint.
3969       return ImplicitConversionSequence::Indistinguishable;
3970     }
3971 
3972     // If the types after this point are equivalent, we're done.
3973     if (S.Context.hasSameUnqualifiedType(T1, T2))
3974       break;
3975   }
3976 
3977   // Check that the winning standard conversion sequence isn't using
3978   // the deprecated string literal array to pointer conversion.
3979   switch (Result) {
3980   case ImplicitConversionSequence::Better:
3981     if (SCS1.DeprecatedStringLiteralToCharPtr)
3982       Result = ImplicitConversionSequence::Indistinguishable;
3983     break;
3984 
3985   case ImplicitConversionSequence::Indistinguishable:
3986     break;
3987 
3988   case ImplicitConversionSequence::Worse:
3989     if (SCS2.DeprecatedStringLiteralToCharPtr)
3990       Result = ImplicitConversionSequence::Indistinguishable;
3991     break;
3992   }
3993 
3994   return Result;
3995 }
3996 
3997 /// CompareDerivedToBaseConversions - Compares two standard conversion
3998 /// sequences to determine whether they can be ranked based on their
3999 /// various kinds of derived-to-base conversions (C++
4000 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4001 /// conversions between Objective-C interface types.
4002 static ImplicitConversionSequence::CompareKind
4003 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4004                                 const StandardConversionSequence& SCS1,
4005                                 const StandardConversionSequence& SCS2) {
4006   QualType FromType1 = SCS1.getFromType();
4007   QualType ToType1 = SCS1.getToType(1);
4008   QualType FromType2 = SCS2.getFromType();
4009   QualType ToType2 = SCS2.getToType(1);
4010 
4011   // Adjust the types we're converting from via the array-to-pointer
4012   // conversion, if we need to.
4013   if (SCS1.First == ICK_Array_To_Pointer)
4014     FromType1 = S.Context.getArrayDecayedType(FromType1);
4015   if (SCS2.First == ICK_Array_To_Pointer)
4016     FromType2 = S.Context.getArrayDecayedType(FromType2);
4017 
4018   // Canonicalize all of the types.
4019   FromType1 = S.Context.getCanonicalType(FromType1);
4020   ToType1 = S.Context.getCanonicalType(ToType1);
4021   FromType2 = S.Context.getCanonicalType(FromType2);
4022   ToType2 = S.Context.getCanonicalType(ToType2);
4023 
4024   // C++ [over.ics.rank]p4b3:
4025   //
4026   //   If class B is derived directly or indirectly from class A and
4027   //   class C is derived directly or indirectly from B,
4028   //
4029   // Compare based on pointer conversions.
4030   if (SCS1.Second == ICK_Pointer_Conversion &&
4031       SCS2.Second == ICK_Pointer_Conversion &&
4032       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4033       FromType1->isPointerType() && FromType2->isPointerType() &&
4034       ToType1->isPointerType() && ToType2->isPointerType()) {
4035     QualType FromPointee1
4036       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4037     QualType ToPointee1
4038       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4039     QualType FromPointee2
4040       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4041     QualType ToPointee2
4042       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4043 
4044     //   -- conversion of C* to B* is better than conversion of C* to A*,
4045     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4046       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4047         return ImplicitConversionSequence::Better;
4048       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4049         return ImplicitConversionSequence::Worse;
4050     }
4051 
4052     //   -- conversion of B* to A* is better than conversion of C* to A*,
4053     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4054       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4055         return ImplicitConversionSequence::Better;
4056       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4057         return ImplicitConversionSequence::Worse;
4058     }
4059   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4060              SCS2.Second == ICK_Pointer_Conversion) {
4061     const ObjCObjectPointerType *FromPtr1
4062       = FromType1->getAs<ObjCObjectPointerType>();
4063     const ObjCObjectPointerType *FromPtr2
4064       = FromType2->getAs<ObjCObjectPointerType>();
4065     const ObjCObjectPointerType *ToPtr1
4066       = ToType1->getAs<ObjCObjectPointerType>();
4067     const ObjCObjectPointerType *ToPtr2
4068       = ToType2->getAs<ObjCObjectPointerType>();
4069 
4070     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4071       // Apply the same conversion ranking rules for Objective-C pointer types
4072       // that we do for C++ pointers to class types. However, we employ the
4073       // Objective-C pseudo-subtyping relationship used for assignment of
4074       // Objective-C pointer types.
4075       bool FromAssignLeft
4076         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4077       bool FromAssignRight
4078         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4079       bool ToAssignLeft
4080         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4081       bool ToAssignRight
4082         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4083 
4084       // A conversion to an a non-id object pointer type or qualified 'id'
4085       // type is better than a conversion to 'id'.
4086       if (ToPtr1->isObjCIdType() &&
4087           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4088         return ImplicitConversionSequence::Worse;
4089       if (ToPtr2->isObjCIdType() &&
4090           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4091         return ImplicitConversionSequence::Better;
4092 
4093       // A conversion to a non-id object pointer type is better than a
4094       // conversion to a qualified 'id' type
4095       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4096         return ImplicitConversionSequence::Worse;
4097       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4098         return ImplicitConversionSequence::Better;
4099 
4100       // A conversion to an a non-Class object pointer type or qualified 'Class'
4101       // type is better than a conversion to 'Class'.
4102       if (ToPtr1->isObjCClassType() &&
4103           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4104         return ImplicitConversionSequence::Worse;
4105       if (ToPtr2->isObjCClassType() &&
4106           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4107         return ImplicitConversionSequence::Better;
4108 
4109       // A conversion to a non-Class object pointer type is better than a
4110       // conversion to a qualified 'Class' type.
4111       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4112         return ImplicitConversionSequence::Worse;
4113       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4114         return ImplicitConversionSequence::Better;
4115 
4116       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4117       if (S.Context.hasSameType(FromType1, FromType2) &&
4118           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4119           (ToAssignLeft != ToAssignRight)) {
4120         if (FromPtr1->isSpecialized()) {
4121           // "conversion of B<A> * to B * is better than conversion of B * to
4122           // C *.
4123           bool IsFirstSame =
4124               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4125           bool IsSecondSame =
4126               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4127           if (IsFirstSame) {
4128             if (!IsSecondSame)
4129               return ImplicitConversionSequence::Better;
4130           } else if (IsSecondSame)
4131             return ImplicitConversionSequence::Worse;
4132         }
4133         return ToAssignLeft? ImplicitConversionSequence::Worse
4134                            : ImplicitConversionSequence::Better;
4135       }
4136 
4137       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4138       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4139           (FromAssignLeft != FromAssignRight))
4140         return FromAssignLeft? ImplicitConversionSequence::Better
4141         : ImplicitConversionSequence::Worse;
4142     }
4143   }
4144 
4145   // Ranking of member-pointer types.
4146   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4147       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4148       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4149     const MemberPointerType * FromMemPointer1 =
4150                                         FromType1->getAs<MemberPointerType>();
4151     const MemberPointerType * ToMemPointer1 =
4152                                           ToType1->getAs<MemberPointerType>();
4153     const MemberPointerType * FromMemPointer2 =
4154                                           FromType2->getAs<MemberPointerType>();
4155     const MemberPointerType * ToMemPointer2 =
4156                                           ToType2->getAs<MemberPointerType>();
4157     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4158     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4159     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4160     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4161     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4162     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4163     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4164     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4165     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4166     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4167       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4168         return ImplicitConversionSequence::Worse;
4169       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4170         return ImplicitConversionSequence::Better;
4171     }
4172     // conversion of B::* to C::* is better than conversion of A::* to C::*
4173     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4174       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4175         return ImplicitConversionSequence::Better;
4176       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4177         return ImplicitConversionSequence::Worse;
4178     }
4179   }
4180 
4181   if (SCS1.Second == ICK_Derived_To_Base) {
4182     //   -- conversion of C to B is better than conversion of C to A,
4183     //   -- binding of an expression of type C to a reference of type
4184     //      B& is better than binding an expression of type C to a
4185     //      reference of type A&,
4186     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4187         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4188       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4189         return ImplicitConversionSequence::Better;
4190       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4191         return ImplicitConversionSequence::Worse;
4192     }
4193 
4194     //   -- conversion of B to A is better than conversion of C to A.
4195     //   -- binding of an expression of type B to a reference of type
4196     //      A& is better than binding an expression of type C to a
4197     //      reference of type A&,
4198     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4199         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4200       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4201         return ImplicitConversionSequence::Better;
4202       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4203         return ImplicitConversionSequence::Worse;
4204     }
4205   }
4206 
4207   return ImplicitConversionSequence::Indistinguishable;
4208 }
4209 
4210 /// Determine whether the given type is valid, e.g., it is not an invalid
4211 /// C++ class.
4212 static bool isTypeValid(QualType T) {
4213   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4214     return !Record->isInvalidDecl();
4215 
4216   return true;
4217 }
4218 
4219 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4220 /// determine whether they are reference-related,
4221 /// reference-compatible, reference-compatible with added
4222 /// qualification, or incompatible, for use in C++ initialization by
4223 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4224 /// type, and the first type (T1) is the pointee type of the reference
4225 /// type being initialized.
4226 Sema::ReferenceCompareResult
4227 Sema::CompareReferenceRelationship(SourceLocation Loc,
4228                                    QualType OrigT1, QualType OrigT2,
4229                                    bool &DerivedToBase,
4230                                    bool &ObjCConversion,
4231                                    bool &ObjCLifetimeConversion) {
4232   assert(!OrigT1->isReferenceType() &&
4233     "T1 must be the pointee type of the reference type");
4234   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4235 
4236   QualType T1 = Context.getCanonicalType(OrigT1);
4237   QualType T2 = Context.getCanonicalType(OrigT2);
4238   Qualifiers T1Quals, T2Quals;
4239   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4240   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4241 
4242   // C++ [dcl.init.ref]p4:
4243   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4244   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4245   //   T1 is a base class of T2.
4246   DerivedToBase = false;
4247   ObjCConversion = false;
4248   ObjCLifetimeConversion = false;
4249   QualType ConvertedT2;
4250   if (UnqualT1 == UnqualT2) {
4251     // Nothing to do.
4252   } else if (isCompleteType(Loc, OrigT2) &&
4253              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4254              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4255     DerivedToBase = true;
4256   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4257            UnqualT2->isObjCObjectOrInterfaceType() &&
4258            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4259     ObjCConversion = true;
4260   else if (UnqualT2->isFunctionType() &&
4261            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4262     // C++1z [dcl.init.ref]p4:
4263     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4264     //   function" and T1 is "function"
4265     //
4266     // We extend this to also apply to 'noreturn', so allow any function
4267     // conversion between function types.
4268     return Ref_Compatible;
4269   else
4270     return Ref_Incompatible;
4271 
4272   // At this point, we know that T1 and T2 are reference-related (at
4273   // least).
4274 
4275   // If the type is an array type, promote the element qualifiers to the type
4276   // for comparison.
4277   if (isa<ArrayType>(T1) && T1Quals)
4278     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4279   if (isa<ArrayType>(T2) && T2Quals)
4280     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4281 
4282   // C++ [dcl.init.ref]p4:
4283   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4284   //   reference-related to T2 and cv1 is the same cv-qualification
4285   //   as, or greater cv-qualification than, cv2. For purposes of
4286   //   overload resolution, cases for which cv1 is greater
4287   //   cv-qualification than cv2 are identified as
4288   //   reference-compatible with added qualification (see 13.3.3.2).
4289   //
4290   // Note that we also require equivalence of Objective-C GC and address-space
4291   // qualifiers when performing these computations, so that e.g., an int in
4292   // address space 1 is not reference-compatible with an int in address
4293   // space 2.
4294   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4295       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4296     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4297       ObjCLifetimeConversion = true;
4298 
4299     T1Quals.removeObjCLifetime();
4300     T2Quals.removeObjCLifetime();
4301   }
4302 
4303   // MS compiler ignores __unaligned qualifier for references; do the same.
4304   T1Quals.removeUnaligned();
4305   T2Quals.removeUnaligned();
4306 
4307   if (T1Quals.compatiblyIncludes(T2Quals))
4308     return Ref_Compatible;
4309   else
4310     return Ref_Related;
4311 }
4312 
4313 /// Look for a user-defined conversion to a value reference-compatible
4314 ///        with DeclType. Return true if something definite is found.
4315 static bool
4316 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4317                          QualType DeclType, SourceLocation DeclLoc,
4318                          Expr *Init, QualType T2, bool AllowRvalues,
4319                          bool AllowExplicit) {
4320   assert(T2->isRecordType() && "Can only find conversions of record types.");
4321   CXXRecordDecl *T2RecordDecl
4322     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4323 
4324   OverloadCandidateSet CandidateSet(
4325       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4326   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4327   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4328     NamedDecl *D = *I;
4329     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4330     if (isa<UsingShadowDecl>(D))
4331       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4332 
4333     FunctionTemplateDecl *ConvTemplate
4334       = dyn_cast<FunctionTemplateDecl>(D);
4335     CXXConversionDecl *Conv;
4336     if (ConvTemplate)
4337       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4338     else
4339       Conv = cast<CXXConversionDecl>(D);
4340 
4341     // If this is an explicit conversion, and we're not allowed to consider
4342     // explicit conversions, skip it.
4343     if (!AllowExplicit && Conv->isExplicit())
4344       continue;
4345 
4346     if (AllowRvalues) {
4347       bool DerivedToBase = false;
4348       bool ObjCConversion = false;
4349       bool ObjCLifetimeConversion = false;
4350 
4351       // If we are initializing an rvalue reference, don't permit conversion
4352       // functions that return lvalues.
4353       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4354         const ReferenceType *RefType
4355           = Conv->getConversionType()->getAs<LValueReferenceType>();
4356         if (RefType && !RefType->getPointeeType()->isFunctionType())
4357           continue;
4358       }
4359 
4360       if (!ConvTemplate &&
4361           S.CompareReferenceRelationship(
4362             DeclLoc,
4363             Conv->getConversionType().getNonReferenceType()
4364               .getUnqualifiedType(),
4365             DeclType.getNonReferenceType().getUnqualifiedType(),
4366             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4367           Sema::Ref_Incompatible)
4368         continue;
4369     } else {
4370       // If the conversion function doesn't return a reference type,
4371       // it can't be considered for this conversion. An rvalue reference
4372       // is only acceptable if its referencee is a function type.
4373 
4374       const ReferenceType *RefType =
4375         Conv->getConversionType()->getAs<ReferenceType>();
4376       if (!RefType ||
4377           (!RefType->isLValueReferenceType() &&
4378            !RefType->getPointeeType()->isFunctionType()))
4379         continue;
4380     }
4381 
4382     if (ConvTemplate)
4383       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4384                                        Init, DeclType, CandidateSet,
4385                                        /*AllowObjCConversionOnExplicit=*/false);
4386     else
4387       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4388                                DeclType, CandidateSet,
4389                                /*AllowObjCConversionOnExplicit=*/false);
4390   }
4391 
4392   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4393 
4394   OverloadCandidateSet::iterator Best;
4395   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4396   case OR_Success:
4397     // C++ [over.ics.ref]p1:
4398     //
4399     //   [...] If the parameter binds directly to the result of
4400     //   applying a conversion function to the argument
4401     //   expression, the implicit conversion sequence is a
4402     //   user-defined conversion sequence (13.3.3.1.2), with the
4403     //   second standard conversion sequence either an identity
4404     //   conversion or, if the conversion function returns an
4405     //   entity of a type that is a derived class of the parameter
4406     //   type, a derived-to-base Conversion.
4407     if (!Best->FinalConversion.DirectBinding)
4408       return false;
4409 
4410     ICS.setUserDefined();
4411     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4412     ICS.UserDefined.After = Best->FinalConversion;
4413     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4414     ICS.UserDefined.ConversionFunction = Best->Function;
4415     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4416     ICS.UserDefined.EllipsisConversion = false;
4417     assert(ICS.UserDefined.After.ReferenceBinding &&
4418            ICS.UserDefined.After.DirectBinding &&
4419            "Expected a direct reference binding!");
4420     return true;
4421 
4422   case OR_Ambiguous:
4423     ICS.setAmbiguous();
4424     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4425          Cand != CandidateSet.end(); ++Cand)
4426       if (Cand->Viable)
4427         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4428     return true;
4429 
4430   case OR_No_Viable_Function:
4431   case OR_Deleted:
4432     // There was no suitable conversion, or we found a deleted
4433     // conversion; continue with other checks.
4434     return false;
4435   }
4436 
4437   llvm_unreachable("Invalid OverloadResult!");
4438 }
4439 
4440 /// Compute an implicit conversion sequence for reference
4441 /// initialization.
4442 static ImplicitConversionSequence
4443 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4444                  SourceLocation DeclLoc,
4445                  bool SuppressUserConversions,
4446                  bool AllowExplicit) {
4447   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4448 
4449   // Most paths end in a failed conversion.
4450   ImplicitConversionSequence ICS;
4451   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4452 
4453   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4454   QualType T2 = Init->getType();
4455 
4456   // If the initializer is the address of an overloaded function, try
4457   // to resolve the overloaded function. If all goes well, T2 is the
4458   // type of the resulting function.
4459   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4460     DeclAccessPair Found;
4461     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4462                                                                 false, Found))
4463       T2 = Fn->getType();
4464   }
4465 
4466   // Compute some basic properties of the types and the initializer.
4467   bool isRValRef = DeclType->isRValueReferenceType();
4468   bool DerivedToBase = false;
4469   bool ObjCConversion = false;
4470   bool ObjCLifetimeConversion = false;
4471   Expr::Classification InitCategory = Init->Classify(S.Context);
4472   Sema::ReferenceCompareResult RefRelationship
4473     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4474                                      ObjCConversion, ObjCLifetimeConversion);
4475 
4476 
4477   // C++0x [dcl.init.ref]p5:
4478   //   A reference to type "cv1 T1" is initialized by an expression
4479   //   of type "cv2 T2" as follows:
4480 
4481   //     -- If reference is an lvalue reference and the initializer expression
4482   if (!isRValRef) {
4483     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4484     //        reference-compatible with "cv2 T2," or
4485     //
4486     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4487     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4488       // C++ [over.ics.ref]p1:
4489       //   When a parameter of reference type binds directly (8.5.3)
4490       //   to an argument expression, the implicit conversion sequence
4491       //   is the identity conversion, unless the argument expression
4492       //   has a type that is a derived class of the parameter type,
4493       //   in which case the implicit conversion sequence is a
4494       //   derived-to-base Conversion (13.3.3.1).
4495       ICS.setStandard();
4496       ICS.Standard.First = ICK_Identity;
4497       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4498                          : ObjCConversion? ICK_Compatible_Conversion
4499                          : ICK_Identity;
4500       ICS.Standard.Third = ICK_Identity;
4501       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4502       ICS.Standard.setToType(0, T2);
4503       ICS.Standard.setToType(1, T1);
4504       ICS.Standard.setToType(2, T1);
4505       ICS.Standard.ReferenceBinding = true;
4506       ICS.Standard.DirectBinding = true;
4507       ICS.Standard.IsLvalueReference = !isRValRef;
4508       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4509       ICS.Standard.BindsToRvalue = false;
4510       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4511       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4512       ICS.Standard.CopyConstructor = nullptr;
4513       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4514 
4515       // Nothing more to do: the inaccessibility/ambiguity check for
4516       // derived-to-base conversions is suppressed when we're
4517       // computing the implicit conversion sequence (C++
4518       // [over.best.ics]p2).
4519       return ICS;
4520     }
4521 
4522     //       -- has a class type (i.e., T2 is a class type), where T1 is
4523     //          not reference-related to T2, and can be implicitly
4524     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4525     //          is reference-compatible with "cv3 T3" 92) (this
4526     //          conversion is selected by enumerating the applicable
4527     //          conversion functions (13.3.1.6) and choosing the best
4528     //          one through overload resolution (13.3)),
4529     if (!SuppressUserConversions && T2->isRecordType() &&
4530         S.isCompleteType(DeclLoc, T2) &&
4531         RefRelationship == Sema::Ref_Incompatible) {
4532       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4533                                    Init, T2, /*AllowRvalues=*/false,
4534                                    AllowExplicit))
4535         return ICS;
4536     }
4537   }
4538 
4539   //     -- Otherwise, the reference shall be an lvalue reference to a
4540   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4541   //        shall be an rvalue reference.
4542   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4543     return ICS;
4544 
4545   //       -- If the initializer expression
4546   //
4547   //            -- is an xvalue, class prvalue, array prvalue or function
4548   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4549   if (RefRelationship == Sema::Ref_Compatible &&
4550       (InitCategory.isXValue() ||
4551        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4552        (InitCategory.isLValue() && T2->isFunctionType()))) {
4553     ICS.setStandard();
4554     ICS.Standard.First = ICK_Identity;
4555     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4556                       : ObjCConversion? ICK_Compatible_Conversion
4557                       : ICK_Identity;
4558     ICS.Standard.Third = ICK_Identity;
4559     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4560     ICS.Standard.setToType(0, T2);
4561     ICS.Standard.setToType(1, T1);
4562     ICS.Standard.setToType(2, T1);
4563     ICS.Standard.ReferenceBinding = true;
4564     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4565     // binding unless we're binding to a class prvalue.
4566     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4567     // allow the use of rvalue references in C++98/03 for the benefit of
4568     // standard library implementors; therefore, we need the xvalue check here.
4569     ICS.Standard.DirectBinding =
4570       S.getLangOpts().CPlusPlus11 ||
4571       !(InitCategory.isPRValue() || T2->isRecordType());
4572     ICS.Standard.IsLvalueReference = !isRValRef;
4573     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4574     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4575     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4576     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4577     ICS.Standard.CopyConstructor = nullptr;
4578     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4579     return ICS;
4580   }
4581 
4582   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4583   //               reference-related to T2, and can be implicitly converted to
4584   //               an xvalue, class prvalue, or function lvalue of type
4585   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4586   //               "cv3 T3",
4587   //
4588   //          then the reference is bound to the value of the initializer
4589   //          expression in the first case and to the result of the conversion
4590   //          in the second case (or, in either case, to an appropriate base
4591   //          class subobject).
4592   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4593       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4594       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4595                                Init, T2, /*AllowRvalues=*/true,
4596                                AllowExplicit)) {
4597     // In the second case, if the reference is an rvalue reference
4598     // and the second standard conversion sequence of the
4599     // user-defined conversion sequence includes an lvalue-to-rvalue
4600     // conversion, the program is ill-formed.
4601     if (ICS.isUserDefined() && isRValRef &&
4602         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4603       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4604 
4605     return ICS;
4606   }
4607 
4608   // A temporary of function type cannot be created; don't even try.
4609   if (T1->isFunctionType())
4610     return ICS;
4611 
4612   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4613   //          initialized from the initializer expression using the
4614   //          rules for a non-reference copy initialization (8.5). The
4615   //          reference is then bound to the temporary. If T1 is
4616   //          reference-related to T2, cv1 must be the same
4617   //          cv-qualification as, or greater cv-qualification than,
4618   //          cv2; otherwise, the program is ill-formed.
4619   if (RefRelationship == Sema::Ref_Related) {
4620     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4621     // we would be reference-compatible or reference-compatible with
4622     // added qualification. But that wasn't the case, so the reference
4623     // initialization fails.
4624     //
4625     // Note that we only want to check address spaces and cvr-qualifiers here.
4626     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4627     Qualifiers T1Quals = T1.getQualifiers();
4628     Qualifiers T2Quals = T2.getQualifiers();
4629     T1Quals.removeObjCGCAttr();
4630     T1Quals.removeObjCLifetime();
4631     T2Quals.removeObjCGCAttr();
4632     T2Quals.removeObjCLifetime();
4633     // MS compiler ignores __unaligned qualifier for references; do the same.
4634     T1Quals.removeUnaligned();
4635     T2Quals.removeUnaligned();
4636     if (!T1Quals.compatiblyIncludes(T2Quals))
4637       return ICS;
4638   }
4639 
4640   // If at least one of the types is a class type, the types are not
4641   // related, and we aren't allowed any user conversions, the
4642   // reference binding fails. This case is important for breaking
4643   // recursion, since TryImplicitConversion below will attempt to
4644   // create a temporary through the use of a copy constructor.
4645   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4646       (T1->isRecordType() || T2->isRecordType()))
4647     return ICS;
4648 
4649   // If T1 is reference-related to T2 and the reference is an rvalue
4650   // reference, the initializer expression shall not be an lvalue.
4651   if (RefRelationship >= Sema::Ref_Related &&
4652       isRValRef && Init->Classify(S.Context).isLValue())
4653     return ICS;
4654 
4655   // C++ [over.ics.ref]p2:
4656   //   When a parameter of reference type is not bound directly to
4657   //   an argument expression, the conversion sequence is the one
4658   //   required to convert the argument expression to the
4659   //   underlying type of the reference according to
4660   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4661   //   to copy-initializing a temporary of the underlying type with
4662   //   the argument expression. Any difference in top-level
4663   //   cv-qualification is subsumed by the initialization itself
4664   //   and does not constitute a conversion.
4665   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4666                               /*AllowExplicit=*/false,
4667                               /*InOverloadResolution=*/false,
4668                               /*CStyle=*/false,
4669                               /*AllowObjCWritebackConversion=*/false,
4670                               /*AllowObjCConversionOnExplicit=*/false);
4671 
4672   // Of course, that's still a reference binding.
4673   if (ICS.isStandard()) {
4674     ICS.Standard.ReferenceBinding = true;
4675     ICS.Standard.IsLvalueReference = !isRValRef;
4676     ICS.Standard.BindsToFunctionLvalue = false;
4677     ICS.Standard.BindsToRvalue = true;
4678     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4679     ICS.Standard.ObjCLifetimeConversionBinding = false;
4680   } else if (ICS.isUserDefined()) {
4681     const ReferenceType *LValRefType =
4682         ICS.UserDefined.ConversionFunction->getReturnType()
4683             ->getAs<LValueReferenceType>();
4684 
4685     // C++ [over.ics.ref]p3:
4686     //   Except for an implicit object parameter, for which see 13.3.1, a
4687     //   standard conversion sequence cannot be formed if it requires [...]
4688     //   binding an rvalue reference to an lvalue other than a function
4689     //   lvalue.
4690     // Note that the function case is not possible here.
4691     if (DeclType->isRValueReferenceType() && LValRefType) {
4692       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4693       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4694       // reference to an rvalue!
4695       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4696       return ICS;
4697     }
4698 
4699     ICS.UserDefined.After.ReferenceBinding = true;
4700     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4701     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4702     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4703     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4704     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4705   }
4706 
4707   return ICS;
4708 }
4709 
4710 static ImplicitConversionSequence
4711 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4712                       bool SuppressUserConversions,
4713                       bool InOverloadResolution,
4714                       bool AllowObjCWritebackConversion,
4715                       bool AllowExplicit = false);
4716 
4717 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4718 /// initializer list From.
4719 static ImplicitConversionSequence
4720 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4721                   bool SuppressUserConversions,
4722                   bool InOverloadResolution,
4723                   bool AllowObjCWritebackConversion) {
4724   // C++11 [over.ics.list]p1:
4725   //   When an argument is an initializer list, it is not an expression and
4726   //   special rules apply for converting it to a parameter type.
4727 
4728   ImplicitConversionSequence Result;
4729   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4730 
4731   // We need a complete type for what follows. Incomplete types can never be
4732   // initialized from init lists.
4733   if (!S.isCompleteType(From->getLocStart(), ToType))
4734     return Result;
4735 
4736   // Per DR1467:
4737   //   If the parameter type is a class X and the initializer list has a single
4738   //   element of type cv U, where U is X or a class derived from X, the
4739   //   implicit conversion sequence is the one required to convert the element
4740   //   to the parameter type.
4741   //
4742   //   Otherwise, if the parameter type is a character array [... ]
4743   //   and the initializer list has a single element that is an
4744   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4745   //   implicit conversion sequence is the identity conversion.
4746   if (From->getNumInits() == 1) {
4747     if (ToType->isRecordType()) {
4748       QualType InitType = From->getInit(0)->getType();
4749       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4750           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4751         return TryCopyInitialization(S, From->getInit(0), ToType,
4752                                      SuppressUserConversions,
4753                                      InOverloadResolution,
4754                                      AllowObjCWritebackConversion);
4755     }
4756     // FIXME: Check the other conditions here: array of character type,
4757     // initializer is a string literal.
4758     if (ToType->isArrayType()) {
4759       InitializedEntity Entity =
4760         InitializedEntity::InitializeParameter(S.Context, ToType,
4761                                                /*Consumed=*/false);
4762       if (S.CanPerformCopyInitialization(Entity, From)) {
4763         Result.setStandard();
4764         Result.Standard.setAsIdentityConversion();
4765         Result.Standard.setFromType(ToType);
4766         Result.Standard.setAllToTypes(ToType);
4767         return Result;
4768       }
4769     }
4770   }
4771 
4772   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4773   // C++11 [over.ics.list]p2:
4774   //   If the parameter type is std::initializer_list<X> or "array of X" and
4775   //   all the elements can be implicitly converted to X, the implicit
4776   //   conversion sequence is the worst conversion necessary to convert an
4777   //   element of the list to X.
4778   //
4779   // C++14 [over.ics.list]p3:
4780   //   Otherwise, if the parameter type is "array of N X", if the initializer
4781   //   list has exactly N elements or if it has fewer than N elements and X is
4782   //   default-constructible, and if all the elements of the initializer list
4783   //   can be implicitly converted to X, the implicit conversion sequence is
4784   //   the worst conversion necessary to convert an element of the list to X.
4785   //
4786   // FIXME: We're missing a lot of these checks.
4787   bool toStdInitializerList = false;
4788   QualType X;
4789   if (ToType->isArrayType())
4790     X = S.Context.getAsArrayType(ToType)->getElementType();
4791   else
4792     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4793   if (!X.isNull()) {
4794     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4795       Expr *Init = From->getInit(i);
4796       ImplicitConversionSequence ICS =
4797           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4798                                 InOverloadResolution,
4799                                 AllowObjCWritebackConversion);
4800       // If a single element isn't convertible, fail.
4801       if (ICS.isBad()) {
4802         Result = ICS;
4803         break;
4804       }
4805       // Otherwise, look for the worst conversion.
4806       if (Result.isBad() ||
4807           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4808                                              Result) ==
4809               ImplicitConversionSequence::Worse)
4810         Result = ICS;
4811     }
4812 
4813     // For an empty list, we won't have computed any conversion sequence.
4814     // Introduce the identity conversion sequence.
4815     if (From->getNumInits() == 0) {
4816       Result.setStandard();
4817       Result.Standard.setAsIdentityConversion();
4818       Result.Standard.setFromType(ToType);
4819       Result.Standard.setAllToTypes(ToType);
4820     }
4821 
4822     Result.setStdInitializerListElement(toStdInitializerList);
4823     return Result;
4824   }
4825 
4826   // C++14 [over.ics.list]p4:
4827   // C++11 [over.ics.list]p3:
4828   //   Otherwise, if the parameter is a non-aggregate class X and overload
4829   //   resolution chooses a single best constructor [...] the implicit
4830   //   conversion sequence is a user-defined conversion sequence. If multiple
4831   //   constructors are viable but none is better than the others, the
4832   //   implicit conversion sequence is a user-defined conversion sequence.
4833   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4834     // This function can deal with initializer lists.
4835     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4836                                     /*AllowExplicit=*/false,
4837                                     InOverloadResolution, /*CStyle=*/false,
4838                                     AllowObjCWritebackConversion,
4839                                     /*AllowObjCConversionOnExplicit=*/false);
4840   }
4841 
4842   // C++14 [over.ics.list]p5:
4843   // C++11 [over.ics.list]p4:
4844   //   Otherwise, if the parameter has an aggregate type which can be
4845   //   initialized from the initializer list [...] the implicit conversion
4846   //   sequence is a user-defined conversion sequence.
4847   if (ToType->isAggregateType()) {
4848     // Type is an aggregate, argument is an init list. At this point it comes
4849     // down to checking whether the initialization works.
4850     // FIXME: Find out whether this parameter is consumed or not.
4851     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4852     // need to call into the initialization code here; overload resolution
4853     // should not be doing that.
4854     InitializedEntity Entity =
4855         InitializedEntity::InitializeParameter(S.Context, ToType,
4856                                                /*Consumed=*/false);
4857     if (S.CanPerformCopyInitialization(Entity, From)) {
4858       Result.setUserDefined();
4859       Result.UserDefined.Before.setAsIdentityConversion();
4860       // Initializer lists don't have a type.
4861       Result.UserDefined.Before.setFromType(QualType());
4862       Result.UserDefined.Before.setAllToTypes(QualType());
4863 
4864       Result.UserDefined.After.setAsIdentityConversion();
4865       Result.UserDefined.After.setFromType(ToType);
4866       Result.UserDefined.After.setAllToTypes(ToType);
4867       Result.UserDefined.ConversionFunction = nullptr;
4868     }
4869     return Result;
4870   }
4871 
4872   // C++14 [over.ics.list]p6:
4873   // C++11 [over.ics.list]p5:
4874   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4875   if (ToType->isReferenceType()) {
4876     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4877     // mention initializer lists in any way. So we go by what list-
4878     // initialization would do and try to extrapolate from that.
4879 
4880     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4881 
4882     // If the initializer list has a single element that is reference-related
4883     // to the parameter type, we initialize the reference from that.
4884     if (From->getNumInits() == 1) {
4885       Expr *Init = From->getInit(0);
4886 
4887       QualType T2 = Init->getType();
4888 
4889       // If the initializer is the address of an overloaded function, try
4890       // to resolve the overloaded function. If all goes well, T2 is the
4891       // type of the resulting function.
4892       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4893         DeclAccessPair Found;
4894         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4895                                    Init, ToType, false, Found))
4896           T2 = Fn->getType();
4897       }
4898 
4899       // Compute some basic properties of the types and the initializer.
4900       bool dummy1 = false;
4901       bool dummy2 = false;
4902       bool dummy3 = false;
4903       Sema::ReferenceCompareResult RefRelationship
4904         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4905                                          dummy2, dummy3);
4906 
4907       if (RefRelationship >= Sema::Ref_Related) {
4908         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4909                                 SuppressUserConversions,
4910                                 /*AllowExplicit=*/false);
4911       }
4912     }
4913 
4914     // Otherwise, we bind the reference to a temporary created from the
4915     // initializer list.
4916     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4917                                InOverloadResolution,
4918                                AllowObjCWritebackConversion);
4919     if (Result.isFailure())
4920       return Result;
4921     assert(!Result.isEllipsis() &&
4922            "Sub-initialization cannot result in ellipsis conversion.");
4923 
4924     // Can we even bind to a temporary?
4925     if (ToType->isRValueReferenceType() ||
4926         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4927       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4928                                             Result.UserDefined.After;
4929       SCS.ReferenceBinding = true;
4930       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4931       SCS.BindsToRvalue = true;
4932       SCS.BindsToFunctionLvalue = false;
4933       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4934       SCS.ObjCLifetimeConversionBinding = false;
4935     } else
4936       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4937                     From, ToType);
4938     return Result;
4939   }
4940 
4941   // C++14 [over.ics.list]p7:
4942   // C++11 [over.ics.list]p6:
4943   //   Otherwise, if the parameter type is not a class:
4944   if (!ToType->isRecordType()) {
4945     //    - if the initializer list has one element that is not itself an
4946     //      initializer list, the implicit conversion sequence is the one
4947     //      required to convert the element to the parameter type.
4948     unsigned NumInits = From->getNumInits();
4949     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4950       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4951                                      SuppressUserConversions,
4952                                      InOverloadResolution,
4953                                      AllowObjCWritebackConversion);
4954     //    - if the initializer list has no elements, the implicit conversion
4955     //      sequence is the identity conversion.
4956     else if (NumInits == 0) {
4957       Result.setStandard();
4958       Result.Standard.setAsIdentityConversion();
4959       Result.Standard.setFromType(ToType);
4960       Result.Standard.setAllToTypes(ToType);
4961     }
4962     return Result;
4963   }
4964 
4965   // C++14 [over.ics.list]p8:
4966   // C++11 [over.ics.list]p7:
4967   //   In all cases other than those enumerated above, no conversion is possible
4968   return Result;
4969 }
4970 
4971 /// TryCopyInitialization - Try to copy-initialize a value of type
4972 /// ToType from the expression From. Return the implicit conversion
4973 /// sequence required to pass this argument, which may be a bad
4974 /// conversion sequence (meaning that the argument cannot be passed to
4975 /// a parameter of this type). If @p SuppressUserConversions, then we
4976 /// do not permit any user-defined conversion sequences.
4977 static ImplicitConversionSequence
4978 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4979                       bool SuppressUserConversions,
4980                       bool InOverloadResolution,
4981                       bool AllowObjCWritebackConversion,
4982                       bool AllowExplicit) {
4983   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4984     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4985                              InOverloadResolution,AllowObjCWritebackConversion);
4986 
4987   if (ToType->isReferenceType())
4988     return TryReferenceInit(S, From, ToType,
4989                             /*FIXME:*/From->getLocStart(),
4990                             SuppressUserConversions,
4991                             AllowExplicit);
4992 
4993   return TryImplicitConversion(S, From, ToType,
4994                                SuppressUserConversions,
4995                                /*AllowExplicit=*/false,
4996                                InOverloadResolution,
4997                                /*CStyle=*/false,
4998                                AllowObjCWritebackConversion,
4999                                /*AllowObjCConversionOnExplicit=*/false);
5000 }
5001 
5002 static bool TryCopyInitialization(const CanQualType FromQTy,
5003                                   const CanQualType ToQTy,
5004                                   Sema &S,
5005                                   SourceLocation Loc,
5006                                   ExprValueKind FromVK) {
5007   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5008   ImplicitConversionSequence ICS =
5009     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5010 
5011   return !ICS.isBad();
5012 }
5013 
5014 /// TryObjectArgumentInitialization - Try to initialize the object
5015 /// parameter of the given member function (@c Method) from the
5016 /// expression @p From.
5017 static ImplicitConversionSequence
5018 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5019                                 Expr::Classification FromClassification,
5020                                 CXXMethodDecl *Method,
5021                                 CXXRecordDecl *ActingContext) {
5022   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5023   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5024   //                 const volatile object.
5025   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5026     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5027   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5028 
5029   // Set up the conversion sequence as a "bad" conversion, to allow us
5030   // to exit early.
5031   ImplicitConversionSequence ICS;
5032 
5033   // We need to have an object of class type.
5034   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5035     FromType = PT->getPointeeType();
5036 
5037     // When we had a pointer, it's implicitly dereferenced, so we
5038     // better have an lvalue.
5039     assert(FromClassification.isLValue());
5040   }
5041 
5042   assert(FromType->isRecordType());
5043 
5044   // C++0x [over.match.funcs]p4:
5045   //   For non-static member functions, the type of the implicit object
5046   //   parameter is
5047   //
5048   //     - "lvalue reference to cv X" for functions declared without a
5049   //        ref-qualifier or with the & ref-qualifier
5050   //     - "rvalue reference to cv X" for functions declared with the &&
5051   //        ref-qualifier
5052   //
5053   // where X is the class of which the function is a member and cv is the
5054   // cv-qualification on the member function declaration.
5055   //
5056   // However, when finding an implicit conversion sequence for the argument, we
5057   // are not allowed to perform user-defined conversions
5058   // (C++ [over.match.funcs]p5). We perform a simplified version of
5059   // reference binding here, that allows class rvalues to bind to
5060   // non-constant references.
5061 
5062   // First check the qualifiers.
5063   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5064   if (ImplicitParamType.getCVRQualifiers()
5065                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5066       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5067     ICS.setBad(BadConversionSequence::bad_qualifiers,
5068                FromType, ImplicitParamType);
5069     return ICS;
5070   }
5071 
5072   // Check that we have either the same type or a derived type. It
5073   // affects the conversion rank.
5074   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5075   ImplicitConversionKind SecondKind;
5076   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5077     SecondKind = ICK_Identity;
5078   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5079     SecondKind = ICK_Derived_To_Base;
5080   else {
5081     ICS.setBad(BadConversionSequence::unrelated_class,
5082                FromType, ImplicitParamType);
5083     return ICS;
5084   }
5085 
5086   // Check the ref-qualifier.
5087   switch (Method->getRefQualifier()) {
5088   case RQ_None:
5089     // Do nothing; we don't care about lvalueness or rvalueness.
5090     break;
5091 
5092   case RQ_LValue:
5093     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5094       // non-const lvalue reference cannot bind to an rvalue
5095       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5096                  ImplicitParamType);
5097       return ICS;
5098     }
5099     break;
5100 
5101   case RQ_RValue:
5102     if (!FromClassification.isRValue()) {
5103       // rvalue reference cannot bind to an lvalue
5104       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5105                  ImplicitParamType);
5106       return ICS;
5107     }
5108     break;
5109   }
5110 
5111   // Success. Mark this as a reference binding.
5112   ICS.setStandard();
5113   ICS.Standard.setAsIdentityConversion();
5114   ICS.Standard.Second = SecondKind;
5115   ICS.Standard.setFromType(FromType);
5116   ICS.Standard.setAllToTypes(ImplicitParamType);
5117   ICS.Standard.ReferenceBinding = true;
5118   ICS.Standard.DirectBinding = true;
5119   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5120   ICS.Standard.BindsToFunctionLvalue = false;
5121   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5122   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5123     = (Method->getRefQualifier() == RQ_None);
5124   return ICS;
5125 }
5126 
5127 /// PerformObjectArgumentInitialization - Perform initialization of
5128 /// the implicit object parameter for the given Method with the given
5129 /// expression.
5130 ExprResult
5131 Sema::PerformObjectArgumentInitialization(Expr *From,
5132                                           NestedNameSpecifier *Qualifier,
5133                                           NamedDecl *FoundDecl,
5134                                           CXXMethodDecl *Method) {
5135   QualType FromRecordType, DestType;
5136   QualType ImplicitParamRecordType  =
5137     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5138 
5139   Expr::Classification FromClassification;
5140   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5141     FromRecordType = PT->getPointeeType();
5142     DestType = Method->getThisType(Context);
5143     FromClassification = Expr::Classification::makeSimpleLValue();
5144   } else {
5145     FromRecordType = From->getType();
5146     DestType = ImplicitParamRecordType;
5147     FromClassification = From->Classify(Context);
5148   }
5149 
5150   // Note that we always use the true parent context when performing
5151   // the actual argument initialization.
5152   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5153       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5154       Method->getParent());
5155   if (ICS.isBad()) {
5156     switch (ICS.Bad.Kind) {
5157     case BadConversionSequence::bad_qualifiers: {
5158       Qualifiers FromQs = FromRecordType.getQualifiers();
5159       Qualifiers ToQs = DestType.getQualifiers();
5160       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5161       if (CVR) {
5162         Diag(From->getLocStart(),
5163              diag::err_member_function_call_bad_cvr)
5164           << Method->getDeclName() << FromRecordType << (CVR - 1)
5165           << From->getSourceRange();
5166         Diag(Method->getLocation(), diag::note_previous_decl)
5167           << Method->getDeclName();
5168         return ExprError();
5169       }
5170       break;
5171     }
5172 
5173     case BadConversionSequence::lvalue_ref_to_rvalue:
5174     case BadConversionSequence::rvalue_ref_to_lvalue: {
5175       bool IsRValueQualified =
5176         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5177       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5178         << Method->getDeclName() << FromClassification.isRValue()
5179         << IsRValueQualified;
5180       Diag(Method->getLocation(), diag::note_previous_decl)
5181         << Method->getDeclName();
5182       return ExprError();
5183     }
5184 
5185     case BadConversionSequence::no_conversion:
5186     case BadConversionSequence::unrelated_class:
5187       break;
5188     }
5189 
5190     return Diag(From->getLocStart(),
5191                 diag::err_member_function_call_bad_type)
5192        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5193   }
5194 
5195   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5196     ExprResult FromRes =
5197       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5198     if (FromRes.isInvalid())
5199       return ExprError();
5200     From = FromRes.get();
5201   }
5202 
5203   if (!Context.hasSameType(From->getType(), DestType))
5204     From = ImpCastExprToType(From, DestType, CK_NoOp,
5205                              From->getValueKind()).get();
5206   return From;
5207 }
5208 
5209 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5210 /// expression From to bool (C++0x [conv]p3).
5211 static ImplicitConversionSequence
5212 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5213   return TryImplicitConversion(S, From, S.Context.BoolTy,
5214                                /*SuppressUserConversions=*/false,
5215                                /*AllowExplicit=*/true,
5216                                /*InOverloadResolution=*/false,
5217                                /*CStyle=*/false,
5218                                /*AllowObjCWritebackConversion=*/false,
5219                                /*AllowObjCConversionOnExplicit=*/false);
5220 }
5221 
5222 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5223 /// of the expression From to bool (C++0x [conv]p3).
5224 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5225   if (checkPlaceholderForOverload(*this, From))
5226     return ExprError();
5227 
5228   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5229   if (!ICS.isBad())
5230     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5231 
5232   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5233     return Diag(From->getLocStart(),
5234                 diag::err_typecheck_bool_condition)
5235                   << From->getType() << From->getSourceRange();
5236   return ExprError();
5237 }
5238 
5239 /// Check that the specified conversion is permitted in a converted constant
5240 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5241 /// is acceptable.
5242 static bool CheckConvertedConstantConversions(Sema &S,
5243                                               StandardConversionSequence &SCS) {
5244   // Since we know that the target type is an integral or unscoped enumeration
5245   // type, most conversion kinds are impossible. All possible First and Third
5246   // conversions are fine.
5247   switch (SCS.Second) {
5248   case ICK_Identity:
5249   case ICK_Function_Conversion:
5250   case ICK_Integral_Promotion:
5251   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5252   case ICK_Zero_Queue_Conversion:
5253     return true;
5254 
5255   case ICK_Boolean_Conversion:
5256     // Conversion from an integral or unscoped enumeration type to bool is
5257     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5258     // conversion, so we allow it in a converted constant expression.
5259     //
5260     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5261     // a lot of popular code. We should at least add a warning for this
5262     // (non-conforming) extension.
5263     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5264            SCS.getToType(2)->isBooleanType();
5265 
5266   case ICK_Pointer_Conversion:
5267   case ICK_Pointer_Member:
5268     // C++1z: null pointer conversions and null member pointer conversions are
5269     // only permitted if the source type is std::nullptr_t.
5270     return SCS.getFromType()->isNullPtrType();
5271 
5272   case ICK_Floating_Promotion:
5273   case ICK_Complex_Promotion:
5274   case ICK_Floating_Conversion:
5275   case ICK_Complex_Conversion:
5276   case ICK_Floating_Integral:
5277   case ICK_Compatible_Conversion:
5278   case ICK_Derived_To_Base:
5279   case ICK_Vector_Conversion:
5280   case ICK_Vector_Splat:
5281   case ICK_Complex_Real:
5282   case ICK_Block_Pointer_Conversion:
5283   case ICK_TransparentUnionConversion:
5284   case ICK_Writeback_Conversion:
5285   case ICK_Zero_Event_Conversion:
5286   case ICK_C_Only_Conversion:
5287   case ICK_Incompatible_Pointer_Conversion:
5288     return false;
5289 
5290   case ICK_Lvalue_To_Rvalue:
5291   case ICK_Array_To_Pointer:
5292   case ICK_Function_To_Pointer:
5293     llvm_unreachable("found a first conversion kind in Second");
5294 
5295   case ICK_Qualification:
5296     llvm_unreachable("found a third conversion kind in Second");
5297 
5298   case ICK_Num_Conversion_Kinds:
5299     break;
5300   }
5301 
5302   llvm_unreachable("unknown conversion kind");
5303 }
5304 
5305 /// CheckConvertedConstantExpression - Check that the expression From is a
5306 /// converted constant expression of type T, perform the conversion and produce
5307 /// the converted expression, per C++11 [expr.const]p3.
5308 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5309                                                    QualType T, APValue &Value,
5310                                                    Sema::CCEKind CCE,
5311                                                    bool RequireInt) {
5312   assert(S.getLangOpts().CPlusPlus11 &&
5313          "converted constant expression outside C++11");
5314 
5315   if (checkPlaceholderForOverload(S, From))
5316     return ExprError();
5317 
5318   // C++1z [expr.const]p3:
5319   //  A converted constant expression of type T is an expression,
5320   //  implicitly converted to type T, where the converted
5321   //  expression is a constant expression and the implicit conversion
5322   //  sequence contains only [... list of conversions ...].
5323   // C++1z [stmt.if]p2:
5324   //  If the if statement is of the form if constexpr, the value of the
5325   //  condition shall be a contextually converted constant expression of type
5326   //  bool.
5327   ImplicitConversionSequence ICS =
5328       CCE == Sema::CCEK_ConstexprIf
5329           ? TryContextuallyConvertToBool(S, From)
5330           : TryCopyInitialization(S, From, T,
5331                                   /*SuppressUserConversions=*/false,
5332                                   /*InOverloadResolution=*/false,
5333                                   /*AllowObjcWritebackConversion=*/false,
5334                                   /*AllowExplicit=*/false);
5335   StandardConversionSequence *SCS = nullptr;
5336   switch (ICS.getKind()) {
5337   case ImplicitConversionSequence::StandardConversion:
5338     SCS = &ICS.Standard;
5339     break;
5340   case ImplicitConversionSequence::UserDefinedConversion:
5341     // We are converting to a non-class type, so the Before sequence
5342     // must be trivial.
5343     SCS = &ICS.UserDefined.After;
5344     break;
5345   case ImplicitConversionSequence::AmbiguousConversion:
5346   case ImplicitConversionSequence::BadConversion:
5347     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5348       return S.Diag(From->getLocStart(),
5349                     diag::err_typecheck_converted_constant_expression)
5350                 << From->getType() << From->getSourceRange() << T;
5351     return ExprError();
5352 
5353   case ImplicitConversionSequence::EllipsisConversion:
5354     llvm_unreachable("ellipsis conversion in converted constant expression");
5355   }
5356 
5357   // Check that we would only use permitted conversions.
5358   if (!CheckConvertedConstantConversions(S, *SCS)) {
5359     return S.Diag(From->getLocStart(),
5360                   diag::err_typecheck_converted_constant_expression_disallowed)
5361              << From->getType() << From->getSourceRange() << T;
5362   }
5363   // [...] and where the reference binding (if any) binds directly.
5364   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5365     return S.Diag(From->getLocStart(),
5366                   diag::err_typecheck_converted_constant_expression_indirect)
5367              << From->getType() << From->getSourceRange() << T;
5368   }
5369 
5370   ExprResult Result =
5371       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5372   if (Result.isInvalid())
5373     return Result;
5374 
5375   // Check for a narrowing implicit conversion.
5376   APValue PreNarrowingValue;
5377   QualType PreNarrowingType;
5378   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5379                                 PreNarrowingType)) {
5380   case NK_Dependent_Narrowing:
5381     // Implicit conversion to a narrower type, but the expression is
5382     // value-dependent so we can't tell whether it's actually narrowing.
5383   case NK_Variable_Narrowing:
5384     // Implicit conversion to a narrower type, and the value is not a constant
5385     // expression. We'll diagnose this in a moment.
5386   case NK_Not_Narrowing:
5387     break;
5388 
5389   case NK_Constant_Narrowing:
5390     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5391       << CCE << /*Constant*/1
5392       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5393     break;
5394 
5395   case NK_Type_Narrowing:
5396     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5397       << CCE << /*Constant*/0 << From->getType() << T;
5398     break;
5399   }
5400 
5401   if (Result.get()->isValueDependent()) {
5402     Value = APValue();
5403     return Result;
5404   }
5405 
5406   // Check the expression is a constant expression.
5407   SmallVector<PartialDiagnosticAt, 8> Notes;
5408   Expr::EvalResult Eval;
5409   Eval.Diag = &Notes;
5410 
5411   if ((T->isReferenceType()
5412            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5413            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5414       (RequireInt && !Eval.Val.isInt())) {
5415     // The expression can't be folded, so we can't keep it at this position in
5416     // the AST.
5417     Result = ExprError();
5418   } else {
5419     Value = Eval.Val;
5420 
5421     if (Notes.empty()) {
5422       // It's a constant expression.
5423       return Result;
5424     }
5425   }
5426 
5427   // It's not a constant expression. Produce an appropriate diagnostic.
5428   if (Notes.size() == 1 &&
5429       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5430     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5431   else {
5432     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5433       << CCE << From->getSourceRange();
5434     for (unsigned I = 0; I < Notes.size(); ++I)
5435       S.Diag(Notes[I].first, Notes[I].second);
5436   }
5437   return ExprError();
5438 }
5439 
5440 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5441                                                   APValue &Value, CCEKind CCE) {
5442   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5443 }
5444 
5445 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5446                                                   llvm::APSInt &Value,
5447                                                   CCEKind CCE) {
5448   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5449 
5450   APValue V;
5451   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5452   if (!R.isInvalid() && !R.get()->isValueDependent())
5453     Value = V.getInt();
5454   return R;
5455 }
5456 
5457 
5458 /// dropPointerConversions - If the given standard conversion sequence
5459 /// involves any pointer conversions, remove them.  This may change
5460 /// the result type of the conversion sequence.
5461 static void dropPointerConversion(StandardConversionSequence &SCS) {
5462   if (SCS.Second == ICK_Pointer_Conversion) {
5463     SCS.Second = ICK_Identity;
5464     SCS.Third = ICK_Identity;
5465     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5466   }
5467 }
5468 
5469 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5470 /// convert the expression From to an Objective-C pointer type.
5471 static ImplicitConversionSequence
5472 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5473   // Do an implicit conversion to 'id'.
5474   QualType Ty = S.Context.getObjCIdType();
5475   ImplicitConversionSequence ICS
5476     = TryImplicitConversion(S, From, Ty,
5477                             // FIXME: Are these flags correct?
5478                             /*SuppressUserConversions=*/false,
5479                             /*AllowExplicit=*/true,
5480                             /*InOverloadResolution=*/false,
5481                             /*CStyle=*/false,
5482                             /*AllowObjCWritebackConversion=*/false,
5483                             /*AllowObjCConversionOnExplicit=*/true);
5484 
5485   // Strip off any final conversions to 'id'.
5486   switch (ICS.getKind()) {
5487   case ImplicitConversionSequence::BadConversion:
5488   case ImplicitConversionSequence::AmbiguousConversion:
5489   case ImplicitConversionSequence::EllipsisConversion:
5490     break;
5491 
5492   case ImplicitConversionSequence::UserDefinedConversion:
5493     dropPointerConversion(ICS.UserDefined.After);
5494     break;
5495 
5496   case ImplicitConversionSequence::StandardConversion:
5497     dropPointerConversion(ICS.Standard);
5498     break;
5499   }
5500 
5501   return ICS;
5502 }
5503 
5504 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5505 /// conversion of the expression From to an Objective-C pointer type.
5506 /// Returns a valid but null ExprResult if no conversion sequence exists.
5507 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5508   if (checkPlaceholderForOverload(*this, From))
5509     return ExprError();
5510 
5511   QualType Ty = Context.getObjCIdType();
5512   ImplicitConversionSequence ICS =
5513     TryContextuallyConvertToObjCPointer(*this, From);
5514   if (!ICS.isBad())
5515     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5516   return ExprResult();
5517 }
5518 
5519 /// Determine whether the provided type is an integral type, or an enumeration
5520 /// type of a permitted flavor.
5521 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5522   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5523                                  : T->isIntegralOrUnscopedEnumerationType();
5524 }
5525 
5526 static ExprResult
5527 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5528                             Sema::ContextualImplicitConverter &Converter,
5529                             QualType T, UnresolvedSetImpl &ViableConversions) {
5530 
5531   if (Converter.Suppress)
5532     return ExprError();
5533 
5534   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5535   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5536     CXXConversionDecl *Conv =
5537         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5538     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5539     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5540   }
5541   return From;
5542 }
5543 
5544 static bool
5545 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5546                            Sema::ContextualImplicitConverter &Converter,
5547                            QualType T, bool HadMultipleCandidates,
5548                            UnresolvedSetImpl &ExplicitConversions) {
5549   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5550     DeclAccessPair Found = ExplicitConversions[0];
5551     CXXConversionDecl *Conversion =
5552         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5553 
5554     // The user probably meant to invoke the given explicit
5555     // conversion; use it.
5556     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5557     std::string TypeStr;
5558     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5559 
5560     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5561         << FixItHint::CreateInsertion(From->getLocStart(),
5562                                       "static_cast<" + TypeStr + ">(")
5563         << FixItHint::CreateInsertion(
5564                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5565     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5566 
5567     // If we aren't in a SFINAE context, build a call to the
5568     // explicit conversion function.
5569     if (SemaRef.isSFINAEContext())
5570       return true;
5571 
5572     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5573     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5574                                                        HadMultipleCandidates);
5575     if (Result.isInvalid())
5576       return true;
5577     // Record usage of conversion in an implicit cast.
5578     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5579                                     CK_UserDefinedConversion, Result.get(),
5580                                     nullptr, Result.get()->getValueKind());
5581   }
5582   return false;
5583 }
5584 
5585 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5586                              Sema::ContextualImplicitConverter &Converter,
5587                              QualType T, bool HadMultipleCandidates,
5588                              DeclAccessPair &Found) {
5589   CXXConversionDecl *Conversion =
5590       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5591   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5592 
5593   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5594   if (!Converter.SuppressConversion) {
5595     if (SemaRef.isSFINAEContext())
5596       return true;
5597 
5598     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5599         << From->getSourceRange();
5600   }
5601 
5602   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5603                                                      HadMultipleCandidates);
5604   if (Result.isInvalid())
5605     return true;
5606   // Record usage of conversion in an implicit cast.
5607   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5608                                   CK_UserDefinedConversion, Result.get(),
5609                                   nullptr, Result.get()->getValueKind());
5610   return false;
5611 }
5612 
5613 static ExprResult finishContextualImplicitConversion(
5614     Sema &SemaRef, SourceLocation Loc, Expr *From,
5615     Sema::ContextualImplicitConverter &Converter) {
5616   if (!Converter.match(From->getType()) && !Converter.Suppress)
5617     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5618         << From->getSourceRange();
5619 
5620   return SemaRef.DefaultLvalueConversion(From);
5621 }
5622 
5623 static void
5624 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5625                                   UnresolvedSetImpl &ViableConversions,
5626                                   OverloadCandidateSet &CandidateSet) {
5627   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5628     DeclAccessPair FoundDecl = ViableConversions[I];
5629     NamedDecl *D = FoundDecl.getDecl();
5630     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5631     if (isa<UsingShadowDecl>(D))
5632       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5633 
5634     CXXConversionDecl *Conv;
5635     FunctionTemplateDecl *ConvTemplate;
5636     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5637       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5638     else
5639       Conv = cast<CXXConversionDecl>(D);
5640 
5641     if (ConvTemplate)
5642       SemaRef.AddTemplateConversionCandidate(
5643         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5644         /*AllowObjCConversionOnExplicit=*/false);
5645     else
5646       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5647                                      ToType, CandidateSet,
5648                                      /*AllowObjCConversionOnExplicit=*/false);
5649   }
5650 }
5651 
5652 /// Attempt to convert the given expression to a type which is accepted
5653 /// by the given converter.
5654 ///
5655 /// This routine will attempt to convert an expression of class type to a
5656 /// type accepted by the specified converter. In C++11 and before, the class
5657 /// must have a single non-explicit conversion function converting to a matching
5658 /// type. In C++1y, there can be multiple such conversion functions, but only
5659 /// one target type.
5660 ///
5661 /// \param Loc The source location of the construct that requires the
5662 /// conversion.
5663 ///
5664 /// \param From The expression we're converting from.
5665 ///
5666 /// \param Converter Used to control and diagnose the conversion process.
5667 ///
5668 /// \returns The expression, converted to an integral or enumeration type if
5669 /// successful.
5670 ExprResult Sema::PerformContextualImplicitConversion(
5671     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5672   // We can't perform any more checking for type-dependent expressions.
5673   if (From->isTypeDependent())
5674     return From;
5675 
5676   // Process placeholders immediately.
5677   if (From->hasPlaceholderType()) {
5678     ExprResult result = CheckPlaceholderExpr(From);
5679     if (result.isInvalid())
5680       return result;
5681     From = result.get();
5682   }
5683 
5684   // If the expression already has a matching type, we're golden.
5685   QualType T = From->getType();
5686   if (Converter.match(T))
5687     return DefaultLvalueConversion(From);
5688 
5689   // FIXME: Check for missing '()' if T is a function type?
5690 
5691   // We can only perform contextual implicit conversions on objects of class
5692   // type.
5693   const RecordType *RecordTy = T->getAs<RecordType>();
5694   if (!RecordTy || !getLangOpts().CPlusPlus) {
5695     if (!Converter.Suppress)
5696       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5697     return From;
5698   }
5699 
5700   // We must have a complete class type.
5701   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5702     ContextualImplicitConverter &Converter;
5703     Expr *From;
5704 
5705     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5706         : Converter(Converter), From(From) {}
5707 
5708     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5709       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5710     }
5711   } IncompleteDiagnoser(Converter, From);
5712 
5713   if (Converter.Suppress ? !isCompleteType(Loc, T)
5714                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5715     return From;
5716 
5717   // Look for a conversion to an integral or enumeration type.
5718   UnresolvedSet<4>
5719       ViableConversions; // These are *potentially* viable in C++1y.
5720   UnresolvedSet<4> ExplicitConversions;
5721   const auto &Conversions =
5722       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5723 
5724   bool HadMultipleCandidates =
5725       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5726 
5727   // To check that there is only one target type, in C++1y:
5728   QualType ToType;
5729   bool HasUniqueTargetType = true;
5730 
5731   // Collect explicit or viable (potentially in C++1y) conversions.
5732   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5733     NamedDecl *D = (*I)->getUnderlyingDecl();
5734     CXXConversionDecl *Conversion;
5735     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5736     if (ConvTemplate) {
5737       if (getLangOpts().CPlusPlus14)
5738         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5739       else
5740         continue; // C++11 does not consider conversion operator templates(?).
5741     } else
5742       Conversion = cast<CXXConversionDecl>(D);
5743 
5744     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5745            "Conversion operator templates are considered potentially "
5746            "viable in C++1y");
5747 
5748     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5749     if (Converter.match(CurToType) || ConvTemplate) {
5750 
5751       if (Conversion->isExplicit()) {
5752         // FIXME: For C++1y, do we need this restriction?
5753         // cf. diagnoseNoViableConversion()
5754         if (!ConvTemplate)
5755           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5756       } else {
5757         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5758           if (ToType.isNull())
5759             ToType = CurToType.getUnqualifiedType();
5760           else if (HasUniqueTargetType &&
5761                    (CurToType.getUnqualifiedType() != ToType))
5762             HasUniqueTargetType = false;
5763         }
5764         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5765       }
5766     }
5767   }
5768 
5769   if (getLangOpts().CPlusPlus14) {
5770     // C++1y [conv]p6:
5771     // ... An expression e of class type E appearing in such a context
5772     // is said to be contextually implicitly converted to a specified
5773     // type T and is well-formed if and only if e can be implicitly
5774     // converted to a type T that is determined as follows: E is searched
5775     // for conversion functions whose return type is cv T or reference to
5776     // cv T such that T is allowed by the context. There shall be
5777     // exactly one such T.
5778 
5779     // If no unique T is found:
5780     if (ToType.isNull()) {
5781       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5782                                      HadMultipleCandidates,
5783                                      ExplicitConversions))
5784         return ExprError();
5785       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5786     }
5787 
5788     // If more than one unique Ts are found:
5789     if (!HasUniqueTargetType)
5790       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5791                                          ViableConversions);
5792 
5793     // If one unique T is found:
5794     // First, build a candidate set from the previously recorded
5795     // potentially viable conversions.
5796     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5797     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5798                                       CandidateSet);
5799 
5800     // Then, perform overload resolution over the candidate set.
5801     OverloadCandidateSet::iterator Best;
5802     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5803     case OR_Success: {
5804       // Apply this conversion.
5805       DeclAccessPair Found =
5806           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5807       if (recordConversion(*this, Loc, From, Converter, T,
5808                            HadMultipleCandidates, Found))
5809         return ExprError();
5810       break;
5811     }
5812     case OR_Ambiguous:
5813       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5814                                          ViableConversions);
5815     case OR_No_Viable_Function:
5816       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5817                                      HadMultipleCandidates,
5818                                      ExplicitConversions))
5819         return ExprError();
5820       LLVM_FALLTHROUGH;
5821     case OR_Deleted:
5822       // We'll complain below about a non-integral condition type.
5823       break;
5824     }
5825   } else {
5826     switch (ViableConversions.size()) {
5827     case 0: {
5828       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5829                                      HadMultipleCandidates,
5830                                      ExplicitConversions))
5831         return ExprError();
5832 
5833       // We'll complain below about a non-integral condition type.
5834       break;
5835     }
5836     case 1: {
5837       // Apply this conversion.
5838       DeclAccessPair Found = ViableConversions[0];
5839       if (recordConversion(*this, Loc, From, Converter, T,
5840                            HadMultipleCandidates, Found))
5841         return ExprError();
5842       break;
5843     }
5844     default:
5845       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5846                                          ViableConversions);
5847     }
5848   }
5849 
5850   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5851 }
5852 
5853 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5854 /// an acceptable non-member overloaded operator for a call whose
5855 /// arguments have types T1 (and, if non-empty, T2). This routine
5856 /// implements the check in C++ [over.match.oper]p3b2 concerning
5857 /// enumeration types.
5858 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5859                                                    FunctionDecl *Fn,
5860                                                    ArrayRef<Expr *> Args) {
5861   QualType T1 = Args[0]->getType();
5862   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5863 
5864   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5865     return true;
5866 
5867   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5868     return true;
5869 
5870   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5871   if (Proto->getNumParams() < 1)
5872     return false;
5873 
5874   if (T1->isEnumeralType()) {
5875     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5876     if (Context.hasSameUnqualifiedType(T1, ArgType))
5877       return true;
5878   }
5879 
5880   if (Proto->getNumParams() < 2)
5881     return false;
5882 
5883   if (!T2.isNull() && T2->isEnumeralType()) {
5884     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5885     if (Context.hasSameUnqualifiedType(T2, ArgType))
5886       return true;
5887   }
5888 
5889   return false;
5890 }
5891 
5892 /// AddOverloadCandidate - Adds the given function to the set of
5893 /// candidate functions, using the given function call arguments.  If
5894 /// @p SuppressUserConversions, then don't allow user-defined
5895 /// conversions via constructors or conversion operators.
5896 ///
5897 /// \param PartialOverloading true if we are performing "partial" overloading
5898 /// based on an incomplete set of function arguments. This feature is used by
5899 /// code completion.
5900 void
5901 Sema::AddOverloadCandidate(FunctionDecl *Function,
5902                            DeclAccessPair FoundDecl,
5903                            ArrayRef<Expr *> Args,
5904                            OverloadCandidateSet &CandidateSet,
5905                            bool SuppressUserConversions,
5906                            bool PartialOverloading,
5907                            bool AllowExplicit,
5908                            ConversionSequenceList EarlyConversions) {
5909   const FunctionProtoType *Proto
5910     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5911   assert(Proto && "Functions without a prototype cannot be overloaded");
5912   assert(!Function->getDescribedFunctionTemplate() &&
5913          "Use AddTemplateOverloadCandidate for function templates");
5914 
5915   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5916     if (!isa<CXXConstructorDecl>(Method)) {
5917       // If we get here, it's because we're calling a member function
5918       // that is named without a member access expression (e.g.,
5919       // "this->f") that was either written explicitly or created
5920       // implicitly. This can happen with a qualified call to a member
5921       // function, e.g., X::f(). We use an empty type for the implied
5922       // object argument (C++ [over.call.func]p3), and the acting context
5923       // is irrelevant.
5924       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5925                          Expr::Classification::makeSimpleLValue(), Args,
5926                          CandidateSet, SuppressUserConversions,
5927                          PartialOverloading, EarlyConversions);
5928       return;
5929     }
5930     // We treat a constructor like a non-member function, since its object
5931     // argument doesn't participate in overload resolution.
5932   }
5933 
5934   if (!CandidateSet.isNewCandidate(Function))
5935     return;
5936 
5937   // C++ [over.match.oper]p3:
5938   //   if no operand has a class type, only those non-member functions in the
5939   //   lookup set that have a first parameter of type T1 or "reference to
5940   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5941   //   is a right operand) a second parameter of type T2 or "reference to
5942   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5943   //   candidate functions.
5944   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5945       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5946     return;
5947 
5948   // C++11 [class.copy]p11: [DR1402]
5949   //   A defaulted move constructor that is defined as deleted is ignored by
5950   //   overload resolution.
5951   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5952   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5953       Constructor->isMoveConstructor())
5954     return;
5955 
5956   // Overload resolution is always an unevaluated context.
5957   EnterExpressionEvaluationContext Unevaluated(
5958       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5959 
5960   // Add this candidate
5961   OverloadCandidate &Candidate =
5962       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5963   Candidate.FoundDecl = FoundDecl;
5964   Candidate.Function = Function;
5965   Candidate.Viable = true;
5966   Candidate.IsSurrogate = false;
5967   Candidate.IgnoreObjectArgument = false;
5968   Candidate.ExplicitCallArguments = Args.size();
5969 
5970   if (Function->isMultiVersion() &&
5971       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5972     Candidate.Viable = false;
5973     Candidate.FailureKind = ovl_non_default_multiversion_function;
5974     return;
5975   }
5976 
5977   if (Constructor) {
5978     // C++ [class.copy]p3:
5979     //   A member function template is never instantiated to perform the copy
5980     //   of a class object to an object of its class type.
5981     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5982     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5983         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5984          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5985                        ClassType))) {
5986       Candidate.Viable = false;
5987       Candidate.FailureKind = ovl_fail_illegal_constructor;
5988       return;
5989     }
5990 
5991     // C++ [over.match.funcs]p8: (proposed DR resolution)
5992     //   A constructor inherited from class type C that has a first parameter
5993     //   of type "reference to P" (including such a constructor instantiated
5994     //   from a template) is excluded from the set of candidate functions when
5995     //   constructing an object of type cv D if the argument list has exactly
5996     //   one argument and D is reference-related to P and P is reference-related
5997     //   to C.
5998     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5999     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6000         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6001       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6002       QualType C = Context.getRecordType(Constructor->getParent());
6003       QualType D = Context.getRecordType(Shadow->getParent());
6004       SourceLocation Loc = Args.front()->getExprLoc();
6005       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6006           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6007         Candidate.Viable = false;
6008         Candidate.FailureKind = ovl_fail_inhctor_slice;
6009         return;
6010       }
6011     }
6012   }
6013 
6014   unsigned NumParams = Proto->getNumParams();
6015 
6016   // (C++ 13.3.2p2): A candidate function having fewer than m
6017   // parameters is viable only if it has an ellipsis in its parameter
6018   // list (8.3.5).
6019   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6020       !Proto->isVariadic()) {
6021     Candidate.Viable = false;
6022     Candidate.FailureKind = ovl_fail_too_many_arguments;
6023     return;
6024   }
6025 
6026   // (C++ 13.3.2p2): A candidate function having more than m parameters
6027   // is viable only if the (m+1)st parameter has a default argument
6028   // (8.3.6). For the purposes of overload resolution, the
6029   // parameter list is truncated on the right, so that there are
6030   // exactly m parameters.
6031   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6032   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6033     // Not enough arguments.
6034     Candidate.Viable = false;
6035     Candidate.FailureKind = ovl_fail_too_few_arguments;
6036     return;
6037   }
6038 
6039   // (CUDA B.1): Check for invalid calls between targets.
6040   if (getLangOpts().CUDA)
6041     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6042       // Skip the check for callers that are implicit members, because in this
6043       // case we may not yet know what the member's target is; the target is
6044       // inferred for the member automatically, based on the bases and fields of
6045       // the class.
6046       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6047         Candidate.Viable = false;
6048         Candidate.FailureKind = ovl_fail_bad_target;
6049         return;
6050       }
6051 
6052   // Determine the implicit conversion sequences for each of the
6053   // arguments.
6054   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6055     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6056       // We already formed a conversion sequence for this parameter during
6057       // template argument deduction.
6058     } else if (ArgIdx < NumParams) {
6059       // (C++ 13.3.2p3): for F to be a viable function, there shall
6060       // exist for each argument an implicit conversion sequence
6061       // (13.3.3.1) that converts that argument to the corresponding
6062       // parameter of F.
6063       QualType ParamType = Proto->getParamType(ArgIdx);
6064       Candidate.Conversions[ArgIdx]
6065         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6066                                 SuppressUserConversions,
6067                                 /*InOverloadResolution=*/true,
6068                                 /*AllowObjCWritebackConversion=*/
6069                                   getLangOpts().ObjCAutoRefCount,
6070                                 AllowExplicit);
6071       if (Candidate.Conversions[ArgIdx].isBad()) {
6072         Candidate.Viable = false;
6073         Candidate.FailureKind = ovl_fail_bad_conversion;
6074         return;
6075       }
6076     } else {
6077       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6078       // argument for which there is no corresponding parameter is
6079       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6080       Candidate.Conversions[ArgIdx].setEllipsis();
6081     }
6082   }
6083 
6084   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6085     Candidate.Viable = false;
6086     Candidate.FailureKind = ovl_fail_enable_if;
6087     Candidate.DeductionFailure.Data = FailedAttr;
6088     return;
6089   }
6090 
6091   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6092     Candidate.Viable = false;
6093     Candidate.FailureKind = ovl_fail_ext_disabled;
6094     return;
6095   }
6096 }
6097 
6098 ObjCMethodDecl *
6099 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6100                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6101   if (Methods.size() <= 1)
6102     return nullptr;
6103 
6104   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6105     bool Match = true;
6106     ObjCMethodDecl *Method = Methods[b];
6107     unsigned NumNamedArgs = Sel.getNumArgs();
6108     // Method might have more arguments than selector indicates. This is due
6109     // to addition of c-style arguments in method.
6110     if (Method->param_size() > NumNamedArgs)
6111       NumNamedArgs = Method->param_size();
6112     if (Args.size() < NumNamedArgs)
6113       continue;
6114 
6115     for (unsigned i = 0; i < NumNamedArgs; i++) {
6116       // We can't do any type-checking on a type-dependent argument.
6117       if (Args[i]->isTypeDependent()) {
6118         Match = false;
6119         break;
6120       }
6121 
6122       ParmVarDecl *param = Method->parameters()[i];
6123       Expr *argExpr = Args[i];
6124       assert(argExpr && "SelectBestMethod(): missing expression");
6125 
6126       // Strip the unbridged-cast placeholder expression off unless it's
6127       // a consumed argument.
6128       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6129           !param->hasAttr<CFConsumedAttr>())
6130         argExpr = stripARCUnbridgedCast(argExpr);
6131 
6132       // If the parameter is __unknown_anytype, move on to the next method.
6133       if (param->getType() == Context.UnknownAnyTy) {
6134         Match = false;
6135         break;
6136       }
6137 
6138       ImplicitConversionSequence ConversionState
6139         = TryCopyInitialization(*this, argExpr, param->getType(),
6140                                 /*SuppressUserConversions*/false,
6141                                 /*InOverloadResolution=*/true,
6142                                 /*AllowObjCWritebackConversion=*/
6143                                 getLangOpts().ObjCAutoRefCount,
6144                                 /*AllowExplicit*/false);
6145       // This function looks for a reasonably-exact match, so we consider
6146       // incompatible pointer conversions to be a failure here.
6147       if (ConversionState.isBad() ||
6148           (ConversionState.isStandard() &&
6149            ConversionState.Standard.Second ==
6150                ICK_Incompatible_Pointer_Conversion)) {
6151         Match = false;
6152         break;
6153       }
6154     }
6155     // Promote additional arguments to variadic methods.
6156     if (Match && Method->isVariadic()) {
6157       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6158         if (Args[i]->isTypeDependent()) {
6159           Match = false;
6160           break;
6161         }
6162         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6163                                                           nullptr);
6164         if (Arg.isInvalid()) {
6165           Match = false;
6166           break;
6167         }
6168       }
6169     } else {
6170       // Check for extra arguments to non-variadic methods.
6171       if (Args.size() != NumNamedArgs)
6172         Match = false;
6173       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6174         // Special case when selectors have no argument. In this case, select
6175         // one with the most general result type of 'id'.
6176         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6177           QualType ReturnT = Methods[b]->getReturnType();
6178           if (ReturnT->isObjCIdType())
6179             return Methods[b];
6180         }
6181       }
6182     }
6183 
6184     if (Match)
6185       return Method;
6186   }
6187   return nullptr;
6188 }
6189 
6190 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6191 // enable_if is order-sensitive. As a result, we need to reverse things
6192 // sometimes. Size of 4 elements is arbitrary.
6193 static SmallVector<EnableIfAttr *, 4>
6194 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6195   SmallVector<EnableIfAttr *, 4> Result;
6196   if (!Function->hasAttrs())
6197     return Result;
6198 
6199   const auto &FuncAttrs = Function->getAttrs();
6200   for (Attr *Attr : FuncAttrs)
6201     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6202       Result.push_back(EnableIf);
6203 
6204   std::reverse(Result.begin(), Result.end());
6205   return Result;
6206 }
6207 
6208 static bool
6209 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6210                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6211                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6212                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6213   if (ThisArg) {
6214     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6215     assert(!isa<CXXConstructorDecl>(Method) &&
6216            "Shouldn't have `this` for ctors!");
6217     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6218     ExprResult R = S.PerformObjectArgumentInitialization(
6219         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6220     if (R.isInvalid())
6221       return false;
6222     ConvertedThis = R.get();
6223   } else {
6224     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6225       (void)MD;
6226       assert((MissingImplicitThis || MD->isStatic() ||
6227               isa<CXXConstructorDecl>(MD)) &&
6228              "Expected `this` for non-ctor instance methods");
6229     }
6230     ConvertedThis = nullptr;
6231   }
6232 
6233   // Ignore any variadic arguments. Converting them is pointless, since the
6234   // user can't refer to them in the function condition.
6235   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6236 
6237   // Convert the arguments.
6238   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6239     ExprResult R;
6240     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6241                                         S.Context, Function->getParamDecl(I)),
6242                                     SourceLocation(), Args[I]);
6243 
6244     if (R.isInvalid())
6245       return false;
6246 
6247     ConvertedArgs.push_back(R.get());
6248   }
6249 
6250   if (Trap.hasErrorOccurred())
6251     return false;
6252 
6253   // Push default arguments if needed.
6254   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6255     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6256       ParmVarDecl *P = Function->getParamDecl(i);
6257       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6258                          ? P->getUninstantiatedDefaultArg()
6259                          : P->getDefaultArg();
6260       // This can only happen in code completion, i.e. when PartialOverloading
6261       // is true.
6262       if (!DefArg)
6263         return false;
6264       ExprResult R =
6265           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6266                                           S.Context, Function->getParamDecl(i)),
6267                                       SourceLocation(), DefArg);
6268       if (R.isInvalid())
6269         return false;
6270       ConvertedArgs.push_back(R.get());
6271     }
6272 
6273     if (Trap.hasErrorOccurred())
6274       return false;
6275   }
6276   return true;
6277 }
6278 
6279 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6280                                   bool MissingImplicitThis) {
6281   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6282       getOrderedEnableIfAttrs(Function);
6283   if (EnableIfAttrs.empty())
6284     return nullptr;
6285 
6286   SFINAETrap Trap(*this);
6287   SmallVector<Expr *, 16> ConvertedArgs;
6288   // FIXME: We should look into making enable_if late-parsed.
6289   Expr *DiscardedThis;
6290   if (!convertArgsForAvailabilityChecks(
6291           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6292           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6293     return EnableIfAttrs[0];
6294 
6295   for (auto *EIA : EnableIfAttrs) {
6296     APValue Result;
6297     // FIXME: This doesn't consider value-dependent cases, because doing so is
6298     // very difficult. Ideally, we should handle them more gracefully.
6299     if (!EIA->getCond()->EvaluateWithSubstitution(
6300             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6301       return EIA;
6302 
6303     if (!Result.isInt() || !Result.getInt().getBoolValue())
6304       return EIA;
6305   }
6306   return nullptr;
6307 }
6308 
6309 template <typename CheckFn>
6310 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6311                                         bool ArgDependent, SourceLocation Loc,
6312                                         CheckFn &&IsSuccessful) {
6313   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6314   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6315     if (ArgDependent == DIA->getArgDependent())
6316       Attrs.push_back(DIA);
6317   }
6318 
6319   // Common case: No diagnose_if attributes, so we can quit early.
6320   if (Attrs.empty())
6321     return false;
6322 
6323   auto WarningBegin = std::stable_partition(
6324       Attrs.begin(), Attrs.end(),
6325       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6326 
6327   // Note that diagnose_if attributes are late-parsed, so they appear in the
6328   // correct order (unlike enable_if attributes).
6329   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6330                                IsSuccessful);
6331   if (ErrAttr != WarningBegin) {
6332     const DiagnoseIfAttr *DIA = *ErrAttr;
6333     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6334     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6335         << DIA->getParent() << DIA->getCond()->getSourceRange();
6336     return true;
6337   }
6338 
6339   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6340     if (IsSuccessful(DIA)) {
6341       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6342       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6343           << DIA->getParent() << DIA->getCond()->getSourceRange();
6344     }
6345 
6346   return false;
6347 }
6348 
6349 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6350                                                const Expr *ThisArg,
6351                                                ArrayRef<const Expr *> Args,
6352                                                SourceLocation Loc) {
6353   return diagnoseDiagnoseIfAttrsWith(
6354       *this, Function, /*ArgDependent=*/true, Loc,
6355       [&](const DiagnoseIfAttr *DIA) {
6356         APValue Result;
6357         // It's sane to use the same Args for any redecl of this function, since
6358         // EvaluateWithSubstitution only cares about the position of each
6359         // argument in the arg list, not the ParmVarDecl* it maps to.
6360         if (!DIA->getCond()->EvaluateWithSubstitution(
6361                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6362           return false;
6363         return Result.isInt() && Result.getInt().getBoolValue();
6364       });
6365 }
6366 
6367 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6368                                                  SourceLocation Loc) {
6369   return diagnoseDiagnoseIfAttrsWith(
6370       *this, ND, /*ArgDependent=*/false, Loc,
6371       [&](const DiagnoseIfAttr *DIA) {
6372         bool Result;
6373         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6374                Result;
6375       });
6376 }
6377 
6378 /// Add all of the function declarations in the given function set to
6379 /// the overload candidate set.
6380 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6381                                  ArrayRef<Expr *> Args,
6382                                  OverloadCandidateSet& CandidateSet,
6383                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6384                                  bool SuppressUserConversions,
6385                                  bool PartialOverloading,
6386                                  bool FirstArgumentIsBase) {
6387   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6388     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6389     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6390       ArrayRef<Expr *> FunctionArgs = Args;
6391       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6392         QualType ObjectType;
6393         Expr::Classification ObjectClassification;
6394         if (Args.size() > 0) {
6395           if (Expr *E = Args[0]) {
6396             // Use the explicit base to restrict the lookup:
6397             ObjectType = E->getType();
6398             ObjectClassification = E->Classify(Context);
6399           } // .. else there is an implit base.
6400           FunctionArgs = Args.slice(1);
6401         }
6402         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6403                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6404                            ObjectClassification, FunctionArgs, CandidateSet,
6405                            SuppressUserConversions, PartialOverloading);
6406       } else {
6407         // Slice the first argument (which is the base) when we access
6408         // static method as non-static
6409         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6410                                              !isa<CXXConstructorDecl>(FD)))) {
6411           assert(cast<CXXMethodDecl>(FD)->isStatic());
6412           FunctionArgs = Args.slice(1);
6413         }
6414         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6415                              SuppressUserConversions, PartialOverloading);
6416       }
6417     } else {
6418       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6419       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6420           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6421         QualType ObjectType;
6422         Expr::Classification ObjectClassification;
6423         if (Expr *E = Args[0]) {
6424           // Use the explicit base to restrict the lookup:
6425           ObjectType = E->getType();
6426           ObjectClassification = E->Classify(Context);
6427         } // .. else there is an implit base.
6428         AddMethodTemplateCandidate(
6429             FunTmpl, F.getPair(),
6430             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6431             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6432             Args.slice(1), CandidateSet, SuppressUserConversions,
6433             PartialOverloading);
6434       } else {
6435         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6436                                      ExplicitTemplateArgs, Args,
6437                                      CandidateSet, SuppressUserConversions,
6438                                      PartialOverloading);
6439       }
6440     }
6441   }
6442 }
6443 
6444 /// AddMethodCandidate - Adds a named decl (which is some kind of
6445 /// method) as a method candidate to the given overload set.
6446 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6447                               QualType ObjectType,
6448                               Expr::Classification ObjectClassification,
6449                               ArrayRef<Expr *> Args,
6450                               OverloadCandidateSet& CandidateSet,
6451                               bool SuppressUserConversions) {
6452   NamedDecl *Decl = FoundDecl.getDecl();
6453   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6454 
6455   if (isa<UsingShadowDecl>(Decl))
6456     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6457 
6458   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6459     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6460            "Expected a member function template");
6461     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6462                                /*ExplicitArgs*/ nullptr, ObjectType,
6463                                ObjectClassification, Args, CandidateSet,
6464                                SuppressUserConversions);
6465   } else {
6466     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6467                        ObjectType, ObjectClassification, Args, CandidateSet,
6468                        SuppressUserConversions);
6469   }
6470 }
6471 
6472 /// AddMethodCandidate - Adds the given C++ member function to the set
6473 /// of candidate functions, using the given function call arguments
6474 /// and the object argument (@c Object). For example, in a call
6475 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6476 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6477 /// allow user-defined conversions via constructors or conversion
6478 /// operators.
6479 void
6480 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6481                          CXXRecordDecl *ActingContext, QualType ObjectType,
6482                          Expr::Classification ObjectClassification,
6483                          ArrayRef<Expr *> Args,
6484                          OverloadCandidateSet &CandidateSet,
6485                          bool SuppressUserConversions,
6486                          bool PartialOverloading,
6487                          ConversionSequenceList EarlyConversions) {
6488   const FunctionProtoType *Proto
6489     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6490   assert(Proto && "Methods without a prototype cannot be overloaded");
6491   assert(!isa<CXXConstructorDecl>(Method) &&
6492          "Use AddOverloadCandidate for constructors");
6493 
6494   if (!CandidateSet.isNewCandidate(Method))
6495     return;
6496 
6497   // C++11 [class.copy]p23: [DR1402]
6498   //   A defaulted move assignment operator that is defined as deleted is
6499   //   ignored by overload resolution.
6500   if (Method->isDefaulted() && Method->isDeleted() &&
6501       Method->isMoveAssignmentOperator())
6502     return;
6503 
6504   // Overload resolution is always an unevaluated context.
6505   EnterExpressionEvaluationContext Unevaluated(
6506       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6507 
6508   // Add this candidate
6509   OverloadCandidate &Candidate =
6510       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6511   Candidate.FoundDecl = FoundDecl;
6512   Candidate.Function = Method;
6513   Candidate.IsSurrogate = false;
6514   Candidate.IgnoreObjectArgument = false;
6515   Candidate.ExplicitCallArguments = Args.size();
6516 
6517   unsigned NumParams = Proto->getNumParams();
6518 
6519   // (C++ 13.3.2p2): A candidate function having fewer than m
6520   // parameters is viable only if it has an ellipsis in its parameter
6521   // list (8.3.5).
6522   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6523       !Proto->isVariadic()) {
6524     Candidate.Viable = false;
6525     Candidate.FailureKind = ovl_fail_too_many_arguments;
6526     return;
6527   }
6528 
6529   // (C++ 13.3.2p2): A candidate function having more than m parameters
6530   // is viable only if the (m+1)st parameter has a default argument
6531   // (8.3.6). For the purposes of overload resolution, the
6532   // parameter list is truncated on the right, so that there are
6533   // exactly m parameters.
6534   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6535   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6536     // Not enough arguments.
6537     Candidate.Viable = false;
6538     Candidate.FailureKind = ovl_fail_too_few_arguments;
6539     return;
6540   }
6541 
6542   Candidate.Viable = true;
6543 
6544   if (Method->isStatic() || ObjectType.isNull())
6545     // The implicit object argument is ignored.
6546     Candidate.IgnoreObjectArgument = true;
6547   else {
6548     // Determine the implicit conversion sequence for the object
6549     // parameter.
6550     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6551         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6552         Method, ActingContext);
6553     if (Candidate.Conversions[0].isBad()) {
6554       Candidate.Viable = false;
6555       Candidate.FailureKind = ovl_fail_bad_conversion;
6556       return;
6557     }
6558   }
6559 
6560   // (CUDA B.1): Check for invalid calls between targets.
6561   if (getLangOpts().CUDA)
6562     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6563       if (!IsAllowedCUDACall(Caller, Method)) {
6564         Candidate.Viable = false;
6565         Candidate.FailureKind = ovl_fail_bad_target;
6566         return;
6567       }
6568 
6569   // Determine the implicit conversion sequences for each of the
6570   // arguments.
6571   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6572     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6573       // We already formed a conversion sequence for this parameter during
6574       // template argument deduction.
6575     } else if (ArgIdx < NumParams) {
6576       // (C++ 13.3.2p3): for F to be a viable function, there shall
6577       // exist for each argument an implicit conversion sequence
6578       // (13.3.3.1) that converts that argument to the corresponding
6579       // parameter of F.
6580       QualType ParamType = Proto->getParamType(ArgIdx);
6581       Candidate.Conversions[ArgIdx + 1]
6582         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6583                                 SuppressUserConversions,
6584                                 /*InOverloadResolution=*/true,
6585                                 /*AllowObjCWritebackConversion=*/
6586                                   getLangOpts().ObjCAutoRefCount);
6587       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6588         Candidate.Viable = false;
6589         Candidate.FailureKind = ovl_fail_bad_conversion;
6590         return;
6591       }
6592     } else {
6593       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6594       // argument for which there is no corresponding parameter is
6595       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6596       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6597     }
6598   }
6599 
6600   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6601     Candidate.Viable = false;
6602     Candidate.FailureKind = ovl_fail_enable_if;
6603     Candidate.DeductionFailure.Data = FailedAttr;
6604     return;
6605   }
6606 
6607   if (Method->isMultiVersion() &&
6608       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6609     Candidate.Viable = false;
6610     Candidate.FailureKind = ovl_non_default_multiversion_function;
6611   }
6612 }
6613 
6614 /// Add a C++ member function template as a candidate to the candidate
6615 /// set, using template argument deduction to produce an appropriate member
6616 /// function template specialization.
6617 void
6618 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6619                                  DeclAccessPair FoundDecl,
6620                                  CXXRecordDecl *ActingContext,
6621                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6622                                  QualType ObjectType,
6623                                  Expr::Classification ObjectClassification,
6624                                  ArrayRef<Expr *> Args,
6625                                  OverloadCandidateSet& CandidateSet,
6626                                  bool SuppressUserConversions,
6627                                  bool PartialOverloading) {
6628   if (!CandidateSet.isNewCandidate(MethodTmpl))
6629     return;
6630 
6631   // C++ [over.match.funcs]p7:
6632   //   In each case where a candidate is a function template, candidate
6633   //   function template specializations are generated using template argument
6634   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6635   //   candidate functions in the usual way.113) A given name can refer to one
6636   //   or more function templates and also to a set of overloaded non-template
6637   //   functions. In such a case, the candidate functions generated from each
6638   //   function template are combined with the set of non-template candidate
6639   //   functions.
6640   TemplateDeductionInfo Info(CandidateSet.getLocation());
6641   FunctionDecl *Specialization = nullptr;
6642   ConversionSequenceList Conversions;
6643   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6644           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6645           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6646             return CheckNonDependentConversions(
6647                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6648                 SuppressUserConversions, ActingContext, ObjectType,
6649                 ObjectClassification);
6650           })) {
6651     OverloadCandidate &Candidate =
6652         CandidateSet.addCandidate(Conversions.size(), Conversions);
6653     Candidate.FoundDecl = FoundDecl;
6654     Candidate.Function = MethodTmpl->getTemplatedDecl();
6655     Candidate.Viable = false;
6656     Candidate.IsSurrogate = false;
6657     Candidate.IgnoreObjectArgument =
6658         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6659         ObjectType.isNull();
6660     Candidate.ExplicitCallArguments = Args.size();
6661     if (Result == TDK_NonDependentConversionFailure)
6662       Candidate.FailureKind = ovl_fail_bad_conversion;
6663     else {
6664       Candidate.FailureKind = ovl_fail_bad_deduction;
6665       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6666                                                             Info);
6667     }
6668     return;
6669   }
6670 
6671   // Add the function template specialization produced by template argument
6672   // deduction as a candidate.
6673   assert(Specialization && "Missing member function template specialization?");
6674   assert(isa<CXXMethodDecl>(Specialization) &&
6675          "Specialization is not a member function?");
6676   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6677                      ActingContext, ObjectType, ObjectClassification, Args,
6678                      CandidateSet, SuppressUserConversions, PartialOverloading,
6679                      Conversions);
6680 }
6681 
6682 /// Add a C++ function template specialization as a candidate
6683 /// in the candidate set, using template argument deduction to produce
6684 /// an appropriate function template specialization.
6685 void
6686 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6687                                    DeclAccessPair FoundDecl,
6688                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6689                                    ArrayRef<Expr *> Args,
6690                                    OverloadCandidateSet& CandidateSet,
6691                                    bool SuppressUserConversions,
6692                                    bool PartialOverloading) {
6693   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6694     return;
6695 
6696   // C++ [over.match.funcs]p7:
6697   //   In each case where a candidate is a function template, candidate
6698   //   function template specializations are generated using template argument
6699   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6700   //   candidate functions in the usual way.113) A given name can refer to one
6701   //   or more function templates and also to a set of overloaded non-template
6702   //   functions. In such a case, the candidate functions generated from each
6703   //   function template are combined with the set of non-template candidate
6704   //   functions.
6705   TemplateDeductionInfo Info(CandidateSet.getLocation());
6706   FunctionDecl *Specialization = nullptr;
6707   ConversionSequenceList Conversions;
6708   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6709           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6710           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6711             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6712                                                 Args, CandidateSet, Conversions,
6713                                                 SuppressUserConversions);
6714           })) {
6715     OverloadCandidate &Candidate =
6716         CandidateSet.addCandidate(Conversions.size(), Conversions);
6717     Candidate.FoundDecl = FoundDecl;
6718     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6719     Candidate.Viable = false;
6720     Candidate.IsSurrogate = false;
6721     // Ignore the object argument if there is one, since we don't have an object
6722     // type.
6723     Candidate.IgnoreObjectArgument =
6724         isa<CXXMethodDecl>(Candidate.Function) &&
6725         !isa<CXXConstructorDecl>(Candidate.Function);
6726     Candidate.ExplicitCallArguments = Args.size();
6727     if (Result == TDK_NonDependentConversionFailure)
6728       Candidate.FailureKind = ovl_fail_bad_conversion;
6729     else {
6730       Candidate.FailureKind = ovl_fail_bad_deduction;
6731       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6732                                                             Info);
6733     }
6734     return;
6735   }
6736 
6737   // Add the function template specialization produced by template argument
6738   // deduction as a candidate.
6739   assert(Specialization && "Missing function template specialization?");
6740   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6741                        SuppressUserConversions, PartialOverloading,
6742                        /*AllowExplicit*/false, Conversions);
6743 }
6744 
6745 /// Check that implicit conversion sequences can be formed for each argument
6746 /// whose corresponding parameter has a non-dependent type, per DR1391's
6747 /// [temp.deduct.call]p10.
6748 bool Sema::CheckNonDependentConversions(
6749     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6750     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6751     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6752     CXXRecordDecl *ActingContext, QualType ObjectType,
6753     Expr::Classification ObjectClassification) {
6754   // FIXME: The cases in which we allow explicit conversions for constructor
6755   // arguments never consider calling a constructor template. It's not clear
6756   // that is correct.
6757   const bool AllowExplicit = false;
6758 
6759   auto *FD = FunctionTemplate->getTemplatedDecl();
6760   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6761   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6762   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6763 
6764   Conversions =
6765       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6766 
6767   // Overload resolution is always an unevaluated context.
6768   EnterExpressionEvaluationContext Unevaluated(
6769       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6770 
6771   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6772   // require that, but this check should never result in a hard error, and
6773   // overload resolution is permitted to sidestep instantiations.
6774   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6775       !ObjectType.isNull()) {
6776     Conversions[0] = TryObjectArgumentInitialization(
6777         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6778         Method, ActingContext);
6779     if (Conversions[0].isBad())
6780       return true;
6781   }
6782 
6783   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6784        ++I) {
6785     QualType ParamType = ParamTypes[I];
6786     if (!ParamType->isDependentType()) {
6787       Conversions[ThisConversions + I]
6788         = TryCopyInitialization(*this, Args[I], ParamType,
6789                                 SuppressUserConversions,
6790                                 /*InOverloadResolution=*/true,
6791                                 /*AllowObjCWritebackConversion=*/
6792                                   getLangOpts().ObjCAutoRefCount,
6793                                 AllowExplicit);
6794       if (Conversions[ThisConversions + I].isBad())
6795         return true;
6796     }
6797   }
6798 
6799   return false;
6800 }
6801 
6802 /// Determine whether this is an allowable conversion from the result
6803 /// of an explicit conversion operator to the expected type, per C++
6804 /// [over.match.conv]p1 and [over.match.ref]p1.
6805 ///
6806 /// \param ConvType The return type of the conversion function.
6807 ///
6808 /// \param ToType The type we are converting to.
6809 ///
6810 /// \param AllowObjCPointerConversion Allow a conversion from one
6811 /// Objective-C pointer to another.
6812 ///
6813 /// \returns true if the conversion is allowable, false otherwise.
6814 static bool isAllowableExplicitConversion(Sema &S,
6815                                           QualType ConvType, QualType ToType,
6816                                           bool AllowObjCPointerConversion) {
6817   QualType ToNonRefType = ToType.getNonReferenceType();
6818 
6819   // Easy case: the types are the same.
6820   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6821     return true;
6822 
6823   // Allow qualification conversions.
6824   bool ObjCLifetimeConversion;
6825   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6826                                   ObjCLifetimeConversion))
6827     return true;
6828 
6829   // If we're not allowed to consider Objective-C pointer conversions,
6830   // we're done.
6831   if (!AllowObjCPointerConversion)
6832     return false;
6833 
6834   // Is this an Objective-C pointer conversion?
6835   bool IncompatibleObjC = false;
6836   QualType ConvertedType;
6837   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6838                                    IncompatibleObjC);
6839 }
6840 
6841 /// AddConversionCandidate - Add a C++ conversion function as a
6842 /// candidate in the candidate set (C++ [over.match.conv],
6843 /// C++ [over.match.copy]). From is the expression we're converting from,
6844 /// and ToType is the type that we're eventually trying to convert to
6845 /// (which may or may not be the same type as the type that the
6846 /// conversion function produces).
6847 void
6848 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6849                              DeclAccessPair FoundDecl,
6850                              CXXRecordDecl *ActingContext,
6851                              Expr *From, QualType ToType,
6852                              OverloadCandidateSet& CandidateSet,
6853                              bool AllowObjCConversionOnExplicit,
6854                              bool AllowResultConversion) {
6855   assert(!Conversion->getDescribedFunctionTemplate() &&
6856          "Conversion function templates use AddTemplateConversionCandidate");
6857   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6858   if (!CandidateSet.isNewCandidate(Conversion))
6859     return;
6860 
6861   // If the conversion function has an undeduced return type, trigger its
6862   // deduction now.
6863   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6864     if (DeduceReturnType(Conversion, From->getExprLoc()))
6865       return;
6866     ConvType = Conversion->getConversionType().getNonReferenceType();
6867   }
6868 
6869   // If we don't allow any conversion of the result type, ignore conversion
6870   // functions that don't convert to exactly (possibly cv-qualified) T.
6871   if (!AllowResultConversion &&
6872       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6873     return;
6874 
6875   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6876   // operator is only a candidate if its return type is the target type or
6877   // can be converted to the target type with a qualification conversion.
6878   if (Conversion->isExplicit() &&
6879       !isAllowableExplicitConversion(*this, ConvType, ToType,
6880                                      AllowObjCConversionOnExplicit))
6881     return;
6882 
6883   // Overload resolution is always an unevaluated context.
6884   EnterExpressionEvaluationContext Unevaluated(
6885       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6886 
6887   // Add this candidate
6888   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6889   Candidate.FoundDecl = FoundDecl;
6890   Candidate.Function = Conversion;
6891   Candidate.IsSurrogate = false;
6892   Candidate.IgnoreObjectArgument = false;
6893   Candidate.FinalConversion.setAsIdentityConversion();
6894   Candidate.FinalConversion.setFromType(ConvType);
6895   Candidate.FinalConversion.setAllToTypes(ToType);
6896   Candidate.Viable = true;
6897   Candidate.ExplicitCallArguments = 1;
6898 
6899   // C++ [over.match.funcs]p4:
6900   //   For conversion functions, the function is considered to be a member of
6901   //   the class of the implicit implied object argument for the purpose of
6902   //   defining the type of the implicit object parameter.
6903   //
6904   // Determine the implicit conversion sequence for the implicit
6905   // object parameter.
6906   QualType ImplicitParamType = From->getType();
6907   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6908     ImplicitParamType = FromPtrType->getPointeeType();
6909   CXXRecordDecl *ConversionContext
6910     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6911 
6912   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6913       *this, CandidateSet.getLocation(), From->getType(),
6914       From->Classify(Context), Conversion, ConversionContext);
6915 
6916   if (Candidate.Conversions[0].isBad()) {
6917     Candidate.Viable = false;
6918     Candidate.FailureKind = ovl_fail_bad_conversion;
6919     return;
6920   }
6921 
6922   // We won't go through a user-defined type conversion function to convert a
6923   // derived to base as such conversions are given Conversion Rank. They only
6924   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6925   QualType FromCanon
6926     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6927   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6928   if (FromCanon == ToCanon ||
6929       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6930     Candidate.Viable = false;
6931     Candidate.FailureKind = ovl_fail_trivial_conversion;
6932     return;
6933   }
6934 
6935   // To determine what the conversion from the result of calling the
6936   // conversion function to the type we're eventually trying to
6937   // convert to (ToType), we need to synthesize a call to the
6938   // conversion function and attempt copy initialization from it. This
6939   // makes sure that we get the right semantics with respect to
6940   // lvalues/rvalues and the type. Fortunately, we can allocate this
6941   // call on the stack and we don't need its arguments to be
6942   // well-formed.
6943   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6944                             VK_LValue, From->getLocStart());
6945   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6946                                 Context.getPointerType(Conversion->getType()),
6947                                 CK_FunctionToPointerDecay,
6948                                 &ConversionRef, VK_RValue);
6949 
6950   QualType ConversionType = Conversion->getConversionType();
6951   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6952     Candidate.Viable = false;
6953     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6954     return;
6955   }
6956 
6957   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6958 
6959   // Note that it is safe to allocate CallExpr on the stack here because
6960   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6961   // allocator).
6962   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6963   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6964                 From->getLocStart());
6965   ImplicitConversionSequence ICS =
6966     TryCopyInitialization(*this, &Call, ToType,
6967                           /*SuppressUserConversions=*/true,
6968                           /*InOverloadResolution=*/false,
6969                           /*AllowObjCWritebackConversion=*/false);
6970 
6971   switch (ICS.getKind()) {
6972   case ImplicitConversionSequence::StandardConversion:
6973     Candidate.FinalConversion = ICS.Standard;
6974 
6975     // C++ [over.ics.user]p3:
6976     //   If the user-defined conversion is specified by a specialization of a
6977     //   conversion function template, the second standard conversion sequence
6978     //   shall have exact match rank.
6979     if (Conversion->getPrimaryTemplate() &&
6980         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6981       Candidate.Viable = false;
6982       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6983       return;
6984     }
6985 
6986     // C++0x [dcl.init.ref]p5:
6987     //    In the second case, if the reference is an rvalue reference and
6988     //    the second standard conversion sequence of the user-defined
6989     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6990     //    program is ill-formed.
6991     if (ToType->isRValueReferenceType() &&
6992         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6993       Candidate.Viable = false;
6994       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6995       return;
6996     }
6997     break;
6998 
6999   case ImplicitConversionSequence::BadConversion:
7000     Candidate.Viable = false;
7001     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7002     return;
7003 
7004   default:
7005     llvm_unreachable(
7006            "Can only end up with a standard conversion sequence or failure");
7007   }
7008 
7009   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7010     Candidate.Viable = false;
7011     Candidate.FailureKind = ovl_fail_enable_if;
7012     Candidate.DeductionFailure.Data = FailedAttr;
7013     return;
7014   }
7015 
7016   if (Conversion->isMultiVersion() &&
7017       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7018     Candidate.Viable = false;
7019     Candidate.FailureKind = ovl_non_default_multiversion_function;
7020   }
7021 }
7022 
7023 /// Adds a conversion function template specialization
7024 /// candidate to the overload set, using template argument deduction
7025 /// to deduce the template arguments of the conversion function
7026 /// template from the type that we are converting to (C++
7027 /// [temp.deduct.conv]).
7028 void
7029 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7030                                      DeclAccessPair FoundDecl,
7031                                      CXXRecordDecl *ActingDC,
7032                                      Expr *From, QualType ToType,
7033                                      OverloadCandidateSet &CandidateSet,
7034                                      bool AllowObjCConversionOnExplicit,
7035                                      bool AllowResultConversion) {
7036   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7037          "Only conversion function templates permitted here");
7038 
7039   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7040     return;
7041 
7042   TemplateDeductionInfo Info(CandidateSet.getLocation());
7043   CXXConversionDecl *Specialization = nullptr;
7044   if (TemplateDeductionResult Result
7045         = DeduceTemplateArguments(FunctionTemplate, ToType,
7046                                   Specialization, Info)) {
7047     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7048     Candidate.FoundDecl = FoundDecl;
7049     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7050     Candidate.Viable = false;
7051     Candidate.FailureKind = ovl_fail_bad_deduction;
7052     Candidate.IsSurrogate = false;
7053     Candidate.IgnoreObjectArgument = false;
7054     Candidate.ExplicitCallArguments = 1;
7055     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7056                                                           Info);
7057     return;
7058   }
7059 
7060   // Add the conversion function template specialization produced by
7061   // template argument deduction as a candidate.
7062   assert(Specialization && "Missing function template specialization?");
7063   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7064                          CandidateSet, AllowObjCConversionOnExplicit,
7065                          AllowResultConversion);
7066 }
7067 
7068 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7069 /// converts the given @c Object to a function pointer via the
7070 /// conversion function @c Conversion, and then attempts to call it
7071 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7072 /// the type of function that we'll eventually be calling.
7073 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7074                                  DeclAccessPair FoundDecl,
7075                                  CXXRecordDecl *ActingContext,
7076                                  const FunctionProtoType *Proto,
7077                                  Expr *Object,
7078                                  ArrayRef<Expr *> Args,
7079                                  OverloadCandidateSet& CandidateSet) {
7080   if (!CandidateSet.isNewCandidate(Conversion))
7081     return;
7082 
7083   // Overload resolution is always an unevaluated context.
7084   EnterExpressionEvaluationContext Unevaluated(
7085       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7086 
7087   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7088   Candidate.FoundDecl = FoundDecl;
7089   Candidate.Function = nullptr;
7090   Candidate.Surrogate = Conversion;
7091   Candidate.Viable = true;
7092   Candidate.IsSurrogate = true;
7093   Candidate.IgnoreObjectArgument = false;
7094   Candidate.ExplicitCallArguments = Args.size();
7095 
7096   // Determine the implicit conversion sequence for the implicit
7097   // object parameter.
7098   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7099       *this, CandidateSet.getLocation(), Object->getType(),
7100       Object->Classify(Context), Conversion, ActingContext);
7101   if (ObjectInit.isBad()) {
7102     Candidate.Viable = false;
7103     Candidate.FailureKind = ovl_fail_bad_conversion;
7104     Candidate.Conversions[0] = ObjectInit;
7105     return;
7106   }
7107 
7108   // The first conversion is actually a user-defined conversion whose
7109   // first conversion is ObjectInit's standard conversion (which is
7110   // effectively a reference binding). Record it as such.
7111   Candidate.Conversions[0].setUserDefined();
7112   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7113   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7114   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7115   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7116   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7117   Candidate.Conversions[0].UserDefined.After
7118     = Candidate.Conversions[0].UserDefined.Before;
7119   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7120 
7121   // Find the
7122   unsigned NumParams = Proto->getNumParams();
7123 
7124   // (C++ 13.3.2p2): A candidate function having fewer than m
7125   // parameters is viable only if it has an ellipsis in its parameter
7126   // list (8.3.5).
7127   if (Args.size() > NumParams && !Proto->isVariadic()) {
7128     Candidate.Viable = false;
7129     Candidate.FailureKind = ovl_fail_too_many_arguments;
7130     return;
7131   }
7132 
7133   // Function types don't have any default arguments, so just check if
7134   // we have enough arguments.
7135   if (Args.size() < NumParams) {
7136     // Not enough arguments.
7137     Candidate.Viable = false;
7138     Candidate.FailureKind = ovl_fail_too_few_arguments;
7139     return;
7140   }
7141 
7142   // Determine the implicit conversion sequences for each of the
7143   // arguments.
7144   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7145     if (ArgIdx < NumParams) {
7146       // (C++ 13.3.2p3): for F to be a viable function, there shall
7147       // exist for each argument an implicit conversion sequence
7148       // (13.3.3.1) that converts that argument to the corresponding
7149       // parameter of F.
7150       QualType ParamType = Proto->getParamType(ArgIdx);
7151       Candidate.Conversions[ArgIdx + 1]
7152         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7153                                 /*SuppressUserConversions=*/false,
7154                                 /*InOverloadResolution=*/false,
7155                                 /*AllowObjCWritebackConversion=*/
7156                                   getLangOpts().ObjCAutoRefCount);
7157       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7158         Candidate.Viable = false;
7159         Candidate.FailureKind = ovl_fail_bad_conversion;
7160         return;
7161       }
7162     } else {
7163       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7164       // argument for which there is no corresponding parameter is
7165       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7166       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7167     }
7168   }
7169 
7170   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7171     Candidate.Viable = false;
7172     Candidate.FailureKind = ovl_fail_enable_if;
7173     Candidate.DeductionFailure.Data = FailedAttr;
7174     return;
7175   }
7176 }
7177 
7178 /// Add overload candidates for overloaded operators that are
7179 /// member functions.
7180 ///
7181 /// Add the overloaded operator candidates that are member functions
7182 /// for the operator Op that was used in an operator expression such
7183 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7184 /// CandidateSet will store the added overload candidates. (C++
7185 /// [over.match.oper]).
7186 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7187                                        SourceLocation OpLoc,
7188                                        ArrayRef<Expr *> Args,
7189                                        OverloadCandidateSet& CandidateSet,
7190                                        SourceRange OpRange) {
7191   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7192 
7193   // C++ [over.match.oper]p3:
7194   //   For a unary operator @ with an operand of a type whose
7195   //   cv-unqualified version is T1, and for a binary operator @ with
7196   //   a left operand of a type whose cv-unqualified version is T1 and
7197   //   a right operand of a type whose cv-unqualified version is T2,
7198   //   three sets of candidate functions, designated member
7199   //   candidates, non-member candidates and built-in candidates, are
7200   //   constructed as follows:
7201   QualType T1 = Args[0]->getType();
7202 
7203   //     -- If T1 is a complete class type or a class currently being
7204   //        defined, the set of member candidates is the result of the
7205   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7206   //        the set of member candidates is empty.
7207   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7208     // Complete the type if it can be completed.
7209     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7210       return;
7211     // If the type is neither complete nor being defined, bail out now.
7212     if (!T1Rec->getDecl()->getDefinition())
7213       return;
7214 
7215     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7216     LookupQualifiedName(Operators, T1Rec->getDecl());
7217     Operators.suppressDiagnostics();
7218 
7219     for (LookupResult::iterator Oper = Operators.begin(),
7220                              OperEnd = Operators.end();
7221          Oper != OperEnd;
7222          ++Oper)
7223       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7224                          Args[0]->Classify(Context), Args.slice(1),
7225                          CandidateSet, /*SuppressUserConversions=*/false);
7226   }
7227 }
7228 
7229 /// AddBuiltinCandidate - Add a candidate for a built-in
7230 /// operator. ResultTy and ParamTys are the result and parameter types
7231 /// of the built-in candidate, respectively. Args and NumArgs are the
7232 /// arguments being passed to the candidate. IsAssignmentOperator
7233 /// should be true when this built-in candidate is an assignment
7234 /// operator. NumContextualBoolArguments is the number of arguments
7235 /// (at the beginning of the argument list) that will be contextually
7236 /// converted to bool.
7237 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7238                                OverloadCandidateSet& CandidateSet,
7239                                bool IsAssignmentOperator,
7240                                unsigned NumContextualBoolArguments) {
7241   // Overload resolution is always an unevaluated context.
7242   EnterExpressionEvaluationContext Unevaluated(
7243       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7244 
7245   // Add this candidate
7246   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7247   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7248   Candidate.Function = nullptr;
7249   Candidate.IsSurrogate = false;
7250   Candidate.IgnoreObjectArgument = false;
7251   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7252 
7253   // Determine the implicit conversion sequences for each of the
7254   // arguments.
7255   Candidate.Viable = true;
7256   Candidate.ExplicitCallArguments = Args.size();
7257   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7258     // C++ [over.match.oper]p4:
7259     //   For the built-in assignment operators, conversions of the
7260     //   left operand are restricted as follows:
7261     //     -- no temporaries are introduced to hold the left operand, and
7262     //     -- no user-defined conversions are applied to the left
7263     //        operand to achieve a type match with the left-most
7264     //        parameter of a built-in candidate.
7265     //
7266     // We block these conversions by turning off user-defined
7267     // conversions, since that is the only way that initialization of
7268     // a reference to a non-class type can occur from something that
7269     // is not of the same type.
7270     if (ArgIdx < NumContextualBoolArguments) {
7271       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7272              "Contextual conversion to bool requires bool type");
7273       Candidate.Conversions[ArgIdx]
7274         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7275     } else {
7276       Candidate.Conversions[ArgIdx]
7277         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7278                                 ArgIdx == 0 && IsAssignmentOperator,
7279                                 /*InOverloadResolution=*/false,
7280                                 /*AllowObjCWritebackConversion=*/
7281                                   getLangOpts().ObjCAutoRefCount);
7282     }
7283     if (Candidate.Conversions[ArgIdx].isBad()) {
7284       Candidate.Viable = false;
7285       Candidate.FailureKind = ovl_fail_bad_conversion;
7286       break;
7287     }
7288   }
7289 }
7290 
7291 namespace {
7292 
7293 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7294 /// candidate operator functions for built-in operators (C++
7295 /// [over.built]). The types are separated into pointer types and
7296 /// enumeration types.
7297 class BuiltinCandidateTypeSet  {
7298   /// TypeSet - A set of types.
7299   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7300                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7301 
7302   /// PointerTypes - The set of pointer types that will be used in the
7303   /// built-in candidates.
7304   TypeSet PointerTypes;
7305 
7306   /// MemberPointerTypes - The set of member pointer types that will be
7307   /// used in the built-in candidates.
7308   TypeSet MemberPointerTypes;
7309 
7310   /// EnumerationTypes - The set of enumeration types that will be
7311   /// used in the built-in candidates.
7312   TypeSet EnumerationTypes;
7313 
7314   /// The set of vector types that will be used in the built-in
7315   /// candidates.
7316   TypeSet VectorTypes;
7317 
7318   /// A flag indicating non-record types are viable candidates
7319   bool HasNonRecordTypes;
7320 
7321   /// A flag indicating whether either arithmetic or enumeration types
7322   /// were present in the candidate set.
7323   bool HasArithmeticOrEnumeralTypes;
7324 
7325   /// A flag indicating whether the nullptr type was present in the
7326   /// candidate set.
7327   bool HasNullPtrType;
7328 
7329   /// Sema - The semantic analysis instance where we are building the
7330   /// candidate type set.
7331   Sema &SemaRef;
7332 
7333   /// Context - The AST context in which we will build the type sets.
7334   ASTContext &Context;
7335 
7336   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7337                                                const Qualifiers &VisibleQuals);
7338   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7339 
7340 public:
7341   /// iterator - Iterates through the types that are part of the set.
7342   typedef TypeSet::iterator iterator;
7343 
7344   BuiltinCandidateTypeSet(Sema &SemaRef)
7345     : HasNonRecordTypes(false),
7346       HasArithmeticOrEnumeralTypes(false),
7347       HasNullPtrType(false),
7348       SemaRef(SemaRef),
7349       Context(SemaRef.Context) { }
7350 
7351   void AddTypesConvertedFrom(QualType Ty,
7352                              SourceLocation Loc,
7353                              bool AllowUserConversions,
7354                              bool AllowExplicitConversions,
7355                              const Qualifiers &VisibleTypeConversionsQuals);
7356 
7357   /// pointer_begin - First pointer type found;
7358   iterator pointer_begin() { return PointerTypes.begin(); }
7359 
7360   /// pointer_end - Past the last pointer type found;
7361   iterator pointer_end() { return PointerTypes.end(); }
7362 
7363   /// member_pointer_begin - First member pointer type found;
7364   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7365 
7366   /// member_pointer_end - Past the last member pointer type found;
7367   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7368 
7369   /// enumeration_begin - First enumeration type found;
7370   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7371 
7372   /// enumeration_end - Past the last enumeration type found;
7373   iterator enumeration_end() { return EnumerationTypes.end(); }
7374 
7375   iterator vector_begin() { return VectorTypes.begin(); }
7376   iterator vector_end() { return VectorTypes.end(); }
7377 
7378   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7379   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7380   bool hasNullPtrType() const { return HasNullPtrType; }
7381 };
7382 
7383 } // end anonymous namespace
7384 
7385 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7386 /// the set of pointer types along with any more-qualified variants of
7387 /// that type. For example, if @p Ty is "int const *", this routine
7388 /// will add "int const *", "int const volatile *", "int const
7389 /// restrict *", and "int const volatile restrict *" to the set of
7390 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7391 /// false otherwise.
7392 ///
7393 /// FIXME: what to do about extended qualifiers?
7394 bool
7395 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7396                                              const Qualifiers &VisibleQuals) {
7397 
7398   // Insert this type.
7399   if (!PointerTypes.insert(Ty))
7400     return false;
7401 
7402   QualType PointeeTy;
7403   const PointerType *PointerTy = Ty->getAs<PointerType>();
7404   bool buildObjCPtr = false;
7405   if (!PointerTy) {
7406     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7407     PointeeTy = PTy->getPointeeType();
7408     buildObjCPtr = true;
7409   } else {
7410     PointeeTy = PointerTy->getPointeeType();
7411   }
7412 
7413   // Don't add qualified variants of arrays. For one, they're not allowed
7414   // (the qualifier would sink to the element type), and for another, the
7415   // only overload situation where it matters is subscript or pointer +- int,
7416   // and those shouldn't have qualifier variants anyway.
7417   if (PointeeTy->isArrayType())
7418     return true;
7419 
7420   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7421   bool hasVolatile = VisibleQuals.hasVolatile();
7422   bool hasRestrict = VisibleQuals.hasRestrict();
7423 
7424   // Iterate through all strict supersets of BaseCVR.
7425   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7426     if ((CVR | BaseCVR) != CVR) continue;
7427     // Skip over volatile if no volatile found anywhere in the types.
7428     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7429 
7430     // Skip over restrict if no restrict found anywhere in the types, or if
7431     // the type cannot be restrict-qualified.
7432     if ((CVR & Qualifiers::Restrict) &&
7433         (!hasRestrict ||
7434          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7435       continue;
7436 
7437     // Build qualified pointee type.
7438     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7439 
7440     // Build qualified pointer type.
7441     QualType QPointerTy;
7442     if (!buildObjCPtr)
7443       QPointerTy = Context.getPointerType(QPointeeTy);
7444     else
7445       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7446 
7447     // Insert qualified pointer type.
7448     PointerTypes.insert(QPointerTy);
7449   }
7450 
7451   return true;
7452 }
7453 
7454 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7455 /// to the set of pointer types along with any more-qualified variants of
7456 /// that type. For example, if @p Ty is "int const *", this routine
7457 /// will add "int const *", "int const volatile *", "int const
7458 /// restrict *", and "int const volatile restrict *" to the set of
7459 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7460 /// false otherwise.
7461 ///
7462 /// FIXME: what to do about extended qualifiers?
7463 bool
7464 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7465     QualType Ty) {
7466   // Insert this type.
7467   if (!MemberPointerTypes.insert(Ty))
7468     return false;
7469 
7470   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7471   assert(PointerTy && "type was not a member pointer type!");
7472 
7473   QualType PointeeTy = PointerTy->getPointeeType();
7474   // Don't add qualified variants of arrays. For one, they're not allowed
7475   // (the qualifier would sink to the element type), and for another, the
7476   // only overload situation where it matters is subscript or pointer +- int,
7477   // and those shouldn't have qualifier variants anyway.
7478   if (PointeeTy->isArrayType())
7479     return true;
7480   const Type *ClassTy = PointerTy->getClass();
7481 
7482   // Iterate through all strict supersets of the pointee type's CVR
7483   // qualifiers.
7484   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7485   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7486     if ((CVR | BaseCVR) != CVR) continue;
7487 
7488     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7489     MemberPointerTypes.insert(
7490       Context.getMemberPointerType(QPointeeTy, ClassTy));
7491   }
7492 
7493   return true;
7494 }
7495 
7496 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7497 /// Ty can be implicit converted to the given set of @p Types. We're
7498 /// primarily interested in pointer types and enumeration types. We also
7499 /// take member pointer types, for the conditional operator.
7500 /// AllowUserConversions is true if we should look at the conversion
7501 /// functions of a class type, and AllowExplicitConversions if we
7502 /// should also include the explicit conversion functions of a class
7503 /// type.
7504 void
7505 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7506                                                SourceLocation Loc,
7507                                                bool AllowUserConversions,
7508                                                bool AllowExplicitConversions,
7509                                                const Qualifiers &VisibleQuals) {
7510   // Only deal with canonical types.
7511   Ty = Context.getCanonicalType(Ty);
7512 
7513   // Look through reference types; they aren't part of the type of an
7514   // expression for the purposes of conversions.
7515   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7516     Ty = RefTy->getPointeeType();
7517 
7518   // If we're dealing with an array type, decay to the pointer.
7519   if (Ty->isArrayType())
7520     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7521 
7522   // Otherwise, we don't care about qualifiers on the type.
7523   Ty = Ty.getLocalUnqualifiedType();
7524 
7525   // Flag if we ever add a non-record type.
7526   const RecordType *TyRec = Ty->getAs<RecordType>();
7527   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7528 
7529   // Flag if we encounter an arithmetic type.
7530   HasArithmeticOrEnumeralTypes =
7531     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7532 
7533   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7534     PointerTypes.insert(Ty);
7535   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7536     // Insert our type, and its more-qualified variants, into the set
7537     // of types.
7538     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7539       return;
7540   } else if (Ty->isMemberPointerType()) {
7541     // Member pointers are far easier, since the pointee can't be converted.
7542     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7543       return;
7544   } else if (Ty->isEnumeralType()) {
7545     HasArithmeticOrEnumeralTypes = true;
7546     EnumerationTypes.insert(Ty);
7547   } else if (Ty->isVectorType()) {
7548     // We treat vector types as arithmetic types in many contexts as an
7549     // extension.
7550     HasArithmeticOrEnumeralTypes = true;
7551     VectorTypes.insert(Ty);
7552   } else if (Ty->isNullPtrType()) {
7553     HasNullPtrType = true;
7554   } else if (AllowUserConversions && TyRec) {
7555     // No conversion functions in incomplete types.
7556     if (!SemaRef.isCompleteType(Loc, Ty))
7557       return;
7558 
7559     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7560     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7561       if (isa<UsingShadowDecl>(D))
7562         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7563 
7564       // Skip conversion function templates; they don't tell us anything
7565       // about which builtin types we can convert to.
7566       if (isa<FunctionTemplateDecl>(D))
7567         continue;
7568 
7569       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7570       if (AllowExplicitConversions || !Conv->isExplicit()) {
7571         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7572                               VisibleQuals);
7573       }
7574     }
7575   }
7576 }
7577 
7578 /// Helper function for AddBuiltinOperatorCandidates() that adds
7579 /// the volatile- and non-volatile-qualified assignment operators for the
7580 /// given type to the candidate set.
7581 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7582                                                    QualType T,
7583                                                    ArrayRef<Expr *> Args,
7584                                     OverloadCandidateSet &CandidateSet) {
7585   QualType ParamTypes[2];
7586 
7587   // T& operator=(T&, T)
7588   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7589   ParamTypes[1] = T;
7590   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7591                         /*IsAssignmentOperator=*/true);
7592 
7593   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7594     // volatile T& operator=(volatile T&, T)
7595     ParamTypes[0]
7596       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7597     ParamTypes[1] = T;
7598     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7599                           /*IsAssignmentOperator=*/true);
7600   }
7601 }
7602 
7603 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7604 /// if any, found in visible type conversion functions found in ArgExpr's type.
7605 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7606     Qualifiers VRQuals;
7607     const RecordType *TyRec;
7608     if (const MemberPointerType *RHSMPType =
7609         ArgExpr->getType()->getAs<MemberPointerType>())
7610       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7611     else
7612       TyRec = ArgExpr->getType()->getAs<RecordType>();
7613     if (!TyRec) {
7614       // Just to be safe, assume the worst case.
7615       VRQuals.addVolatile();
7616       VRQuals.addRestrict();
7617       return VRQuals;
7618     }
7619 
7620     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7621     if (!ClassDecl->hasDefinition())
7622       return VRQuals;
7623 
7624     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7625       if (isa<UsingShadowDecl>(D))
7626         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7627       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7628         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7629         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7630           CanTy = ResTypeRef->getPointeeType();
7631         // Need to go down the pointer/mempointer chain and add qualifiers
7632         // as see them.
7633         bool done = false;
7634         while (!done) {
7635           if (CanTy.isRestrictQualified())
7636             VRQuals.addRestrict();
7637           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7638             CanTy = ResTypePtr->getPointeeType();
7639           else if (const MemberPointerType *ResTypeMPtr =
7640                 CanTy->getAs<MemberPointerType>())
7641             CanTy = ResTypeMPtr->getPointeeType();
7642           else
7643             done = true;
7644           if (CanTy.isVolatileQualified())
7645             VRQuals.addVolatile();
7646           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7647             return VRQuals;
7648         }
7649       }
7650     }
7651     return VRQuals;
7652 }
7653 
7654 namespace {
7655 
7656 /// Helper class to manage the addition of builtin operator overload
7657 /// candidates. It provides shared state and utility methods used throughout
7658 /// the process, as well as a helper method to add each group of builtin
7659 /// operator overloads from the standard to a candidate set.
7660 class BuiltinOperatorOverloadBuilder {
7661   // Common instance state available to all overload candidate addition methods.
7662   Sema &S;
7663   ArrayRef<Expr *> Args;
7664   Qualifiers VisibleTypeConversionsQuals;
7665   bool HasArithmeticOrEnumeralCandidateType;
7666   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7667   OverloadCandidateSet &CandidateSet;
7668 
7669   static constexpr int ArithmeticTypesCap = 24;
7670   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7671 
7672   // Define some indices used to iterate over the arithemetic types in
7673   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7674   // types are that preserved by promotion (C++ [over.built]p2).
7675   unsigned FirstIntegralType,
7676            LastIntegralType;
7677   unsigned FirstPromotedIntegralType,
7678            LastPromotedIntegralType;
7679   unsigned FirstPromotedArithmeticType,
7680            LastPromotedArithmeticType;
7681   unsigned NumArithmeticTypes;
7682 
7683   void InitArithmeticTypes() {
7684     // Start of promoted types.
7685     FirstPromotedArithmeticType = 0;
7686     ArithmeticTypes.push_back(S.Context.FloatTy);
7687     ArithmeticTypes.push_back(S.Context.DoubleTy);
7688     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7689     if (S.Context.getTargetInfo().hasFloat128Type())
7690       ArithmeticTypes.push_back(S.Context.Float128Ty);
7691 
7692     // Start of integral types.
7693     FirstIntegralType = ArithmeticTypes.size();
7694     FirstPromotedIntegralType = ArithmeticTypes.size();
7695     ArithmeticTypes.push_back(S.Context.IntTy);
7696     ArithmeticTypes.push_back(S.Context.LongTy);
7697     ArithmeticTypes.push_back(S.Context.LongLongTy);
7698     if (S.Context.getTargetInfo().hasInt128Type())
7699       ArithmeticTypes.push_back(S.Context.Int128Ty);
7700     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7701     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7702     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7703     if (S.Context.getTargetInfo().hasInt128Type())
7704       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7705     LastPromotedIntegralType = ArithmeticTypes.size();
7706     LastPromotedArithmeticType = ArithmeticTypes.size();
7707     // End of promoted types.
7708 
7709     ArithmeticTypes.push_back(S.Context.BoolTy);
7710     ArithmeticTypes.push_back(S.Context.CharTy);
7711     ArithmeticTypes.push_back(S.Context.WCharTy);
7712     if (S.Context.getLangOpts().Char8)
7713       ArithmeticTypes.push_back(S.Context.Char8Ty);
7714     ArithmeticTypes.push_back(S.Context.Char16Ty);
7715     ArithmeticTypes.push_back(S.Context.Char32Ty);
7716     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7717     ArithmeticTypes.push_back(S.Context.ShortTy);
7718     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7719     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7720     LastIntegralType = ArithmeticTypes.size();
7721     NumArithmeticTypes = ArithmeticTypes.size();
7722     // End of integral types.
7723     // FIXME: What about complex? What about half?
7724 
7725     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7726            "Enough inline storage for all arithmetic types.");
7727   }
7728 
7729   /// Helper method to factor out the common pattern of adding overloads
7730   /// for '++' and '--' builtin operators.
7731   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7732                                            bool HasVolatile,
7733                                            bool HasRestrict) {
7734     QualType ParamTypes[2] = {
7735       S.Context.getLValueReferenceType(CandidateTy),
7736       S.Context.IntTy
7737     };
7738 
7739     // Non-volatile version.
7740     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7741 
7742     // Use a heuristic to reduce number of builtin candidates in the set:
7743     // add volatile version only if there are conversions to a volatile type.
7744     if (HasVolatile) {
7745       ParamTypes[0] =
7746         S.Context.getLValueReferenceType(
7747           S.Context.getVolatileType(CandidateTy));
7748       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7749     }
7750 
7751     // Add restrict version only if there are conversions to a restrict type
7752     // and our candidate type is a non-restrict-qualified pointer.
7753     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7754         !CandidateTy.isRestrictQualified()) {
7755       ParamTypes[0]
7756         = S.Context.getLValueReferenceType(
7757             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7758       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7759 
7760       if (HasVolatile) {
7761         ParamTypes[0]
7762           = S.Context.getLValueReferenceType(
7763               S.Context.getCVRQualifiedType(CandidateTy,
7764                                             (Qualifiers::Volatile |
7765                                              Qualifiers::Restrict)));
7766         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7767       }
7768     }
7769 
7770   }
7771 
7772 public:
7773   BuiltinOperatorOverloadBuilder(
7774     Sema &S, ArrayRef<Expr *> Args,
7775     Qualifiers VisibleTypeConversionsQuals,
7776     bool HasArithmeticOrEnumeralCandidateType,
7777     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7778     OverloadCandidateSet &CandidateSet)
7779     : S(S), Args(Args),
7780       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7781       HasArithmeticOrEnumeralCandidateType(
7782         HasArithmeticOrEnumeralCandidateType),
7783       CandidateTypes(CandidateTypes),
7784       CandidateSet(CandidateSet) {
7785 
7786     InitArithmeticTypes();
7787   }
7788 
7789   // Increment is deprecated for bool since C++17.
7790   //
7791   // C++ [over.built]p3:
7792   //
7793   //   For every pair (T, VQ), where T is an arithmetic type other
7794   //   than bool, and VQ is either volatile or empty, there exist
7795   //   candidate operator functions of the form
7796   //
7797   //       VQ T&      operator++(VQ T&);
7798   //       T          operator++(VQ T&, int);
7799   //
7800   // C++ [over.built]p4:
7801   //
7802   //   For every pair (T, VQ), where T is an arithmetic type other
7803   //   than bool, and VQ is either volatile or empty, there exist
7804   //   candidate operator functions of the form
7805   //
7806   //       VQ T&      operator--(VQ T&);
7807   //       T          operator--(VQ T&, int);
7808   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7809     if (!HasArithmeticOrEnumeralCandidateType)
7810       return;
7811 
7812     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7813       const auto TypeOfT = ArithmeticTypes[Arith];
7814       if (TypeOfT == S.Context.BoolTy) {
7815         if (Op == OO_MinusMinus)
7816           continue;
7817         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7818           continue;
7819       }
7820       addPlusPlusMinusMinusStyleOverloads(
7821         TypeOfT,
7822         VisibleTypeConversionsQuals.hasVolatile(),
7823         VisibleTypeConversionsQuals.hasRestrict());
7824     }
7825   }
7826 
7827   // C++ [over.built]p5:
7828   //
7829   //   For every pair (T, VQ), where T is a cv-qualified or
7830   //   cv-unqualified object type, and VQ is either volatile or
7831   //   empty, there exist candidate operator functions of the form
7832   //
7833   //       T*VQ&      operator++(T*VQ&);
7834   //       T*VQ&      operator--(T*VQ&);
7835   //       T*         operator++(T*VQ&, int);
7836   //       T*         operator--(T*VQ&, int);
7837   void addPlusPlusMinusMinusPointerOverloads() {
7838     for (BuiltinCandidateTypeSet::iterator
7839               Ptr = CandidateTypes[0].pointer_begin(),
7840            PtrEnd = CandidateTypes[0].pointer_end();
7841          Ptr != PtrEnd; ++Ptr) {
7842       // Skip pointer types that aren't pointers to object types.
7843       if (!(*Ptr)->getPointeeType()->isObjectType())
7844         continue;
7845 
7846       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7847         (!(*Ptr).isVolatileQualified() &&
7848          VisibleTypeConversionsQuals.hasVolatile()),
7849         (!(*Ptr).isRestrictQualified() &&
7850          VisibleTypeConversionsQuals.hasRestrict()));
7851     }
7852   }
7853 
7854   // C++ [over.built]p6:
7855   //   For every cv-qualified or cv-unqualified object type T, there
7856   //   exist candidate operator functions of the form
7857   //
7858   //       T&         operator*(T*);
7859   //
7860   // C++ [over.built]p7:
7861   //   For every function type T that does not have cv-qualifiers or a
7862   //   ref-qualifier, there exist candidate operator functions of the form
7863   //       T&         operator*(T*);
7864   void addUnaryStarPointerOverloads() {
7865     for (BuiltinCandidateTypeSet::iterator
7866               Ptr = CandidateTypes[0].pointer_begin(),
7867            PtrEnd = CandidateTypes[0].pointer_end();
7868          Ptr != PtrEnd; ++Ptr) {
7869       QualType ParamTy = *Ptr;
7870       QualType PointeeTy = ParamTy->getPointeeType();
7871       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7872         continue;
7873 
7874       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7875         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7876           continue;
7877 
7878       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7879     }
7880   }
7881 
7882   // C++ [over.built]p9:
7883   //  For every promoted arithmetic type T, there exist candidate
7884   //  operator functions of the form
7885   //
7886   //       T         operator+(T);
7887   //       T         operator-(T);
7888   void addUnaryPlusOrMinusArithmeticOverloads() {
7889     if (!HasArithmeticOrEnumeralCandidateType)
7890       return;
7891 
7892     for (unsigned Arith = FirstPromotedArithmeticType;
7893          Arith < LastPromotedArithmeticType; ++Arith) {
7894       QualType ArithTy = ArithmeticTypes[Arith];
7895       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7896     }
7897 
7898     // Extension: We also add these operators for vector types.
7899     for (BuiltinCandidateTypeSet::iterator
7900               Vec = CandidateTypes[0].vector_begin(),
7901            VecEnd = CandidateTypes[0].vector_end();
7902          Vec != VecEnd; ++Vec) {
7903       QualType VecTy = *Vec;
7904       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7905     }
7906   }
7907 
7908   // C++ [over.built]p8:
7909   //   For every type T, there exist candidate operator functions of
7910   //   the form
7911   //
7912   //       T*         operator+(T*);
7913   void addUnaryPlusPointerOverloads() {
7914     for (BuiltinCandidateTypeSet::iterator
7915               Ptr = CandidateTypes[0].pointer_begin(),
7916            PtrEnd = CandidateTypes[0].pointer_end();
7917          Ptr != PtrEnd; ++Ptr) {
7918       QualType ParamTy = *Ptr;
7919       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7920     }
7921   }
7922 
7923   // C++ [over.built]p10:
7924   //   For every promoted integral type T, there exist candidate
7925   //   operator functions of the form
7926   //
7927   //        T         operator~(T);
7928   void addUnaryTildePromotedIntegralOverloads() {
7929     if (!HasArithmeticOrEnumeralCandidateType)
7930       return;
7931 
7932     for (unsigned Int = FirstPromotedIntegralType;
7933          Int < LastPromotedIntegralType; ++Int) {
7934       QualType IntTy = ArithmeticTypes[Int];
7935       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7936     }
7937 
7938     // Extension: We also add this operator for vector types.
7939     for (BuiltinCandidateTypeSet::iterator
7940               Vec = CandidateTypes[0].vector_begin(),
7941            VecEnd = CandidateTypes[0].vector_end();
7942          Vec != VecEnd; ++Vec) {
7943       QualType VecTy = *Vec;
7944       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7945     }
7946   }
7947 
7948   // C++ [over.match.oper]p16:
7949   //   For every pointer to member type T or type std::nullptr_t, there
7950   //   exist candidate operator functions of the form
7951   //
7952   //        bool operator==(T,T);
7953   //        bool operator!=(T,T);
7954   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7955     /// Set of (canonical) types that we've already handled.
7956     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7957 
7958     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7959       for (BuiltinCandidateTypeSet::iterator
7960                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7961              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7962            MemPtr != MemPtrEnd;
7963            ++MemPtr) {
7964         // Don't add the same builtin candidate twice.
7965         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7966           continue;
7967 
7968         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7969         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7970       }
7971 
7972       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7973         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7974         if (AddedTypes.insert(NullPtrTy).second) {
7975           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7976           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7977         }
7978       }
7979     }
7980   }
7981 
7982   // C++ [over.built]p15:
7983   //
7984   //   For every T, where T is an enumeration type or a pointer type,
7985   //   there exist candidate operator functions of the form
7986   //
7987   //        bool       operator<(T, T);
7988   //        bool       operator>(T, T);
7989   //        bool       operator<=(T, T);
7990   //        bool       operator>=(T, T);
7991   //        bool       operator==(T, T);
7992   //        bool       operator!=(T, T);
7993   //           R       operator<=>(T, T)
7994   void addGenericBinaryPointerOrEnumeralOverloads() {
7995     // C++ [over.match.oper]p3:
7996     //   [...]the built-in candidates include all of the candidate operator
7997     //   functions defined in 13.6 that, compared to the given operator, [...]
7998     //   do not have the same parameter-type-list as any non-template non-member
7999     //   candidate.
8000     //
8001     // Note that in practice, this only affects enumeration types because there
8002     // aren't any built-in candidates of record type, and a user-defined operator
8003     // must have an operand of record or enumeration type. Also, the only other
8004     // overloaded operator with enumeration arguments, operator=,
8005     // cannot be overloaded for enumeration types, so this is the only place
8006     // where we must suppress candidates like this.
8007     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8008       UserDefinedBinaryOperators;
8009 
8010     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8011       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8012           CandidateTypes[ArgIdx].enumeration_end()) {
8013         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8014                                          CEnd = CandidateSet.end();
8015              C != CEnd; ++C) {
8016           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8017             continue;
8018 
8019           if (C->Function->isFunctionTemplateSpecialization())
8020             continue;
8021 
8022           QualType FirstParamType =
8023             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8024           QualType SecondParamType =
8025             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8026 
8027           // Skip if either parameter isn't of enumeral type.
8028           if (!FirstParamType->isEnumeralType() ||
8029               !SecondParamType->isEnumeralType())
8030             continue;
8031 
8032           // Add this operator to the set of known user-defined operators.
8033           UserDefinedBinaryOperators.insert(
8034             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8035                            S.Context.getCanonicalType(SecondParamType)));
8036         }
8037       }
8038     }
8039 
8040     /// Set of (canonical) types that we've already handled.
8041     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8042 
8043     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8044       for (BuiltinCandidateTypeSet::iterator
8045                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8046              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8047            Ptr != PtrEnd; ++Ptr) {
8048         // Don't add the same builtin candidate twice.
8049         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8050           continue;
8051 
8052         QualType ParamTypes[2] = { *Ptr, *Ptr };
8053         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8054       }
8055       for (BuiltinCandidateTypeSet::iterator
8056                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8057              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8058            Enum != EnumEnd; ++Enum) {
8059         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8060 
8061         // Don't add the same builtin candidate twice, or if a user defined
8062         // candidate exists.
8063         if (!AddedTypes.insert(CanonType).second ||
8064             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8065                                                             CanonType)))
8066           continue;
8067         QualType ParamTypes[2] = { *Enum, *Enum };
8068         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8069       }
8070     }
8071   }
8072 
8073   // C++ [over.built]p13:
8074   //
8075   //   For every cv-qualified or cv-unqualified object type T
8076   //   there exist candidate operator functions of the form
8077   //
8078   //      T*         operator+(T*, ptrdiff_t);
8079   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8080   //      T*         operator-(T*, ptrdiff_t);
8081   //      T*         operator+(ptrdiff_t, T*);
8082   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8083   //
8084   // C++ [over.built]p14:
8085   //
8086   //   For every T, where T is a pointer to object type, there
8087   //   exist candidate operator functions of the form
8088   //
8089   //      ptrdiff_t  operator-(T, T);
8090   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8091     /// Set of (canonical) types that we've already handled.
8092     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8093 
8094     for (int Arg = 0; Arg < 2; ++Arg) {
8095       QualType AsymmetricParamTypes[2] = {
8096         S.Context.getPointerDiffType(),
8097         S.Context.getPointerDiffType(),
8098       };
8099       for (BuiltinCandidateTypeSet::iterator
8100                 Ptr = CandidateTypes[Arg].pointer_begin(),
8101              PtrEnd = CandidateTypes[Arg].pointer_end();
8102            Ptr != PtrEnd; ++Ptr) {
8103         QualType PointeeTy = (*Ptr)->getPointeeType();
8104         if (!PointeeTy->isObjectType())
8105           continue;
8106 
8107         AsymmetricParamTypes[Arg] = *Ptr;
8108         if (Arg == 0 || Op == OO_Plus) {
8109           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8110           // T* operator+(ptrdiff_t, T*);
8111           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8112         }
8113         if (Op == OO_Minus) {
8114           // ptrdiff_t operator-(T, T);
8115           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8116             continue;
8117 
8118           QualType ParamTypes[2] = { *Ptr, *Ptr };
8119           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8120         }
8121       }
8122     }
8123   }
8124 
8125   // C++ [over.built]p12:
8126   //
8127   //   For every pair of promoted arithmetic types L and R, there
8128   //   exist candidate operator functions of the form
8129   //
8130   //        LR         operator*(L, R);
8131   //        LR         operator/(L, R);
8132   //        LR         operator+(L, R);
8133   //        LR         operator-(L, R);
8134   //        bool       operator<(L, R);
8135   //        bool       operator>(L, R);
8136   //        bool       operator<=(L, R);
8137   //        bool       operator>=(L, R);
8138   //        bool       operator==(L, R);
8139   //        bool       operator!=(L, R);
8140   //
8141   //   where LR is the result of the usual arithmetic conversions
8142   //   between types L and R.
8143   //
8144   // C++ [over.built]p24:
8145   //
8146   //   For every pair of promoted arithmetic types L and R, there exist
8147   //   candidate operator functions of the form
8148   //
8149   //        LR       operator?(bool, L, R);
8150   //
8151   //   where LR is the result of the usual arithmetic conversions
8152   //   between types L and R.
8153   // Our candidates ignore the first parameter.
8154   void addGenericBinaryArithmeticOverloads() {
8155     if (!HasArithmeticOrEnumeralCandidateType)
8156       return;
8157 
8158     for (unsigned Left = FirstPromotedArithmeticType;
8159          Left < LastPromotedArithmeticType; ++Left) {
8160       for (unsigned Right = FirstPromotedArithmeticType;
8161            Right < LastPromotedArithmeticType; ++Right) {
8162         QualType LandR[2] = { ArithmeticTypes[Left],
8163                               ArithmeticTypes[Right] };
8164         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8165       }
8166     }
8167 
8168     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8169     // conditional operator for vector types.
8170     for (BuiltinCandidateTypeSet::iterator
8171               Vec1 = CandidateTypes[0].vector_begin(),
8172            Vec1End = CandidateTypes[0].vector_end();
8173          Vec1 != Vec1End; ++Vec1) {
8174       for (BuiltinCandidateTypeSet::iterator
8175                 Vec2 = CandidateTypes[1].vector_begin(),
8176              Vec2End = CandidateTypes[1].vector_end();
8177            Vec2 != Vec2End; ++Vec2) {
8178         QualType LandR[2] = { *Vec1, *Vec2 };
8179         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8180       }
8181     }
8182   }
8183 
8184   // C++2a [over.built]p14:
8185   //
8186   //   For every integral type T there exists a candidate operator function
8187   //   of the form
8188   //
8189   //        std::strong_ordering operator<=>(T, T)
8190   //
8191   // C++2a [over.built]p15:
8192   //
8193   //   For every pair of floating-point types L and R, there exists a candidate
8194   //   operator function of the form
8195   //
8196   //       std::partial_ordering operator<=>(L, R);
8197   //
8198   // FIXME: The current specification for integral types doesn't play nice with
8199   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8200   // comparisons. Under the current spec this can lead to ambiguity during
8201   // overload resolution. For example:
8202   //
8203   //   enum A : int {a};
8204   //   auto x = (a <=> (long)42);
8205   //
8206   //   error: call is ambiguous for arguments 'A' and 'long'.
8207   //   note: candidate operator<=>(int, int)
8208   //   note: candidate operator<=>(long, long)
8209   //
8210   // To avoid this error, this function deviates from the specification and adds
8211   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8212   // arithmetic types (the same as the generic relational overloads).
8213   //
8214   // For now this function acts as a placeholder.
8215   void addThreeWayArithmeticOverloads() {
8216     addGenericBinaryArithmeticOverloads();
8217   }
8218 
8219   // C++ [over.built]p17:
8220   //
8221   //   For every pair of promoted integral types L and R, there
8222   //   exist candidate operator functions of the form
8223   //
8224   //      LR         operator%(L, R);
8225   //      LR         operator&(L, R);
8226   //      LR         operator^(L, R);
8227   //      LR         operator|(L, R);
8228   //      L          operator<<(L, R);
8229   //      L          operator>>(L, R);
8230   //
8231   //   where LR is the result of the usual arithmetic conversions
8232   //   between types L and R.
8233   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8234     if (!HasArithmeticOrEnumeralCandidateType)
8235       return;
8236 
8237     for (unsigned Left = FirstPromotedIntegralType;
8238          Left < LastPromotedIntegralType; ++Left) {
8239       for (unsigned Right = FirstPromotedIntegralType;
8240            Right < LastPromotedIntegralType; ++Right) {
8241         QualType LandR[2] = { ArithmeticTypes[Left],
8242                               ArithmeticTypes[Right] };
8243         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8244       }
8245     }
8246   }
8247 
8248   // C++ [over.built]p20:
8249   //
8250   //   For every pair (T, VQ), where T is an enumeration or
8251   //   pointer to member type and VQ is either volatile or
8252   //   empty, there exist candidate operator functions of the form
8253   //
8254   //        VQ T&      operator=(VQ T&, T);
8255   void addAssignmentMemberPointerOrEnumeralOverloads() {
8256     /// Set of (canonical) types that we've already handled.
8257     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8258 
8259     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8260       for (BuiltinCandidateTypeSet::iterator
8261                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8262              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8263            Enum != EnumEnd; ++Enum) {
8264         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8265           continue;
8266 
8267         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8268       }
8269 
8270       for (BuiltinCandidateTypeSet::iterator
8271                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8272              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8273            MemPtr != MemPtrEnd; ++MemPtr) {
8274         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8275           continue;
8276 
8277         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8278       }
8279     }
8280   }
8281 
8282   // C++ [over.built]p19:
8283   //
8284   //   For every pair (T, VQ), where T is any type and VQ is either
8285   //   volatile or empty, there exist candidate operator functions
8286   //   of the form
8287   //
8288   //        T*VQ&      operator=(T*VQ&, T*);
8289   //
8290   // C++ [over.built]p21:
8291   //
8292   //   For every pair (T, VQ), where T is a cv-qualified or
8293   //   cv-unqualified object type and VQ is either volatile or
8294   //   empty, there exist candidate operator functions of the form
8295   //
8296   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8297   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8298   void addAssignmentPointerOverloads(bool isEqualOp) {
8299     /// Set of (canonical) types that we've already handled.
8300     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8301 
8302     for (BuiltinCandidateTypeSet::iterator
8303               Ptr = CandidateTypes[0].pointer_begin(),
8304            PtrEnd = CandidateTypes[0].pointer_end();
8305          Ptr != PtrEnd; ++Ptr) {
8306       // If this is operator=, keep track of the builtin candidates we added.
8307       if (isEqualOp)
8308         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8309       else if (!(*Ptr)->getPointeeType()->isObjectType())
8310         continue;
8311 
8312       // non-volatile version
8313       QualType ParamTypes[2] = {
8314         S.Context.getLValueReferenceType(*Ptr),
8315         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8316       };
8317       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8318                             /*IsAssigmentOperator=*/ isEqualOp);
8319 
8320       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8321                           VisibleTypeConversionsQuals.hasVolatile();
8322       if (NeedVolatile) {
8323         // volatile version
8324         ParamTypes[0] =
8325           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8326         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8327                               /*IsAssigmentOperator=*/isEqualOp);
8328       }
8329 
8330       if (!(*Ptr).isRestrictQualified() &&
8331           VisibleTypeConversionsQuals.hasRestrict()) {
8332         // restrict version
8333         ParamTypes[0]
8334           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8335         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8336                               /*IsAssigmentOperator=*/isEqualOp);
8337 
8338         if (NeedVolatile) {
8339           // volatile restrict version
8340           ParamTypes[0]
8341             = S.Context.getLValueReferenceType(
8342                 S.Context.getCVRQualifiedType(*Ptr,
8343                                               (Qualifiers::Volatile |
8344                                                Qualifiers::Restrict)));
8345           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8346                                 /*IsAssigmentOperator=*/isEqualOp);
8347         }
8348       }
8349     }
8350 
8351     if (isEqualOp) {
8352       for (BuiltinCandidateTypeSet::iterator
8353                 Ptr = CandidateTypes[1].pointer_begin(),
8354              PtrEnd = CandidateTypes[1].pointer_end();
8355            Ptr != PtrEnd; ++Ptr) {
8356         // Make sure we don't add the same candidate twice.
8357         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8358           continue;
8359 
8360         QualType ParamTypes[2] = {
8361           S.Context.getLValueReferenceType(*Ptr),
8362           *Ptr,
8363         };
8364 
8365         // non-volatile version
8366         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8367                               /*IsAssigmentOperator=*/true);
8368 
8369         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8370                            VisibleTypeConversionsQuals.hasVolatile();
8371         if (NeedVolatile) {
8372           // volatile version
8373           ParamTypes[0] =
8374             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8375           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8376                                 /*IsAssigmentOperator=*/true);
8377         }
8378 
8379         if (!(*Ptr).isRestrictQualified() &&
8380             VisibleTypeConversionsQuals.hasRestrict()) {
8381           // restrict version
8382           ParamTypes[0]
8383             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8384           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8385                                 /*IsAssigmentOperator=*/true);
8386 
8387           if (NeedVolatile) {
8388             // volatile restrict version
8389             ParamTypes[0]
8390               = S.Context.getLValueReferenceType(
8391                   S.Context.getCVRQualifiedType(*Ptr,
8392                                                 (Qualifiers::Volatile |
8393                                                  Qualifiers::Restrict)));
8394             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8395                                   /*IsAssigmentOperator=*/true);
8396           }
8397         }
8398       }
8399     }
8400   }
8401 
8402   // C++ [over.built]p18:
8403   //
8404   //   For every triple (L, VQ, R), where L is an arithmetic type,
8405   //   VQ is either volatile or empty, and R is a promoted
8406   //   arithmetic type, there exist candidate operator functions of
8407   //   the form
8408   //
8409   //        VQ L&      operator=(VQ L&, R);
8410   //        VQ L&      operator*=(VQ L&, R);
8411   //        VQ L&      operator/=(VQ L&, R);
8412   //        VQ L&      operator+=(VQ L&, R);
8413   //        VQ L&      operator-=(VQ L&, R);
8414   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8415     if (!HasArithmeticOrEnumeralCandidateType)
8416       return;
8417 
8418     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8419       for (unsigned Right = FirstPromotedArithmeticType;
8420            Right < LastPromotedArithmeticType; ++Right) {
8421         QualType ParamTypes[2];
8422         ParamTypes[1] = ArithmeticTypes[Right];
8423 
8424         // Add this built-in operator as a candidate (VQ is empty).
8425         ParamTypes[0] =
8426           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8427         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8428                               /*IsAssigmentOperator=*/isEqualOp);
8429 
8430         // Add this built-in operator as a candidate (VQ is 'volatile').
8431         if (VisibleTypeConversionsQuals.hasVolatile()) {
8432           ParamTypes[0] =
8433             S.Context.getVolatileType(ArithmeticTypes[Left]);
8434           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8435           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8436                                 /*IsAssigmentOperator=*/isEqualOp);
8437         }
8438       }
8439     }
8440 
8441     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8442     for (BuiltinCandidateTypeSet::iterator
8443               Vec1 = CandidateTypes[0].vector_begin(),
8444            Vec1End = CandidateTypes[0].vector_end();
8445          Vec1 != Vec1End; ++Vec1) {
8446       for (BuiltinCandidateTypeSet::iterator
8447                 Vec2 = CandidateTypes[1].vector_begin(),
8448              Vec2End = CandidateTypes[1].vector_end();
8449            Vec2 != Vec2End; ++Vec2) {
8450         QualType ParamTypes[2];
8451         ParamTypes[1] = *Vec2;
8452         // Add this built-in operator as a candidate (VQ is empty).
8453         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8455                               /*IsAssigmentOperator=*/isEqualOp);
8456 
8457         // Add this built-in operator as a candidate (VQ is 'volatile').
8458         if (VisibleTypeConversionsQuals.hasVolatile()) {
8459           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8460           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8461           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8462                                 /*IsAssigmentOperator=*/isEqualOp);
8463         }
8464       }
8465     }
8466   }
8467 
8468   // C++ [over.built]p22:
8469   //
8470   //   For every triple (L, VQ, R), where L is an integral type, VQ
8471   //   is either volatile or empty, and R is a promoted integral
8472   //   type, there exist candidate operator functions of the form
8473   //
8474   //        VQ L&       operator%=(VQ L&, R);
8475   //        VQ L&       operator<<=(VQ L&, R);
8476   //        VQ L&       operator>>=(VQ L&, R);
8477   //        VQ L&       operator&=(VQ L&, R);
8478   //        VQ L&       operator^=(VQ L&, R);
8479   //        VQ L&       operator|=(VQ L&, R);
8480   void addAssignmentIntegralOverloads() {
8481     if (!HasArithmeticOrEnumeralCandidateType)
8482       return;
8483 
8484     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8485       for (unsigned Right = FirstPromotedIntegralType;
8486            Right < LastPromotedIntegralType; ++Right) {
8487         QualType ParamTypes[2];
8488         ParamTypes[1] = ArithmeticTypes[Right];
8489 
8490         // Add this built-in operator as a candidate (VQ is empty).
8491         ParamTypes[0] =
8492           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8493         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8494         if (VisibleTypeConversionsQuals.hasVolatile()) {
8495           // Add this built-in operator as a candidate (VQ is 'volatile').
8496           ParamTypes[0] = ArithmeticTypes[Left];
8497           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8498           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8499           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8500         }
8501       }
8502     }
8503   }
8504 
8505   // C++ [over.operator]p23:
8506   //
8507   //   There also exist candidate operator functions of the form
8508   //
8509   //        bool        operator!(bool);
8510   //        bool        operator&&(bool, bool);
8511   //        bool        operator||(bool, bool);
8512   void addExclaimOverload() {
8513     QualType ParamTy = S.Context.BoolTy;
8514     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8515                           /*IsAssignmentOperator=*/false,
8516                           /*NumContextualBoolArguments=*/1);
8517   }
8518   void addAmpAmpOrPipePipeOverload() {
8519     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8520     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8521                           /*IsAssignmentOperator=*/false,
8522                           /*NumContextualBoolArguments=*/2);
8523   }
8524 
8525   // C++ [over.built]p13:
8526   //
8527   //   For every cv-qualified or cv-unqualified object type T there
8528   //   exist candidate operator functions of the form
8529   //
8530   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8531   //        T&         operator[](T*, ptrdiff_t);
8532   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8533   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8534   //        T&         operator[](ptrdiff_t, T*);
8535   void addSubscriptOverloads() {
8536     for (BuiltinCandidateTypeSet::iterator
8537               Ptr = CandidateTypes[0].pointer_begin(),
8538            PtrEnd = CandidateTypes[0].pointer_end();
8539          Ptr != PtrEnd; ++Ptr) {
8540       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8541       QualType PointeeType = (*Ptr)->getPointeeType();
8542       if (!PointeeType->isObjectType())
8543         continue;
8544 
8545       // T& operator[](T*, ptrdiff_t)
8546       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8547     }
8548 
8549     for (BuiltinCandidateTypeSet::iterator
8550               Ptr = CandidateTypes[1].pointer_begin(),
8551            PtrEnd = CandidateTypes[1].pointer_end();
8552          Ptr != PtrEnd; ++Ptr) {
8553       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8554       QualType PointeeType = (*Ptr)->getPointeeType();
8555       if (!PointeeType->isObjectType())
8556         continue;
8557 
8558       // T& operator[](ptrdiff_t, T*)
8559       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8560     }
8561   }
8562 
8563   // C++ [over.built]p11:
8564   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8565   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8566   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8567   //    there exist candidate operator functions of the form
8568   //
8569   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8570   //
8571   //    where CV12 is the union of CV1 and CV2.
8572   void addArrowStarOverloads() {
8573     for (BuiltinCandidateTypeSet::iterator
8574              Ptr = CandidateTypes[0].pointer_begin(),
8575            PtrEnd = CandidateTypes[0].pointer_end();
8576          Ptr != PtrEnd; ++Ptr) {
8577       QualType C1Ty = (*Ptr);
8578       QualType C1;
8579       QualifierCollector Q1;
8580       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8581       if (!isa<RecordType>(C1))
8582         continue;
8583       // heuristic to reduce number of builtin candidates in the set.
8584       // Add volatile/restrict version only if there are conversions to a
8585       // volatile/restrict type.
8586       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8587         continue;
8588       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8589         continue;
8590       for (BuiltinCandidateTypeSet::iterator
8591                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8592              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8593            MemPtr != MemPtrEnd; ++MemPtr) {
8594         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8595         QualType C2 = QualType(mptr->getClass(), 0);
8596         C2 = C2.getUnqualifiedType();
8597         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8598           break;
8599         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8600         // build CV12 T&
8601         QualType T = mptr->getPointeeType();
8602         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8603             T.isVolatileQualified())
8604           continue;
8605         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8606             T.isRestrictQualified())
8607           continue;
8608         T = Q1.apply(S.Context, T);
8609         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8610       }
8611     }
8612   }
8613 
8614   // Note that we don't consider the first argument, since it has been
8615   // contextually converted to bool long ago. The candidates below are
8616   // therefore added as binary.
8617   //
8618   // C++ [over.built]p25:
8619   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8620   //   enumeration type, there exist candidate operator functions of the form
8621   //
8622   //        T        operator?(bool, T, T);
8623   //
8624   void addConditionalOperatorOverloads() {
8625     /// Set of (canonical) types that we've already handled.
8626     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8627 
8628     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8629       for (BuiltinCandidateTypeSet::iterator
8630                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8631              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8632            Ptr != PtrEnd; ++Ptr) {
8633         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8634           continue;
8635 
8636         QualType ParamTypes[2] = { *Ptr, *Ptr };
8637         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8638       }
8639 
8640       for (BuiltinCandidateTypeSet::iterator
8641                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8642              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8643            MemPtr != MemPtrEnd; ++MemPtr) {
8644         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8645           continue;
8646 
8647         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8648         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8649       }
8650 
8651       if (S.getLangOpts().CPlusPlus11) {
8652         for (BuiltinCandidateTypeSet::iterator
8653                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8654                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8655              Enum != EnumEnd; ++Enum) {
8656           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8657             continue;
8658 
8659           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8660             continue;
8661 
8662           QualType ParamTypes[2] = { *Enum, *Enum };
8663           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8664         }
8665       }
8666     }
8667   }
8668 };
8669 
8670 } // end anonymous namespace
8671 
8672 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8673 /// operator overloads to the candidate set (C++ [over.built]), based
8674 /// on the operator @p Op and the arguments given. For example, if the
8675 /// operator is a binary '+', this routine might add "int
8676 /// operator+(int, int)" to cover integer addition.
8677 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8678                                         SourceLocation OpLoc,
8679                                         ArrayRef<Expr *> Args,
8680                                         OverloadCandidateSet &CandidateSet) {
8681   // Find all of the types that the arguments can convert to, but only
8682   // if the operator we're looking at has built-in operator candidates
8683   // that make use of these types. Also record whether we encounter non-record
8684   // candidate types or either arithmetic or enumeral candidate types.
8685   Qualifiers VisibleTypeConversionsQuals;
8686   VisibleTypeConversionsQuals.addConst();
8687   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8688     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8689 
8690   bool HasNonRecordCandidateType = false;
8691   bool HasArithmeticOrEnumeralCandidateType = false;
8692   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8693   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8694     CandidateTypes.emplace_back(*this);
8695     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8696                                                  OpLoc,
8697                                                  true,
8698                                                  (Op == OO_Exclaim ||
8699                                                   Op == OO_AmpAmp ||
8700                                                   Op == OO_PipePipe),
8701                                                  VisibleTypeConversionsQuals);
8702     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8703         CandidateTypes[ArgIdx].hasNonRecordTypes();
8704     HasArithmeticOrEnumeralCandidateType =
8705         HasArithmeticOrEnumeralCandidateType ||
8706         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8707   }
8708 
8709   // Exit early when no non-record types have been added to the candidate set
8710   // for any of the arguments to the operator.
8711   //
8712   // We can't exit early for !, ||, or &&, since there we have always have
8713   // 'bool' overloads.
8714   if (!HasNonRecordCandidateType &&
8715       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8716     return;
8717 
8718   // Setup an object to manage the common state for building overloads.
8719   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8720                                            VisibleTypeConversionsQuals,
8721                                            HasArithmeticOrEnumeralCandidateType,
8722                                            CandidateTypes, CandidateSet);
8723 
8724   // Dispatch over the operation to add in only those overloads which apply.
8725   switch (Op) {
8726   case OO_None:
8727   case NUM_OVERLOADED_OPERATORS:
8728     llvm_unreachable("Expected an overloaded operator");
8729 
8730   case OO_New:
8731   case OO_Delete:
8732   case OO_Array_New:
8733   case OO_Array_Delete:
8734   case OO_Call:
8735     llvm_unreachable(
8736                     "Special operators don't use AddBuiltinOperatorCandidates");
8737 
8738   case OO_Comma:
8739   case OO_Arrow:
8740   case OO_Coawait:
8741     // C++ [over.match.oper]p3:
8742     //   -- For the operator ',', the unary operator '&', the
8743     //      operator '->', or the operator 'co_await', the
8744     //      built-in candidates set is empty.
8745     break;
8746 
8747   case OO_Plus: // '+' is either unary or binary
8748     if (Args.size() == 1)
8749       OpBuilder.addUnaryPlusPointerOverloads();
8750     LLVM_FALLTHROUGH;
8751 
8752   case OO_Minus: // '-' is either unary or binary
8753     if (Args.size() == 1) {
8754       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8755     } else {
8756       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8757       OpBuilder.addGenericBinaryArithmeticOverloads();
8758     }
8759     break;
8760 
8761   case OO_Star: // '*' is either unary or binary
8762     if (Args.size() == 1)
8763       OpBuilder.addUnaryStarPointerOverloads();
8764     else
8765       OpBuilder.addGenericBinaryArithmeticOverloads();
8766     break;
8767 
8768   case OO_Slash:
8769     OpBuilder.addGenericBinaryArithmeticOverloads();
8770     break;
8771 
8772   case OO_PlusPlus:
8773   case OO_MinusMinus:
8774     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8775     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8776     break;
8777 
8778   case OO_EqualEqual:
8779   case OO_ExclaimEqual:
8780     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8781     LLVM_FALLTHROUGH;
8782 
8783   case OO_Less:
8784   case OO_Greater:
8785   case OO_LessEqual:
8786   case OO_GreaterEqual:
8787     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8788     OpBuilder.addGenericBinaryArithmeticOverloads();
8789     break;
8790 
8791   case OO_Spaceship:
8792     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8793     OpBuilder.addThreeWayArithmeticOverloads();
8794     break;
8795 
8796   case OO_Percent:
8797   case OO_Caret:
8798   case OO_Pipe:
8799   case OO_LessLess:
8800   case OO_GreaterGreater:
8801     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8802     break;
8803 
8804   case OO_Amp: // '&' is either unary or binary
8805     if (Args.size() == 1)
8806       // C++ [over.match.oper]p3:
8807       //   -- For the operator ',', the unary operator '&', or the
8808       //      operator '->', the built-in candidates set is empty.
8809       break;
8810 
8811     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8812     break;
8813 
8814   case OO_Tilde:
8815     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8816     break;
8817 
8818   case OO_Equal:
8819     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8820     LLVM_FALLTHROUGH;
8821 
8822   case OO_PlusEqual:
8823   case OO_MinusEqual:
8824     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8825     LLVM_FALLTHROUGH;
8826 
8827   case OO_StarEqual:
8828   case OO_SlashEqual:
8829     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8830     break;
8831 
8832   case OO_PercentEqual:
8833   case OO_LessLessEqual:
8834   case OO_GreaterGreaterEqual:
8835   case OO_AmpEqual:
8836   case OO_CaretEqual:
8837   case OO_PipeEqual:
8838     OpBuilder.addAssignmentIntegralOverloads();
8839     break;
8840 
8841   case OO_Exclaim:
8842     OpBuilder.addExclaimOverload();
8843     break;
8844 
8845   case OO_AmpAmp:
8846   case OO_PipePipe:
8847     OpBuilder.addAmpAmpOrPipePipeOverload();
8848     break;
8849 
8850   case OO_Subscript:
8851     OpBuilder.addSubscriptOverloads();
8852     break;
8853 
8854   case OO_ArrowStar:
8855     OpBuilder.addArrowStarOverloads();
8856     break;
8857 
8858   case OO_Conditional:
8859     OpBuilder.addConditionalOperatorOverloads();
8860     OpBuilder.addGenericBinaryArithmeticOverloads();
8861     break;
8862   }
8863 }
8864 
8865 /// Add function candidates found via argument-dependent lookup
8866 /// to the set of overloading candidates.
8867 ///
8868 /// This routine performs argument-dependent name lookup based on the
8869 /// given function name (which may also be an operator name) and adds
8870 /// all of the overload candidates found by ADL to the overload
8871 /// candidate set (C++ [basic.lookup.argdep]).
8872 void
8873 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8874                                            SourceLocation Loc,
8875                                            ArrayRef<Expr *> Args,
8876                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8877                                            OverloadCandidateSet& CandidateSet,
8878                                            bool PartialOverloading) {
8879   ADLResult Fns;
8880 
8881   // FIXME: This approach for uniquing ADL results (and removing
8882   // redundant candidates from the set) relies on pointer-equality,
8883   // which means we need to key off the canonical decl.  However,
8884   // always going back to the canonical decl might not get us the
8885   // right set of default arguments.  What default arguments are
8886   // we supposed to consider on ADL candidates, anyway?
8887 
8888   // FIXME: Pass in the explicit template arguments?
8889   ArgumentDependentLookup(Name, Loc, Args, Fns);
8890 
8891   // Erase all of the candidates we already knew about.
8892   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8893                                    CandEnd = CandidateSet.end();
8894        Cand != CandEnd; ++Cand)
8895     if (Cand->Function) {
8896       Fns.erase(Cand->Function);
8897       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8898         Fns.erase(FunTmpl);
8899     }
8900 
8901   // For each of the ADL candidates we found, add it to the overload
8902   // set.
8903   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8904     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8905     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8906       if (ExplicitTemplateArgs)
8907         continue;
8908 
8909       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8910                            PartialOverloading);
8911     } else
8912       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8913                                    FoundDecl, ExplicitTemplateArgs,
8914                                    Args, CandidateSet, PartialOverloading);
8915   }
8916 }
8917 
8918 namespace {
8919 enum class Comparison { Equal, Better, Worse };
8920 }
8921 
8922 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8923 /// overload resolution.
8924 ///
8925 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8926 /// Cand1's first N enable_if attributes have precisely the same conditions as
8927 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8928 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8929 ///
8930 /// Note that you can have a pair of candidates such that Cand1's enable_if
8931 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8932 /// worse than Cand1's.
8933 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8934                                        const FunctionDecl *Cand2) {
8935   // Common case: One (or both) decls don't have enable_if attrs.
8936   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8937   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8938   if (!Cand1Attr || !Cand2Attr) {
8939     if (Cand1Attr == Cand2Attr)
8940       return Comparison::Equal;
8941     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8942   }
8943 
8944   // FIXME: The next several lines are just
8945   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8946   // instead of reverse order which is how they're stored in the AST.
8947   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8948   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8949 
8950   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8951   // has fewer enable_if attributes than Cand2.
8952   if (Cand1Attrs.size() < Cand2Attrs.size())
8953     return Comparison::Worse;
8954 
8955   auto Cand1I = Cand1Attrs.begin();
8956   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8957   for (auto &Cand2A : Cand2Attrs) {
8958     Cand1ID.clear();
8959     Cand2ID.clear();
8960 
8961     auto &Cand1A = *Cand1I++;
8962     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8963     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8964     if (Cand1ID != Cand2ID)
8965       return Comparison::Worse;
8966   }
8967 
8968   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8969 }
8970 
8971 /// isBetterOverloadCandidate - Determines whether the first overload
8972 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8973 bool clang::isBetterOverloadCandidate(
8974     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8975     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8976   // Define viable functions to be better candidates than non-viable
8977   // functions.
8978   if (!Cand2.Viable)
8979     return Cand1.Viable;
8980   else if (!Cand1.Viable)
8981     return false;
8982 
8983   // C++ [over.match.best]p1:
8984   //
8985   //   -- if F is a static member function, ICS1(F) is defined such
8986   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8987   //      any function G, and, symmetrically, ICS1(G) is neither
8988   //      better nor worse than ICS1(F).
8989   unsigned StartArg = 0;
8990   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8991     StartArg = 1;
8992 
8993   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8994     // We don't allow incompatible pointer conversions in C++.
8995     if (!S.getLangOpts().CPlusPlus)
8996       return ICS.isStandard() &&
8997              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8998 
8999     // The only ill-formed conversion we allow in C++ is the string literal to
9000     // char* conversion, which is only considered ill-formed after C++11.
9001     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9002            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9003   };
9004 
9005   // Define functions that don't require ill-formed conversions for a given
9006   // argument to be better candidates than functions that do.
9007   unsigned NumArgs = Cand1.Conversions.size();
9008   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9009   bool HasBetterConversion = false;
9010   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9011     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9012     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9013     if (Cand1Bad != Cand2Bad) {
9014       if (Cand1Bad)
9015         return false;
9016       HasBetterConversion = true;
9017     }
9018   }
9019 
9020   if (HasBetterConversion)
9021     return true;
9022 
9023   // C++ [over.match.best]p1:
9024   //   A viable function F1 is defined to be a better function than another
9025   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9026   //   conversion sequence than ICSi(F2), and then...
9027   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9028     switch (CompareImplicitConversionSequences(S, Loc,
9029                                                Cand1.Conversions[ArgIdx],
9030                                                Cand2.Conversions[ArgIdx])) {
9031     case ImplicitConversionSequence::Better:
9032       // Cand1 has a better conversion sequence.
9033       HasBetterConversion = true;
9034       break;
9035 
9036     case ImplicitConversionSequence::Worse:
9037       // Cand1 can't be better than Cand2.
9038       return false;
9039 
9040     case ImplicitConversionSequence::Indistinguishable:
9041       // Do nothing.
9042       break;
9043     }
9044   }
9045 
9046   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9047   //       ICSj(F2), or, if not that,
9048   if (HasBetterConversion)
9049     return true;
9050 
9051   //   -- the context is an initialization by user-defined conversion
9052   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9053   //      from the return type of F1 to the destination type (i.e.,
9054   //      the type of the entity being initialized) is a better
9055   //      conversion sequence than the standard conversion sequence
9056   //      from the return type of F2 to the destination type.
9057   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9058       Cand1.Function && Cand2.Function &&
9059       isa<CXXConversionDecl>(Cand1.Function) &&
9060       isa<CXXConversionDecl>(Cand2.Function)) {
9061     // First check whether we prefer one of the conversion functions over the
9062     // other. This only distinguishes the results in non-standard, extension
9063     // cases such as the conversion from a lambda closure type to a function
9064     // pointer or block.
9065     ImplicitConversionSequence::CompareKind Result =
9066         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9067     if (Result == ImplicitConversionSequence::Indistinguishable)
9068       Result = CompareStandardConversionSequences(S, Loc,
9069                                                   Cand1.FinalConversion,
9070                                                   Cand2.FinalConversion);
9071 
9072     if (Result != ImplicitConversionSequence::Indistinguishable)
9073       return Result == ImplicitConversionSequence::Better;
9074 
9075     // FIXME: Compare kind of reference binding if conversion functions
9076     // convert to a reference type used in direct reference binding, per
9077     // C++14 [over.match.best]p1 section 2 bullet 3.
9078   }
9079 
9080   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9081   // as combined with the resolution to CWG issue 243.
9082   //
9083   // When the context is initialization by constructor ([over.match.ctor] or
9084   // either phase of [over.match.list]), a constructor is preferred over
9085   // a conversion function.
9086   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9087       Cand1.Function && Cand2.Function &&
9088       isa<CXXConstructorDecl>(Cand1.Function) !=
9089           isa<CXXConstructorDecl>(Cand2.Function))
9090     return isa<CXXConstructorDecl>(Cand1.Function);
9091 
9092   //    -- F1 is a non-template function and F2 is a function template
9093   //       specialization, or, if not that,
9094   bool Cand1IsSpecialization = Cand1.Function &&
9095                                Cand1.Function->getPrimaryTemplate();
9096   bool Cand2IsSpecialization = Cand2.Function &&
9097                                Cand2.Function->getPrimaryTemplate();
9098   if (Cand1IsSpecialization != Cand2IsSpecialization)
9099     return Cand2IsSpecialization;
9100 
9101   //   -- F1 and F2 are function template specializations, and the function
9102   //      template for F1 is more specialized than the template for F2
9103   //      according to the partial ordering rules described in 14.5.5.2, or,
9104   //      if not that,
9105   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9106     if (FunctionTemplateDecl *BetterTemplate
9107           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9108                                          Cand2.Function->getPrimaryTemplate(),
9109                                          Loc,
9110                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9111                                                              : TPOC_Call,
9112                                          Cand1.ExplicitCallArguments,
9113                                          Cand2.ExplicitCallArguments))
9114       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9115   }
9116 
9117   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9118   // A derived-class constructor beats an (inherited) base class constructor.
9119   bool Cand1IsInherited =
9120       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9121   bool Cand2IsInherited =
9122       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9123   if (Cand1IsInherited != Cand2IsInherited)
9124     return Cand2IsInherited;
9125   else if (Cand1IsInherited) {
9126     assert(Cand2IsInherited);
9127     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9128     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9129     if (Cand1Class->isDerivedFrom(Cand2Class))
9130       return true;
9131     if (Cand2Class->isDerivedFrom(Cand1Class))
9132       return false;
9133     // Inherited from sibling base classes: still ambiguous.
9134   }
9135 
9136   // Check C++17 tie-breakers for deduction guides.
9137   {
9138     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9139     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9140     if (Guide1 && Guide2) {
9141       //  -- F1 is generated from a deduction-guide and F2 is not
9142       if (Guide1->isImplicit() != Guide2->isImplicit())
9143         return Guide2->isImplicit();
9144 
9145       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9146       if (Guide1->isCopyDeductionCandidate())
9147         return true;
9148     }
9149   }
9150 
9151   // Check for enable_if value-based overload resolution.
9152   if (Cand1.Function && Cand2.Function) {
9153     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9154     if (Cmp != Comparison::Equal)
9155       return Cmp == Comparison::Better;
9156   }
9157 
9158   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9159     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9160     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9161            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9162   }
9163 
9164   bool HasPS1 = Cand1.Function != nullptr &&
9165                 functionHasPassObjectSizeParams(Cand1.Function);
9166   bool HasPS2 = Cand2.Function != nullptr &&
9167                 functionHasPassObjectSizeParams(Cand2.Function);
9168   return HasPS1 != HasPS2 && HasPS1;
9169 }
9170 
9171 /// Determine whether two declarations are "equivalent" for the purposes of
9172 /// name lookup and overload resolution. This applies when the same internal/no
9173 /// linkage entity is defined by two modules (probably by textually including
9174 /// the same header). In such a case, we don't consider the declarations to
9175 /// declare the same entity, but we also don't want lookups with both
9176 /// declarations visible to be ambiguous in some cases (this happens when using
9177 /// a modularized libstdc++).
9178 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9179                                                   const NamedDecl *B) {
9180   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9181   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9182   if (!VA || !VB)
9183     return false;
9184 
9185   // The declarations must be declaring the same name as an internal linkage
9186   // entity in different modules.
9187   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9188           VB->getDeclContext()->getRedeclContext()) ||
9189       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9190           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9191       VA->isExternallyVisible() || VB->isExternallyVisible())
9192     return false;
9193 
9194   // Check that the declarations appear to be equivalent.
9195   //
9196   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9197   // For constants and functions, we should check the initializer or body is
9198   // the same. For non-constant variables, we shouldn't allow it at all.
9199   if (Context.hasSameType(VA->getType(), VB->getType()))
9200     return true;
9201 
9202   // Enum constants within unnamed enumerations will have different types, but
9203   // may still be similar enough to be interchangeable for our purposes.
9204   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9205     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9206       // Only handle anonymous enums. If the enumerations were named and
9207       // equivalent, they would have been merged to the same type.
9208       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9209       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9210       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9211           !Context.hasSameType(EnumA->getIntegerType(),
9212                                EnumB->getIntegerType()))
9213         return false;
9214       // Allow this only if the value is the same for both enumerators.
9215       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9216     }
9217   }
9218 
9219   // Nothing else is sufficiently similar.
9220   return false;
9221 }
9222 
9223 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9224     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9225   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9226 
9227   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9228   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9229       << !M << (M ? M->getFullModuleName() : "");
9230 
9231   for (auto *E : Equiv) {
9232     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9233     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9234         << !M << (M ? M->getFullModuleName() : "");
9235   }
9236 }
9237 
9238 /// Computes the best viable function (C++ 13.3.3)
9239 /// within an overload candidate set.
9240 ///
9241 /// \param Loc The location of the function name (or operator symbol) for
9242 /// which overload resolution occurs.
9243 ///
9244 /// \param Best If overload resolution was successful or found a deleted
9245 /// function, \p Best points to the candidate function found.
9246 ///
9247 /// \returns The result of overload resolution.
9248 OverloadingResult
9249 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9250                                          iterator &Best) {
9251   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9252   std::transform(begin(), end(), std::back_inserter(Candidates),
9253                  [](OverloadCandidate &Cand) { return &Cand; });
9254 
9255   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9256   // are accepted by both clang and NVCC. However, during a particular
9257   // compilation mode only one call variant is viable. We need to
9258   // exclude non-viable overload candidates from consideration based
9259   // only on their host/device attributes. Specifically, if one
9260   // candidate call is WrongSide and the other is SameSide, we ignore
9261   // the WrongSide candidate.
9262   if (S.getLangOpts().CUDA) {
9263     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9264     bool ContainsSameSideCandidate =
9265         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9266           return Cand->Function &&
9267                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9268                      Sema::CFP_SameSide;
9269         });
9270     if (ContainsSameSideCandidate) {
9271       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9272         return Cand->Function &&
9273                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9274                    Sema::CFP_WrongSide;
9275       };
9276       llvm::erase_if(Candidates, IsWrongSideCandidate);
9277     }
9278   }
9279 
9280   // Find the best viable function.
9281   Best = end();
9282   for (auto *Cand : Candidates)
9283     if (Cand->Viable)
9284       if (Best == end() ||
9285           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9286         Best = Cand;
9287 
9288   // If we didn't find any viable functions, abort.
9289   if (Best == end())
9290     return OR_No_Viable_Function;
9291 
9292   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9293 
9294   // Make sure that this function is better than every other viable
9295   // function. If not, we have an ambiguity.
9296   for (auto *Cand : Candidates) {
9297     if (Cand->Viable && Cand != Best &&
9298         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9299       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9300                                                    Cand->Function)) {
9301         EquivalentCands.push_back(Cand->Function);
9302         continue;
9303       }
9304 
9305       Best = end();
9306       return OR_Ambiguous;
9307     }
9308   }
9309 
9310   // Best is the best viable function.
9311   if (Best->Function &&
9312       (Best->Function->isDeleted() ||
9313        S.isFunctionConsideredUnavailable(Best->Function)))
9314     return OR_Deleted;
9315 
9316   if (!EquivalentCands.empty())
9317     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9318                                                     EquivalentCands);
9319 
9320   return OR_Success;
9321 }
9322 
9323 namespace {
9324 
9325 enum OverloadCandidateKind {
9326   oc_function,
9327   oc_method,
9328   oc_constructor,
9329   oc_function_template,
9330   oc_method_template,
9331   oc_constructor_template,
9332   oc_implicit_default_constructor,
9333   oc_implicit_copy_constructor,
9334   oc_implicit_move_constructor,
9335   oc_implicit_copy_assignment,
9336   oc_implicit_move_assignment,
9337   oc_inherited_constructor,
9338   oc_inherited_constructor_template
9339 };
9340 
9341 static OverloadCandidateKind
9342 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9343                           std::string &Description) {
9344   bool isTemplate = false;
9345 
9346   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9347     isTemplate = true;
9348     Description = S.getTemplateArgumentBindingsText(
9349       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9350   }
9351 
9352   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9353     if (!Ctor->isImplicit()) {
9354       if (isa<ConstructorUsingShadowDecl>(Found))
9355         return isTemplate ? oc_inherited_constructor_template
9356                           : oc_inherited_constructor;
9357       else
9358         return isTemplate ? oc_constructor_template : oc_constructor;
9359     }
9360 
9361     if (Ctor->isDefaultConstructor())
9362       return oc_implicit_default_constructor;
9363 
9364     if (Ctor->isMoveConstructor())
9365       return oc_implicit_move_constructor;
9366 
9367     assert(Ctor->isCopyConstructor() &&
9368            "unexpected sort of implicit constructor");
9369     return oc_implicit_copy_constructor;
9370   }
9371 
9372   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9373     // This actually gets spelled 'candidate function' for now, but
9374     // it doesn't hurt to split it out.
9375     if (!Meth->isImplicit())
9376       return isTemplate ? oc_method_template : oc_method;
9377 
9378     if (Meth->isMoveAssignmentOperator())
9379       return oc_implicit_move_assignment;
9380 
9381     if (Meth->isCopyAssignmentOperator())
9382       return oc_implicit_copy_assignment;
9383 
9384     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9385     return oc_method;
9386   }
9387 
9388   return isTemplate ? oc_function_template : oc_function;
9389 }
9390 
9391 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9392   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9393   // set.
9394   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9395     S.Diag(FoundDecl->getLocation(),
9396            diag::note_ovl_candidate_inherited_constructor)
9397       << Shadow->getNominatedBaseClass();
9398 }
9399 
9400 } // end anonymous namespace
9401 
9402 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9403                                     const FunctionDecl *FD) {
9404   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9405     bool AlwaysTrue;
9406     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9407       return false;
9408     if (!AlwaysTrue)
9409       return false;
9410   }
9411   return true;
9412 }
9413 
9414 /// Returns true if we can take the address of the function.
9415 ///
9416 /// \param Complain - If true, we'll emit a diagnostic
9417 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9418 ///   we in overload resolution?
9419 /// \param Loc - The location of the statement we're complaining about. Ignored
9420 ///   if we're not complaining, or if we're in overload resolution.
9421 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9422                                               bool Complain,
9423                                               bool InOverloadResolution,
9424                                               SourceLocation Loc) {
9425   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9426     if (Complain) {
9427       if (InOverloadResolution)
9428         S.Diag(FD->getLocStart(),
9429                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9430       else
9431         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9432     }
9433     return false;
9434   }
9435 
9436   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9437     return P->hasAttr<PassObjectSizeAttr>();
9438   });
9439   if (I == FD->param_end())
9440     return true;
9441 
9442   if (Complain) {
9443     // Add one to ParamNo because it's user-facing
9444     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9445     if (InOverloadResolution)
9446       S.Diag(FD->getLocation(),
9447              diag::note_ovl_candidate_has_pass_object_size_params)
9448           << ParamNo;
9449     else
9450       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9451           << FD << ParamNo;
9452   }
9453   return false;
9454 }
9455 
9456 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9457                                                const FunctionDecl *FD) {
9458   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9459                                            /*InOverloadResolution=*/true,
9460                                            /*Loc=*/SourceLocation());
9461 }
9462 
9463 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9464                                              bool Complain,
9465                                              SourceLocation Loc) {
9466   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9467                                              /*InOverloadResolution=*/false,
9468                                              Loc);
9469 }
9470 
9471 // Notes the location of an overload candidate.
9472 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9473                                  QualType DestType, bool TakingAddress) {
9474   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9475     return;
9476   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9477     return;
9478 
9479   std::string FnDesc;
9480   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9481   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9482                              << (unsigned) K << Fn << FnDesc;
9483 
9484   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9485   Diag(Fn->getLocation(), PD);
9486   MaybeEmitInheritedConstructorNote(*this, Found);
9487 }
9488 
9489 // Notes the location of all overload candidates designated through
9490 // OverloadedExpr
9491 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9492                                      bool TakingAddress) {
9493   assert(OverloadedExpr->getType() == Context.OverloadTy);
9494 
9495   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9496   OverloadExpr *OvlExpr = Ovl.Expression;
9497 
9498   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9499                             IEnd = OvlExpr->decls_end();
9500        I != IEnd; ++I) {
9501     if (FunctionTemplateDecl *FunTmpl =
9502                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9503       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9504                             TakingAddress);
9505     } else if (FunctionDecl *Fun
9506                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9507       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9508     }
9509   }
9510 }
9511 
9512 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9513 /// "lead" diagnostic; it will be given two arguments, the source and
9514 /// target types of the conversion.
9515 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9516                                  Sema &S,
9517                                  SourceLocation CaretLoc,
9518                                  const PartialDiagnostic &PDiag) const {
9519   S.Diag(CaretLoc, PDiag)
9520     << Ambiguous.getFromType() << Ambiguous.getToType();
9521   // FIXME: The note limiting machinery is borrowed from
9522   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9523   // refactoring here.
9524   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9525   unsigned CandsShown = 0;
9526   AmbiguousConversionSequence::const_iterator I, E;
9527   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9528     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9529       break;
9530     ++CandsShown;
9531     S.NoteOverloadCandidate(I->first, I->second);
9532   }
9533   if (I != E)
9534     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9535 }
9536 
9537 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9538                                   unsigned I, bool TakingCandidateAddress) {
9539   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9540   assert(Conv.isBad());
9541   assert(Cand->Function && "for now, candidate must be a function");
9542   FunctionDecl *Fn = Cand->Function;
9543 
9544   // There's a conversion slot for the object argument if this is a
9545   // non-constructor method.  Note that 'I' corresponds the
9546   // conversion-slot index.
9547   bool isObjectArgument = false;
9548   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9549     if (I == 0)
9550       isObjectArgument = true;
9551     else
9552       I--;
9553   }
9554 
9555   std::string FnDesc;
9556   OverloadCandidateKind FnKind =
9557       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9558 
9559   Expr *FromExpr = Conv.Bad.FromExpr;
9560   QualType FromTy = Conv.Bad.getFromType();
9561   QualType ToTy = Conv.Bad.getToType();
9562 
9563   if (FromTy == S.Context.OverloadTy) {
9564     assert(FromExpr && "overload set argument came from implicit argument?");
9565     Expr *E = FromExpr->IgnoreParens();
9566     if (isa<UnaryOperator>(E))
9567       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9568     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9569 
9570     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9571       << (unsigned) FnKind << FnDesc
9572       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9573       << ToTy << Name << I+1;
9574     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9575     return;
9576   }
9577 
9578   // Do some hand-waving analysis to see if the non-viability is due
9579   // to a qualifier mismatch.
9580   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9581   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9582   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9583     CToTy = RT->getPointeeType();
9584   else {
9585     // TODO: detect and diagnose the full richness of const mismatches.
9586     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9587       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9588         CFromTy = FromPT->getPointeeType();
9589         CToTy = ToPT->getPointeeType();
9590       }
9591   }
9592 
9593   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9594       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9595     Qualifiers FromQs = CFromTy.getQualifiers();
9596     Qualifiers ToQs = CToTy.getQualifiers();
9597 
9598     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9599       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9600         << (unsigned) FnKind << FnDesc
9601         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9602         << FromTy
9603         << FromQs.getAddressSpaceAttributePrintValue()
9604         << ToQs.getAddressSpaceAttributePrintValue()
9605         << (unsigned) isObjectArgument << I+1;
9606       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9607       return;
9608     }
9609 
9610     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9611       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9612         << (unsigned) FnKind << FnDesc
9613         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9614         << FromTy
9615         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9616         << (unsigned) isObjectArgument << I+1;
9617       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9618       return;
9619     }
9620 
9621     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9622       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9623       << (unsigned) FnKind << FnDesc
9624       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9625       << FromTy
9626       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9627       << (unsigned) isObjectArgument << I+1;
9628       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9629       return;
9630     }
9631 
9632     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9633       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9634         << (unsigned) FnKind << FnDesc
9635         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9636         << FromTy << FromQs.hasUnaligned() << I+1;
9637       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9638       return;
9639     }
9640 
9641     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9642     assert(CVR && "unexpected qualifiers mismatch");
9643 
9644     if (isObjectArgument) {
9645       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9646         << (unsigned) FnKind << FnDesc
9647         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9648         << FromTy << (CVR - 1);
9649     } else {
9650       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9651         << (unsigned) FnKind << FnDesc
9652         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9653         << FromTy << (CVR - 1) << I+1;
9654     }
9655     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9656     return;
9657   }
9658 
9659   // Special diagnostic for failure to convert an initializer list, since
9660   // telling the user that it has type void is not useful.
9661   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9662     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9663       << (unsigned) FnKind << FnDesc
9664       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9665       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9666     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9667     return;
9668   }
9669 
9670   // Diagnose references or pointers to incomplete types differently,
9671   // since it's far from impossible that the incompleteness triggered
9672   // the failure.
9673   QualType TempFromTy = FromTy.getNonReferenceType();
9674   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9675     TempFromTy = PTy->getPointeeType();
9676   if (TempFromTy->isIncompleteType()) {
9677     // Emit the generic diagnostic and, optionally, add the hints to it.
9678     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9679       << (unsigned) FnKind << FnDesc
9680       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9681       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9682       << (unsigned) (Cand->Fix.Kind);
9683 
9684     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9685     return;
9686   }
9687 
9688   // Diagnose base -> derived pointer conversions.
9689   unsigned BaseToDerivedConversion = 0;
9690   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9691     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9692       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9693                                                FromPtrTy->getPointeeType()) &&
9694           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9695           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9696           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9697                           FromPtrTy->getPointeeType()))
9698         BaseToDerivedConversion = 1;
9699     }
9700   } else if (const ObjCObjectPointerType *FromPtrTy
9701                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9702     if (const ObjCObjectPointerType *ToPtrTy
9703                                         = ToTy->getAs<ObjCObjectPointerType>())
9704       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9705         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9706           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9707                                                 FromPtrTy->getPointeeType()) &&
9708               FromIface->isSuperClassOf(ToIface))
9709             BaseToDerivedConversion = 2;
9710   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9711     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9712         !FromTy->isIncompleteType() &&
9713         !ToRefTy->getPointeeType()->isIncompleteType() &&
9714         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9715       BaseToDerivedConversion = 3;
9716     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9717                ToTy.getNonReferenceType().getCanonicalType() ==
9718                FromTy.getNonReferenceType().getCanonicalType()) {
9719       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9720         << (unsigned) FnKind << FnDesc
9721         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9722         << (unsigned) isObjectArgument << I + 1;
9723       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9724       return;
9725     }
9726   }
9727 
9728   if (BaseToDerivedConversion) {
9729     S.Diag(Fn->getLocation(),
9730            diag::note_ovl_candidate_bad_base_to_derived_conv)
9731       << (unsigned) FnKind << FnDesc
9732       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9733       << (BaseToDerivedConversion - 1)
9734       << FromTy << ToTy << I+1;
9735     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9736     return;
9737   }
9738 
9739   if (isa<ObjCObjectPointerType>(CFromTy) &&
9740       isa<PointerType>(CToTy)) {
9741       Qualifiers FromQs = CFromTy.getQualifiers();
9742       Qualifiers ToQs = CToTy.getQualifiers();
9743       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9744         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9745         << (unsigned) FnKind << FnDesc
9746         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9747         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9748         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9749         return;
9750       }
9751   }
9752 
9753   if (TakingCandidateAddress &&
9754       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9755     return;
9756 
9757   // Emit the generic diagnostic and, optionally, add the hints to it.
9758   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9759   FDiag << (unsigned) FnKind << FnDesc
9760     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9761     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9762     << (unsigned) (Cand->Fix.Kind);
9763 
9764   // If we can fix the conversion, suggest the FixIts.
9765   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9766        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9767     FDiag << *HI;
9768   S.Diag(Fn->getLocation(), FDiag);
9769 
9770   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9771 }
9772 
9773 /// Additional arity mismatch diagnosis specific to a function overload
9774 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9775 /// over a candidate in any candidate set.
9776 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9777                                unsigned NumArgs) {
9778   FunctionDecl *Fn = Cand->Function;
9779   unsigned MinParams = Fn->getMinRequiredArguments();
9780 
9781   // With invalid overloaded operators, it's possible that we think we
9782   // have an arity mismatch when in fact it looks like we have the
9783   // right number of arguments, because only overloaded operators have
9784   // the weird behavior of overloading member and non-member functions.
9785   // Just don't report anything.
9786   if (Fn->isInvalidDecl() &&
9787       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9788     return true;
9789 
9790   if (NumArgs < MinParams) {
9791     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9792            (Cand->FailureKind == ovl_fail_bad_deduction &&
9793             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9794   } else {
9795     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9796            (Cand->FailureKind == ovl_fail_bad_deduction &&
9797             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9798   }
9799 
9800   return false;
9801 }
9802 
9803 /// General arity mismatch diagnosis over a candidate in a candidate set.
9804 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9805                                   unsigned NumFormalArgs) {
9806   assert(isa<FunctionDecl>(D) &&
9807       "The templated declaration should at least be a function"
9808       " when diagnosing bad template argument deduction due to too many"
9809       " or too few arguments");
9810 
9811   FunctionDecl *Fn = cast<FunctionDecl>(D);
9812 
9813   // TODO: treat calls to a missing default constructor as a special case
9814   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9815   unsigned MinParams = Fn->getMinRequiredArguments();
9816 
9817   // at least / at most / exactly
9818   unsigned mode, modeCount;
9819   if (NumFormalArgs < MinParams) {
9820     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9821         FnTy->isTemplateVariadic())
9822       mode = 0; // "at least"
9823     else
9824       mode = 2; // "exactly"
9825     modeCount = MinParams;
9826   } else {
9827     if (MinParams != FnTy->getNumParams())
9828       mode = 1; // "at most"
9829     else
9830       mode = 2; // "exactly"
9831     modeCount = FnTy->getNumParams();
9832   }
9833 
9834   std::string Description;
9835   OverloadCandidateKind FnKind =
9836       ClassifyOverloadCandidate(S, Found, Fn, Description);
9837 
9838   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9839     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9840       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9841       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9842   else
9843     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9844       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9845       << mode << modeCount << NumFormalArgs;
9846   MaybeEmitInheritedConstructorNote(S, Found);
9847 }
9848 
9849 /// Arity mismatch diagnosis specific to a function overload candidate.
9850 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9851                                   unsigned NumFormalArgs) {
9852   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9853     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9854 }
9855 
9856 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9857   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9858     return TD;
9859   llvm_unreachable("Unsupported: Getting the described template declaration"
9860                    " for bad deduction diagnosis");
9861 }
9862 
9863 /// Diagnose a failed template-argument deduction.
9864 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9865                                  DeductionFailureInfo &DeductionFailure,
9866                                  unsigned NumArgs,
9867                                  bool TakingCandidateAddress) {
9868   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9869   NamedDecl *ParamD;
9870   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9871   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9872   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9873   switch (DeductionFailure.Result) {
9874   case Sema::TDK_Success:
9875     llvm_unreachable("TDK_success while diagnosing bad deduction");
9876 
9877   case Sema::TDK_Incomplete: {
9878     assert(ParamD && "no parameter found for incomplete deduction result");
9879     S.Diag(Templated->getLocation(),
9880            diag::note_ovl_candidate_incomplete_deduction)
9881         << ParamD->getDeclName();
9882     MaybeEmitInheritedConstructorNote(S, Found);
9883     return;
9884   }
9885 
9886   case Sema::TDK_Underqualified: {
9887     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9888     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9889 
9890     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9891 
9892     // Param will have been canonicalized, but it should just be a
9893     // qualified version of ParamD, so move the qualifiers to that.
9894     QualifierCollector Qs;
9895     Qs.strip(Param);
9896     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9897     assert(S.Context.hasSameType(Param, NonCanonParam));
9898 
9899     // Arg has also been canonicalized, but there's nothing we can do
9900     // about that.  It also doesn't matter as much, because it won't
9901     // have any template parameters in it (because deduction isn't
9902     // done on dependent types).
9903     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9904 
9905     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9906         << ParamD->getDeclName() << Arg << NonCanonParam;
9907     MaybeEmitInheritedConstructorNote(S, Found);
9908     return;
9909   }
9910 
9911   case Sema::TDK_Inconsistent: {
9912     assert(ParamD && "no parameter found for inconsistent deduction result");
9913     int which = 0;
9914     if (isa<TemplateTypeParmDecl>(ParamD))
9915       which = 0;
9916     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9917       // Deduction might have failed because we deduced arguments of two
9918       // different types for a non-type template parameter.
9919       // FIXME: Use a different TDK value for this.
9920       QualType T1 =
9921           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9922       QualType T2 =
9923           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9924       if (!S.Context.hasSameType(T1, T2)) {
9925         S.Diag(Templated->getLocation(),
9926                diag::note_ovl_candidate_inconsistent_deduction_types)
9927           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9928           << *DeductionFailure.getSecondArg() << T2;
9929         MaybeEmitInheritedConstructorNote(S, Found);
9930         return;
9931       }
9932 
9933       which = 1;
9934     } else {
9935       which = 2;
9936     }
9937 
9938     S.Diag(Templated->getLocation(),
9939            diag::note_ovl_candidate_inconsistent_deduction)
9940         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9941         << *DeductionFailure.getSecondArg();
9942     MaybeEmitInheritedConstructorNote(S, Found);
9943     return;
9944   }
9945 
9946   case Sema::TDK_InvalidExplicitArguments:
9947     assert(ParamD && "no parameter found for invalid explicit arguments");
9948     if (ParamD->getDeclName())
9949       S.Diag(Templated->getLocation(),
9950              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9951           << ParamD->getDeclName();
9952     else {
9953       int index = 0;
9954       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9955         index = TTP->getIndex();
9956       else if (NonTypeTemplateParmDecl *NTTP
9957                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9958         index = NTTP->getIndex();
9959       else
9960         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9961       S.Diag(Templated->getLocation(),
9962              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9963           << (index + 1);
9964     }
9965     MaybeEmitInheritedConstructorNote(S, Found);
9966     return;
9967 
9968   case Sema::TDK_TooManyArguments:
9969   case Sema::TDK_TooFewArguments:
9970     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9971     return;
9972 
9973   case Sema::TDK_InstantiationDepth:
9974     S.Diag(Templated->getLocation(),
9975            diag::note_ovl_candidate_instantiation_depth);
9976     MaybeEmitInheritedConstructorNote(S, Found);
9977     return;
9978 
9979   case Sema::TDK_SubstitutionFailure: {
9980     // Format the template argument list into the argument string.
9981     SmallString<128> TemplateArgString;
9982     if (TemplateArgumentList *Args =
9983             DeductionFailure.getTemplateArgumentList()) {
9984       TemplateArgString = " ";
9985       TemplateArgString += S.getTemplateArgumentBindingsText(
9986           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9987     }
9988 
9989     // If this candidate was disabled by enable_if, say so.
9990     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9991     if (PDiag && PDiag->second.getDiagID() ==
9992           diag::err_typename_nested_not_found_enable_if) {
9993       // FIXME: Use the source range of the condition, and the fully-qualified
9994       //        name of the enable_if template. These are both present in PDiag.
9995       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9996         << "'enable_if'" << TemplateArgString;
9997       return;
9998     }
9999 
10000     // We found a specific requirement that disabled the enable_if.
10001     if (PDiag && PDiag->second.getDiagID() ==
10002         diag::err_typename_nested_not_found_requirement) {
10003       S.Diag(Templated->getLocation(),
10004              diag::note_ovl_candidate_disabled_by_requirement)
10005         << PDiag->second.getStringArg(0) << TemplateArgString;
10006       return;
10007     }
10008 
10009     // Format the SFINAE diagnostic into the argument string.
10010     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10011     //        formatted message in another diagnostic.
10012     SmallString<128> SFINAEArgString;
10013     SourceRange R;
10014     if (PDiag) {
10015       SFINAEArgString = ": ";
10016       R = SourceRange(PDiag->first, PDiag->first);
10017       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10018     }
10019 
10020     S.Diag(Templated->getLocation(),
10021            diag::note_ovl_candidate_substitution_failure)
10022         << TemplateArgString << SFINAEArgString << R;
10023     MaybeEmitInheritedConstructorNote(S, Found);
10024     return;
10025   }
10026 
10027   case Sema::TDK_DeducedMismatch:
10028   case Sema::TDK_DeducedMismatchNested: {
10029     // Format the template argument list into the argument string.
10030     SmallString<128> TemplateArgString;
10031     if (TemplateArgumentList *Args =
10032             DeductionFailure.getTemplateArgumentList()) {
10033       TemplateArgString = " ";
10034       TemplateArgString += S.getTemplateArgumentBindingsText(
10035           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10036     }
10037 
10038     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10039         << (*DeductionFailure.getCallArgIndex() + 1)
10040         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10041         << TemplateArgString
10042         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10043     break;
10044   }
10045 
10046   case Sema::TDK_NonDeducedMismatch: {
10047     // FIXME: Provide a source location to indicate what we couldn't match.
10048     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10049     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10050     if (FirstTA.getKind() == TemplateArgument::Template &&
10051         SecondTA.getKind() == TemplateArgument::Template) {
10052       TemplateName FirstTN = FirstTA.getAsTemplate();
10053       TemplateName SecondTN = SecondTA.getAsTemplate();
10054       if (FirstTN.getKind() == TemplateName::Template &&
10055           SecondTN.getKind() == TemplateName::Template) {
10056         if (FirstTN.getAsTemplateDecl()->getName() ==
10057             SecondTN.getAsTemplateDecl()->getName()) {
10058           // FIXME: This fixes a bad diagnostic where both templates are named
10059           // the same.  This particular case is a bit difficult since:
10060           // 1) It is passed as a string to the diagnostic printer.
10061           // 2) The diagnostic printer only attempts to find a better
10062           //    name for types, not decls.
10063           // Ideally, this should folded into the diagnostic printer.
10064           S.Diag(Templated->getLocation(),
10065                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10066               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10067           return;
10068         }
10069       }
10070     }
10071 
10072     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10073         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10074       return;
10075 
10076     // FIXME: For generic lambda parameters, check if the function is a lambda
10077     // call operator, and if so, emit a prettier and more informative
10078     // diagnostic that mentions 'auto' and lambda in addition to
10079     // (or instead of?) the canonical template type parameters.
10080     S.Diag(Templated->getLocation(),
10081            diag::note_ovl_candidate_non_deduced_mismatch)
10082         << FirstTA << SecondTA;
10083     return;
10084   }
10085   // TODO: diagnose these individually, then kill off
10086   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10087   case Sema::TDK_MiscellaneousDeductionFailure:
10088     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10089     MaybeEmitInheritedConstructorNote(S, Found);
10090     return;
10091   case Sema::TDK_CUDATargetMismatch:
10092     S.Diag(Templated->getLocation(),
10093            diag::note_cuda_ovl_candidate_target_mismatch);
10094     return;
10095   }
10096 }
10097 
10098 /// Diagnose a failed template-argument deduction, for function calls.
10099 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10100                                  unsigned NumArgs,
10101                                  bool TakingCandidateAddress) {
10102   unsigned TDK = Cand->DeductionFailure.Result;
10103   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10104     if (CheckArityMismatch(S, Cand, NumArgs))
10105       return;
10106   }
10107   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10108                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10109 }
10110 
10111 /// CUDA: diagnose an invalid call across targets.
10112 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10113   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10114   FunctionDecl *Callee = Cand->Function;
10115 
10116   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10117                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10118 
10119   std::string FnDesc;
10120   OverloadCandidateKind FnKind =
10121       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10122 
10123   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10124       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10125 
10126   // This could be an implicit constructor for which we could not infer the
10127   // target due to a collsion. Diagnose that case.
10128   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10129   if (Meth != nullptr && Meth->isImplicit()) {
10130     CXXRecordDecl *ParentClass = Meth->getParent();
10131     Sema::CXXSpecialMember CSM;
10132 
10133     switch (FnKind) {
10134     default:
10135       return;
10136     case oc_implicit_default_constructor:
10137       CSM = Sema::CXXDefaultConstructor;
10138       break;
10139     case oc_implicit_copy_constructor:
10140       CSM = Sema::CXXCopyConstructor;
10141       break;
10142     case oc_implicit_move_constructor:
10143       CSM = Sema::CXXMoveConstructor;
10144       break;
10145     case oc_implicit_copy_assignment:
10146       CSM = Sema::CXXCopyAssignment;
10147       break;
10148     case oc_implicit_move_assignment:
10149       CSM = Sema::CXXMoveAssignment;
10150       break;
10151     };
10152 
10153     bool ConstRHS = false;
10154     if (Meth->getNumParams()) {
10155       if (const ReferenceType *RT =
10156               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10157         ConstRHS = RT->getPointeeType().isConstQualified();
10158       }
10159     }
10160 
10161     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10162                                               /* ConstRHS */ ConstRHS,
10163                                               /* Diagnose */ true);
10164   }
10165 }
10166 
10167 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10168   FunctionDecl *Callee = Cand->Function;
10169   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10170 
10171   S.Diag(Callee->getLocation(),
10172          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10173       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10174 }
10175 
10176 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10177   FunctionDecl *Callee = Cand->Function;
10178 
10179   S.Diag(Callee->getLocation(),
10180          diag::note_ovl_candidate_disabled_by_extension);
10181 }
10182 
10183 /// Generates a 'note' diagnostic for an overload candidate.  We've
10184 /// already generated a primary error at the call site.
10185 ///
10186 /// It really does need to be a single diagnostic with its caret
10187 /// pointed at the candidate declaration.  Yes, this creates some
10188 /// major challenges of technical writing.  Yes, this makes pointing
10189 /// out problems with specific arguments quite awkward.  It's still
10190 /// better than generating twenty screens of text for every failed
10191 /// overload.
10192 ///
10193 /// It would be great to be able to express per-candidate problems
10194 /// more richly for those diagnostic clients that cared, but we'd
10195 /// still have to be just as careful with the default diagnostics.
10196 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10197                                   unsigned NumArgs,
10198                                   bool TakingCandidateAddress) {
10199   FunctionDecl *Fn = Cand->Function;
10200 
10201   // Note deleted candidates, but only if they're viable.
10202   if (Cand->Viable) {
10203     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10204       std::string FnDesc;
10205       OverloadCandidateKind FnKind =
10206         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10207 
10208       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10209         << FnKind << FnDesc
10210         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10211       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10212       return;
10213     }
10214 
10215     // We don't really have anything else to say about viable candidates.
10216     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10217     return;
10218   }
10219 
10220   switch (Cand->FailureKind) {
10221   case ovl_fail_too_many_arguments:
10222   case ovl_fail_too_few_arguments:
10223     return DiagnoseArityMismatch(S, Cand, NumArgs);
10224 
10225   case ovl_fail_bad_deduction:
10226     return DiagnoseBadDeduction(S, Cand, NumArgs,
10227                                 TakingCandidateAddress);
10228 
10229   case ovl_fail_illegal_constructor: {
10230     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10231       << (Fn->getPrimaryTemplate() ? 1 : 0);
10232     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10233     return;
10234   }
10235 
10236   case ovl_fail_trivial_conversion:
10237   case ovl_fail_bad_final_conversion:
10238   case ovl_fail_final_conversion_not_exact:
10239     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10240 
10241   case ovl_fail_bad_conversion: {
10242     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10243     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10244       if (Cand->Conversions[I].isBad())
10245         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10246 
10247     // FIXME: this currently happens when we're called from SemaInit
10248     // when user-conversion overload fails.  Figure out how to handle
10249     // those conditions and diagnose them well.
10250     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10251   }
10252 
10253   case ovl_fail_bad_target:
10254     return DiagnoseBadTarget(S, Cand);
10255 
10256   case ovl_fail_enable_if:
10257     return DiagnoseFailedEnableIfAttr(S, Cand);
10258 
10259   case ovl_fail_ext_disabled:
10260     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10261 
10262   case ovl_fail_inhctor_slice:
10263     // It's generally not interesting to note copy/move constructors here.
10264     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10265       return;
10266     S.Diag(Fn->getLocation(),
10267            diag::note_ovl_candidate_inherited_constructor_slice)
10268       << (Fn->getPrimaryTemplate() ? 1 : 0)
10269       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10270     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10271     return;
10272 
10273   case ovl_fail_addr_not_available: {
10274     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10275     (void)Available;
10276     assert(!Available);
10277     break;
10278   }
10279   case ovl_non_default_multiversion_function:
10280     // Do nothing, these should simply be ignored.
10281     break;
10282   }
10283 }
10284 
10285 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10286   // Desugar the type of the surrogate down to a function type,
10287   // retaining as many typedefs as possible while still showing
10288   // the function type (and, therefore, its parameter types).
10289   QualType FnType = Cand->Surrogate->getConversionType();
10290   bool isLValueReference = false;
10291   bool isRValueReference = false;
10292   bool isPointer = false;
10293   if (const LValueReferenceType *FnTypeRef =
10294         FnType->getAs<LValueReferenceType>()) {
10295     FnType = FnTypeRef->getPointeeType();
10296     isLValueReference = true;
10297   } else if (const RValueReferenceType *FnTypeRef =
10298                FnType->getAs<RValueReferenceType>()) {
10299     FnType = FnTypeRef->getPointeeType();
10300     isRValueReference = true;
10301   }
10302   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10303     FnType = FnTypePtr->getPointeeType();
10304     isPointer = true;
10305   }
10306   // Desugar down to a function type.
10307   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10308   // Reconstruct the pointer/reference as appropriate.
10309   if (isPointer) FnType = S.Context.getPointerType(FnType);
10310   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10311   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10312 
10313   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10314     << FnType;
10315 }
10316 
10317 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10318                                          SourceLocation OpLoc,
10319                                          OverloadCandidate *Cand) {
10320   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10321   std::string TypeStr("operator");
10322   TypeStr += Opc;
10323   TypeStr += "(";
10324   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10325   if (Cand->Conversions.size() == 1) {
10326     TypeStr += ")";
10327     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10328   } else {
10329     TypeStr += ", ";
10330     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10331     TypeStr += ")";
10332     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10333   }
10334 }
10335 
10336 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10337                                          OverloadCandidate *Cand) {
10338   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10339     if (ICS.isBad()) break; // all meaningless after first invalid
10340     if (!ICS.isAmbiguous()) continue;
10341 
10342     ICS.DiagnoseAmbiguousConversion(
10343         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10344   }
10345 }
10346 
10347 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10348   if (Cand->Function)
10349     return Cand->Function->getLocation();
10350   if (Cand->IsSurrogate)
10351     return Cand->Surrogate->getLocation();
10352   return SourceLocation();
10353 }
10354 
10355 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10356   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10357   case Sema::TDK_Success:
10358   case Sema::TDK_NonDependentConversionFailure:
10359     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10360 
10361   case Sema::TDK_Invalid:
10362   case Sema::TDK_Incomplete:
10363     return 1;
10364 
10365   case Sema::TDK_Underqualified:
10366   case Sema::TDK_Inconsistent:
10367     return 2;
10368 
10369   case Sema::TDK_SubstitutionFailure:
10370   case Sema::TDK_DeducedMismatch:
10371   case Sema::TDK_DeducedMismatchNested:
10372   case Sema::TDK_NonDeducedMismatch:
10373   case Sema::TDK_MiscellaneousDeductionFailure:
10374   case Sema::TDK_CUDATargetMismatch:
10375     return 3;
10376 
10377   case Sema::TDK_InstantiationDepth:
10378     return 4;
10379 
10380   case Sema::TDK_InvalidExplicitArguments:
10381     return 5;
10382 
10383   case Sema::TDK_TooManyArguments:
10384   case Sema::TDK_TooFewArguments:
10385     return 6;
10386   }
10387   llvm_unreachable("Unhandled deduction result");
10388 }
10389 
10390 namespace {
10391 struct CompareOverloadCandidatesForDisplay {
10392   Sema &S;
10393   SourceLocation Loc;
10394   size_t NumArgs;
10395   OverloadCandidateSet::CandidateSetKind CSK;
10396 
10397   CompareOverloadCandidatesForDisplay(
10398       Sema &S, SourceLocation Loc, size_t NArgs,
10399       OverloadCandidateSet::CandidateSetKind CSK)
10400       : S(S), NumArgs(NArgs), CSK(CSK) {}
10401 
10402   bool operator()(const OverloadCandidate *L,
10403                   const OverloadCandidate *R) {
10404     // Fast-path this check.
10405     if (L == R) return false;
10406 
10407     // Order first by viability.
10408     if (L->Viable) {
10409       if (!R->Viable) return true;
10410 
10411       // TODO: introduce a tri-valued comparison for overload
10412       // candidates.  Would be more worthwhile if we had a sort
10413       // that could exploit it.
10414       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10415         return true;
10416       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10417         return false;
10418     } else if (R->Viable)
10419       return false;
10420 
10421     assert(L->Viable == R->Viable);
10422 
10423     // Criteria by which we can sort non-viable candidates:
10424     if (!L->Viable) {
10425       // 1. Arity mismatches come after other candidates.
10426       if (L->FailureKind == ovl_fail_too_many_arguments ||
10427           L->FailureKind == ovl_fail_too_few_arguments) {
10428         if (R->FailureKind == ovl_fail_too_many_arguments ||
10429             R->FailureKind == ovl_fail_too_few_arguments) {
10430           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10431           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10432           if (LDist == RDist) {
10433             if (L->FailureKind == R->FailureKind)
10434               // Sort non-surrogates before surrogates.
10435               return !L->IsSurrogate && R->IsSurrogate;
10436             // Sort candidates requiring fewer parameters than there were
10437             // arguments given after candidates requiring more parameters
10438             // than there were arguments given.
10439             return L->FailureKind == ovl_fail_too_many_arguments;
10440           }
10441           return LDist < RDist;
10442         }
10443         return false;
10444       }
10445       if (R->FailureKind == ovl_fail_too_many_arguments ||
10446           R->FailureKind == ovl_fail_too_few_arguments)
10447         return true;
10448 
10449       // 2. Bad conversions come first and are ordered by the number
10450       // of bad conversions and quality of good conversions.
10451       if (L->FailureKind == ovl_fail_bad_conversion) {
10452         if (R->FailureKind != ovl_fail_bad_conversion)
10453           return true;
10454 
10455         // The conversion that can be fixed with a smaller number of changes,
10456         // comes first.
10457         unsigned numLFixes = L->Fix.NumConversionsFixed;
10458         unsigned numRFixes = R->Fix.NumConversionsFixed;
10459         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10460         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10461         if (numLFixes != numRFixes) {
10462           return numLFixes < numRFixes;
10463         }
10464 
10465         // If there's any ordering between the defined conversions...
10466         // FIXME: this might not be transitive.
10467         assert(L->Conversions.size() == R->Conversions.size());
10468 
10469         int leftBetter = 0;
10470         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10471         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10472           switch (CompareImplicitConversionSequences(S, Loc,
10473                                                      L->Conversions[I],
10474                                                      R->Conversions[I])) {
10475           case ImplicitConversionSequence::Better:
10476             leftBetter++;
10477             break;
10478 
10479           case ImplicitConversionSequence::Worse:
10480             leftBetter--;
10481             break;
10482 
10483           case ImplicitConversionSequence::Indistinguishable:
10484             break;
10485           }
10486         }
10487         if (leftBetter > 0) return true;
10488         if (leftBetter < 0) return false;
10489 
10490       } else if (R->FailureKind == ovl_fail_bad_conversion)
10491         return false;
10492 
10493       if (L->FailureKind == ovl_fail_bad_deduction) {
10494         if (R->FailureKind != ovl_fail_bad_deduction)
10495           return true;
10496 
10497         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10498           return RankDeductionFailure(L->DeductionFailure)
10499                < RankDeductionFailure(R->DeductionFailure);
10500       } else if (R->FailureKind == ovl_fail_bad_deduction)
10501         return false;
10502 
10503       // TODO: others?
10504     }
10505 
10506     // Sort everything else by location.
10507     SourceLocation LLoc = GetLocationForCandidate(L);
10508     SourceLocation RLoc = GetLocationForCandidate(R);
10509 
10510     // Put candidates without locations (e.g. builtins) at the end.
10511     if (LLoc.isInvalid()) return false;
10512     if (RLoc.isInvalid()) return true;
10513 
10514     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10515   }
10516 };
10517 }
10518 
10519 /// CompleteNonViableCandidate - Normally, overload resolution only
10520 /// computes up to the first bad conversion. Produces the FixIt set if
10521 /// possible.
10522 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10523                                        ArrayRef<Expr *> Args) {
10524   assert(!Cand->Viable);
10525 
10526   // Don't do anything on failures other than bad conversion.
10527   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10528 
10529   // We only want the FixIts if all the arguments can be corrected.
10530   bool Unfixable = false;
10531   // Use a implicit copy initialization to check conversion fixes.
10532   Cand->Fix.setConversionChecker(TryCopyInitialization);
10533 
10534   // Attempt to fix the bad conversion.
10535   unsigned ConvCount = Cand->Conversions.size();
10536   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10537        ++ConvIdx) {
10538     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10539     if (Cand->Conversions[ConvIdx].isInitialized() &&
10540         Cand->Conversions[ConvIdx].isBad()) {
10541       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10542       break;
10543     }
10544   }
10545 
10546   // FIXME: this should probably be preserved from the overload
10547   // operation somehow.
10548   bool SuppressUserConversions = false;
10549 
10550   unsigned ConvIdx = 0;
10551   ArrayRef<QualType> ParamTypes;
10552 
10553   if (Cand->IsSurrogate) {
10554     QualType ConvType
10555       = Cand->Surrogate->getConversionType().getNonReferenceType();
10556     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10557       ConvType = ConvPtrType->getPointeeType();
10558     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10559     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10560     ConvIdx = 1;
10561   } else if (Cand->Function) {
10562     ParamTypes =
10563         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10564     if (isa<CXXMethodDecl>(Cand->Function) &&
10565         !isa<CXXConstructorDecl>(Cand->Function)) {
10566       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10567       ConvIdx = 1;
10568     }
10569   } else {
10570     // Builtin operator.
10571     assert(ConvCount <= 3);
10572     ParamTypes = Cand->BuiltinParamTypes;
10573   }
10574 
10575   // Fill in the rest of the conversions.
10576   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10577     if (Cand->Conversions[ConvIdx].isInitialized()) {
10578       // We've already checked this conversion.
10579     } else if (ArgIdx < ParamTypes.size()) {
10580       if (ParamTypes[ArgIdx]->isDependentType())
10581         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10582             Args[ArgIdx]->getType());
10583       else {
10584         Cand->Conversions[ConvIdx] =
10585             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10586                                   SuppressUserConversions,
10587                                   /*InOverloadResolution=*/true,
10588                                   /*AllowObjCWritebackConversion=*/
10589                                   S.getLangOpts().ObjCAutoRefCount);
10590         // Store the FixIt in the candidate if it exists.
10591         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10592           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10593       }
10594     } else
10595       Cand->Conversions[ConvIdx].setEllipsis();
10596   }
10597 }
10598 
10599 /// When overload resolution fails, prints diagnostic messages containing the
10600 /// candidates in the candidate set.
10601 void OverloadCandidateSet::NoteCandidates(
10602     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10603     StringRef Opc, SourceLocation OpLoc,
10604     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10605   // Sort the candidates by viability and position.  Sorting directly would
10606   // be prohibitive, so we make a set of pointers and sort those.
10607   SmallVector<OverloadCandidate*, 32> Cands;
10608   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10609   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10610     if (!Filter(*Cand))
10611       continue;
10612     if (Cand->Viable)
10613       Cands.push_back(Cand);
10614     else if (OCD == OCD_AllCandidates) {
10615       CompleteNonViableCandidate(S, Cand, Args);
10616       if (Cand->Function || Cand->IsSurrogate)
10617         Cands.push_back(Cand);
10618       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10619       // want to list every possible builtin candidate.
10620     }
10621   }
10622 
10623   std::stable_sort(Cands.begin(), Cands.end(),
10624             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10625 
10626   bool ReportedAmbiguousConversions = false;
10627 
10628   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10629   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10630   unsigned CandsShown = 0;
10631   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10632     OverloadCandidate *Cand = *I;
10633 
10634     // Set an arbitrary limit on the number of candidate functions we'll spam
10635     // the user with.  FIXME: This limit should depend on details of the
10636     // candidate list.
10637     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10638       break;
10639     }
10640     ++CandsShown;
10641 
10642     if (Cand->Function)
10643       NoteFunctionCandidate(S, Cand, Args.size(),
10644                             /*TakingCandidateAddress=*/false);
10645     else if (Cand->IsSurrogate)
10646       NoteSurrogateCandidate(S, Cand);
10647     else {
10648       assert(Cand->Viable &&
10649              "Non-viable built-in candidates are not added to Cands.");
10650       // Generally we only see ambiguities including viable builtin
10651       // operators if overload resolution got screwed up by an
10652       // ambiguous user-defined conversion.
10653       //
10654       // FIXME: It's quite possible for different conversions to see
10655       // different ambiguities, though.
10656       if (!ReportedAmbiguousConversions) {
10657         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10658         ReportedAmbiguousConversions = true;
10659       }
10660 
10661       // If this is a viable builtin, print it.
10662       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10663     }
10664   }
10665 
10666   if (I != E)
10667     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10668 }
10669 
10670 static SourceLocation
10671 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10672   return Cand->Specialization ? Cand->Specialization->getLocation()
10673                               : SourceLocation();
10674 }
10675 
10676 namespace {
10677 struct CompareTemplateSpecCandidatesForDisplay {
10678   Sema &S;
10679   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10680 
10681   bool operator()(const TemplateSpecCandidate *L,
10682                   const TemplateSpecCandidate *R) {
10683     // Fast-path this check.
10684     if (L == R)
10685       return false;
10686 
10687     // Assuming that both candidates are not matches...
10688 
10689     // Sort by the ranking of deduction failures.
10690     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10691       return RankDeductionFailure(L->DeductionFailure) <
10692              RankDeductionFailure(R->DeductionFailure);
10693 
10694     // Sort everything else by location.
10695     SourceLocation LLoc = GetLocationForCandidate(L);
10696     SourceLocation RLoc = GetLocationForCandidate(R);
10697 
10698     // Put candidates without locations (e.g. builtins) at the end.
10699     if (LLoc.isInvalid())
10700       return false;
10701     if (RLoc.isInvalid())
10702       return true;
10703 
10704     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10705   }
10706 };
10707 }
10708 
10709 /// Diagnose a template argument deduction failure.
10710 /// We are treating these failures as overload failures due to bad
10711 /// deductions.
10712 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10713                                                  bool ForTakingAddress) {
10714   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10715                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10716 }
10717 
10718 void TemplateSpecCandidateSet::destroyCandidates() {
10719   for (iterator i = begin(), e = end(); i != e; ++i) {
10720     i->DeductionFailure.Destroy();
10721   }
10722 }
10723 
10724 void TemplateSpecCandidateSet::clear() {
10725   destroyCandidates();
10726   Candidates.clear();
10727 }
10728 
10729 /// NoteCandidates - When no template specialization match is found, prints
10730 /// diagnostic messages containing the non-matching specializations that form
10731 /// the candidate set.
10732 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10733 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10734 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10735   // Sort the candidates by position (assuming no candidate is a match).
10736   // Sorting directly would be prohibitive, so we make a set of pointers
10737   // and sort those.
10738   SmallVector<TemplateSpecCandidate *, 32> Cands;
10739   Cands.reserve(size());
10740   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10741     if (Cand->Specialization)
10742       Cands.push_back(Cand);
10743     // Otherwise, this is a non-matching builtin candidate.  We do not,
10744     // in general, want to list every possible builtin candidate.
10745   }
10746 
10747   llvm::sort(Cands.begin(), Cands.end(),
10748              CompareTemplateSpecCandidatesForDisplay(S));
10749 
10750   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10751   // for generalization purposes (?).
10752   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10753 
10754   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10755   unsigned CandsShown = 0;
10756   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10757     TemplateSpecCandidate *Cand = *I;
10758 
10759     // Set an arbitrary limit on the number of candidates we'll spam
10760     // the user with.  FIXME: This limit should depend on details of the
10761     // candidate list.
10762     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10763       break;
10764     ++CandsShown;
10765 
10766     assert(Cand->Specialization &&
10767            "Non-matching built-in candidates are not added to Cands.");
10768     Cand->NoteDeductionFailure(S, ForTakingAddress);
10769   }
10770 
10771   if (I != E)
10772     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10773 }
10774 
10775 // [PossiblyAFunctionType]  -->   [Return]
10776 // NonFunctionType --> NonFunctionType
10777 // R (A) --> R(A)
10778 // R (*)(A) --> R (A)
10779 // R (&)(A) --> R (A)
10780 // R (S::*)(A) --> R (A)
10781 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10782   QualType Ret = PossiblyAFunctionType;
10783   if (const PointerType *ToTypePtr =
10784     PossiblyAFunctionType->getAs<PointerType>())
10785     Ret = ToTypePtr->getPointeeType();
10786   else if (const ReferenceType *ToTypeRef =
10787     PossiblyAFunctionType->getAs<ReferenceType>())
10788     Ret = ToTypeRef->getPointeeType();
10789   else if (const MemberPointerType *MemTypePtr =
10790     PossiblyAFunctionType->getAs<MemberPointerType>())
10791     Ret = MemTypePtr->getPointeeType();
10792   Ret =
10793     Context.getCanonicalType(Ret).getUnqualifiedType();
10794   return Ret;
10795 }
10796 
10797 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10798                                  bool Complain = true) {
10799   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10800       S.DeduceReturnType(FD, Loc, Complain))
10801     return true;
10802 
10803   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10804   if (S.getLangOpts().CPlusPlus17 &&
10805       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10806       !S.ResolveExceptionSpec(Loc, FPT))
10807     return true;
10808 
10809   return false;
10810 }
10811 
10812 namespace {
10813 // A helper class to help with address of function resolution
10814 // - allows us to avoid passing around all those ugly parameters
10815 class AddressOfFunctionResolver {
10816   Sema& S;
10817   Expr* SourceExpr;
10818   const QualType& TargetType;
10819   QualType TargetFunctionType; // Extracted function type from target type
10820 
10821   bool Complain;
10822   //DeclAccessPair& ResultFunctionAccessPair;
10823   ASTContext& Context;
10824 
10825   bool TargetTypeIsNonStaticMemberFunction;
10826   bool FoundNonTemplateFunction;
10827   bool StaticMemberFunctionFromBoundPointer;
10828   bool HasComplained;
10829 
10830   OverloadExpr::FindResult OvlExprInfo;
10831   OverloadExpr *OvlExpr;
10832   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10833   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10834   TemplateSpecCandidateSet FailedCandidates;
10835 
10836 public:
10837   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10838                             const QualType &TargetType, bool Complain)
10839       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10840         Complain(Complain), Context(S.getASTContext()),
10841         TargetTypeIsNonStaticMemberFunction(
10842             !!TargetType->getAs<MemberPointerType>()),
10843         FoundNonTemplateFunction(false),
10844         StaticMemberFunctionFromBoundPointer(false),
10845         HasComplained(false),
10846         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10847         OvlExpr(OvlExprInfo.Expression),
10848         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10849     ExtractUnqualifiedFunctionTypeFromTargetType();
10850 
10851     if (TargetFunctionType->isFunctionType()) {
10852       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10853         if (!UME->isImplicitAccess() &&
10854             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10855           StaticMemberFunctionFromBoundPointer = true;
10856     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10857       DeclAccessPair dap;
10858       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10859               OvlExpr, false, &dap)) {
10860         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10861           if (!Method->isStatic()) {
10862             // If the target type is a non-function type and the function found
10863             // is a non-static member function, pretend as if that was the
10864             // target, it's the only possible type to end up with.
10865             TargetTypeIsNonStaticMemberFunction = true;
10866 
10867             // And skip adding the function if its not in the proper form.
10868             // We'll diagnose this due to an empty set of functions.
10869             if (!OvlExprInfo.HasFormOfMemberPointer)
10870               return;
10871           }
10872 
10873         Matches.push_back(std::make_pair(dap, Fn));
10874       }
10875       return;
10876     }
10877 
10878     if (OvlExpr->hasExplicitTemplateArgs())
10879       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10880 
10881     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10882       // C++ [over.over]p4:
10883       //   If more than one function is selected, [...]
10884       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10885         if (FoundNonTemplateFunction)
10886           EliminateAllTemplateMatches();
10887         else
10888           EliminateAllExceptMostSpecializedTemplate();
10889       }
10890     }
10891 
10892     if (S.getLangOpts().CUDA && Matches.size() > 1)
10893       EliminateSuboptimalCudaMatches();
10894   }
10895 
10896   bool hasComplained() const { return HasComplained; }
10897 
10898 private:
10899   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10900     QualType Discard;
10901     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10902            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10903   }
10904 
10905   /// \return true if A is considered a better overload candidate for the
10906   /// desired type than B.
10907   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10908     // If A doesn't have exactly the correct type, we don't want to classify it
10909     // as "better" than anything else. This way, the user is required to
10910     // disambiguate for us if there are multiple candidates and no exact match.
10911     return candidateHasExactlyCorrectType(A) &&
10912            (!candidateHasExactlyCorrectType(B) ||
10913             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10914   }
10915 
10916   /// \return true if we were able to eliminate all but one overload candidate,
10917   /// false otherwise.
10918   bool eliminiateSuboptimalOverloadCandidates() {
10919     // Same algorithm as overload resolution -- one pass to pick the "best",
10920     // another pass to be sure that nothing is better than the best.
10921     auto Best = Matches.begin();
10922     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10923       if (isBetterCandidate(I->second, Best->second))
10924         Best = I;
10925 
10926     const FunctionDecl *BestFn = Best->second;
10927     auto IsBestOrInferiorToBest = [this, BestFn](
10928         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10929       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10930     };
10931 
10932     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10933     // option, so we can potentially give the user a better error
10934     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10935       return false;
10936     Matches[0] = *Best;
10937     Matches.resize(1);
10938     return true;
10939   }
10940 
10941   bool isTargetTypeAFunction() const {
10942     return TargetFunctionType->isFunctionType();
10943   }
10944 
10945   // [ToType]     [Return]
10946 
10947   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10948   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10949   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10950   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10951     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10952   }
10953 
10954   // return true if any matching specializations were found
10955   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10956                                    const DeclAccessPair& CurAccessFunPair) {
10957     if (CXXMethodDecl *Method
10958               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10959       // Skip non-static function templates when converting to pointer, and
10960       // static when converting to member pointer.
10961       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10962         return false;
10963     }
10964     else if (TargetTypeIsNonStaticMemberFunction)
10965       return false;
10966 
10967     // C++ [over.over]p2:
10968     //   If the name is a function template, template argument deduction is
10969     //   done (14.8.2.2), and if the argument deduction succeeds, the
10970     //   resulting template argument list is used to generate a single
10971     //   function template specialization, which is added to the set of
10972     //   overloaded functions considered.
10973     FunctionDecl *Specialization = nullptr;
10974     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10975     if (Sema::TemplateDeductionResult Result
10976           = S.DeduceTemplateArguments(FunctionTemplate,
10977                                       &OvlExplicitTemplateArgs,
10978                                       TargetFunctionType, Specialization,
10979                                       Info, /*IsAddressOfFunction*/true)) {
10980       // Make a note of the failed deduction for diagnostics.
10981       FailedCandidates.addCandidate()
10982           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10983                MakeDeductionFailureInfo(Context, Result, Info));
10984       return false;
10985     }
10986 
10987     // Template argument deduction ensures that we have an exact match or
10988     // compatible pointer-to-function arguments that would be adjusted by ICS.
10989     // This function template specicalization works.
10990     assert(S.isSameOrCompatibleFunctionType(
10991               Context.getCanonicalType(Specialization->getType()),
10992               Context.getCanonicalType(TargetFunctionType)));
10993 
10994     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10995       return false;
10996 
10997     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10998     return true;
10999   }
11000 
11001   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11002                                       const DeclAccessPair& CurAccessFunPair) {
11003     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11004       // Skip non-static functions when converting to pointer, and static
11005       // when converting to member pointer.
11006       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11007         return false;
11008     }
11009     else if (TargetTypeIsNonStaticMemberFunction)
11010       return false;
11011 
11012     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11013       if (S.getLangOpts().CUDA)
11014         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11015           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11016             return false;
11017       if (FunDecl->isMultiVersion()) {
11018         const auto *TA = FunDecl->getAttr<TargetAttr>();
11019         assert(TA && "Multiversioned functions require a target attribute");
11020         if (!TA->isDefaultVersion())
11021           return false;
11022       }
11023 
11024       // If any candidate has a placeholder return type, trigger its deduction
11025       // now.
11026       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11027                                Complain)) {
11028         HasComplained |= Complain;
11029         return false;
11030       }
11031 
11032       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11033         return false;
11034 
11035       // If we're in C, we need to support types that aren't exactly identical.
11036       if (!S.getLangOpts().CPlusPlus ||
11037           candidateHasExactlyCorrectType(FunDecl)) {
11038         Matches.push_back(std::make_pair(
11039             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11040         FoundNonTemplateFunction = true;
11041         return true;
11042       }
11043     }
11044 
11045     return false;
11046   }
11047 
11048   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11049     bool Ret = false;
11050 
11051     // If the overload expression doesn't have the form of a pointer to
11052     // member, don't try to convert it to a pointer-to-member type.
11053     if (IsInvalidFormOfPointerToMemberFunction())
11054       return false;
11055 
11056     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11057                                E = OvlExpr->decls_end();
11058          I != E; ++I) {
11059       // Look through any using declarations to find the underlying function.
11060       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11061 
11062       // C++ [over.over]p3:
11063       //   Non-member functions and static member functions match
11064       //   targets of type "pointer-to-function" or "reference-to-function."
11065       //   Nonstatic member functions match targets of
11066       //   type "pointer-to-member-function."
11067       // Note that according to DR 247, the containing class does not matter.
11068       if (FunctionTemplateDecl *FunctionTemplate
11069                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11070         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11071           Ret = true;
11072       }
11073       // If we have explicit template arguments supplied, skip non-templates.
11074       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11075                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11076         Ret = true;
11077     }
11078     assert(Ret || Matches.empty());
11079     return Ret;
11080   }
11081 
11082   void EliminateAllExceptMostSpecializedTemplate() {
11083     //   [...] and any given function template specialization F1 is
11084     //   eliminated if the set contains a second function template
11085     //   specialization whose function template is more specialized
11086     //   than the function template of F1 according to the partial
11087     //   ordering rules of 14.5.5.2.
11088 
11089     // The algorithm specified above is quadratic. We instead use a
11090     // two-pass algorithm (similar to the one used to identify the
11091     // best viable function in an overload set) that identifies the
11092     // best function template (if it exists).
11093 
11094     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11095     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11096       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11097 
11098     // TODO: It looks like FailedCandidates does not serve much purpose
11099     // here, since the no_viable diagnostic has index 0.
11100     UnresolvedSetIterator Result = S.getMostSpecialized(
11101         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11102         SourceExpr->getLocStart(), S.PDiag(),
11103         S.PDiag(diag::err_addr_ovl_ambiguous)
11104           << Matches[0].second->getDeclName(),
11105         S.PDiag(diag::note_ovl_candidate)
11106           << (unsigned)oc_function_template,
11107         Complain, TargetFunctionType);
11108 
11109     if (Result != MatchesCopy.end()) {
11110       // Make it the first and only element
11111       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11112       Matches[0].second = cast<FunctionDecl>(*Result);
11113       Matches.resize(1);
11114     } else
11115       HasComplained |= Complain;
11116   }
11117 
11118   void EliminateAllTemplateMatches() {
11119     //   [...] any function template specializations in the set are
11120     //   eliminated if the set also contains a non-template function, [...]
11121     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11122       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11123         ++I;
11124       else {
11125         Matches[I] = Matches[--N];
11126         Matches.resize(N);
11127       }
11128     }
11129   }
11130 
11131   void EliminateSuboptimalCudaMatches() {
11132     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11133   }
11134 
11135 public:
11136   void ComplainNoMatchesFound() const {
11137     assert(Matches.empty());
11138     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11139         << OvlExpr->getName() << TargetFunctionType
11140         << OvlExpr->getSourceRange();
11141     if (FailedCandidates.empty())
11142       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11143                                   /*TakingAddress=*/true);
11144     else {
11145       // We have some deduction failure messages. Use them to diagnose
11146       // the function templates, and diagnose the non-template candidates
11147       // normally.
11148       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11149                                  IEnd = OvlExpr->decls_end();
11150            I != IEnd; ++I)
11151         if (FunctionDecl *Fun =
11152                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11153           if (!functionHasPassObjectSizeParams(Fun))
11154             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11155                                     /*TakingAddress=*/true);
11156       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11157     }
11158   }
11159 
11160   bool IsInvalidFormOfPointerToMemberFunction() const {
11161     return TargetTypeIsNonStaticMemberFunction &&
11162       !OvlExprInfo.HasFormOfMemberPointer;
11163   }
11164 
11165   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11166       // TODO: Should we condition this on whether any functions might
11167       // have matched, or is it more appropriate to do that in callers?
11168       // TODO: a fixit wouldn't hurt.
11169       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11170         << TargetType << OvlExpr->getSourceRange();
11171   }
11172 
11173   bool IsStaticMemberFunctionFromBoundPointer() const {
11174     return StaticMemberFunctionFromBoundPointer;
11175   }
11176 
11177   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11178     S.Diag(OvlExpr->getLocStart(),
11179            diag::err_invalid_form_pointer_member_function)
11180       << OvlExpr->getSourceRange();
11181   }
11182 
11183   void ComplainOfInvalidConversion() const {
11184     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11185       << OvlExpr->getName() << TargetType;
11186   }
11187 
11188   void ComplainMultipleMatchesFound() const {
11189     assert(Matches.size() > 1);
11190     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11191       << OvlExpr->getName()
11192       << OvlExpr->getSourceRange();
11193     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11194                                 /*TakingAddress=*/true);
11195   }
11196 
11197   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11198 
11199   int getNumMatches() const { return Matches.size(); }
11200 
11201   FunctionDecl* getMatchingFunctionDecl() const {
11202     if (Matches.size() != 1) return nullptr;
11203     return Matches[0].second;
11204   }
11205 
11206   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11207     if (Matches.size() != 1) return nullptr;
11208     return &Matches[0].first;
11209   }
11210 };
11211 }
11212 
11213 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11214 /// an overloaded function (C++ [over.over]), where @p From is an
11215 /// expression with overloaded function type and @p ToType is the type
11216 /// we're trying to resolve to. For example:
11217 ///
11218 /// @code
11219 /// int f(double);
11220 /// int f(int);
11221 ///
11222 /// int (*pfd)(double) = f; // selects f(double)
11223 /// @endcode
11224 ///
11225 /// This routine returns the resulting FunctionDecl if it could be
11226 /// resolved, and NULL otherwise. When @p Complain is true, this
11227 /// routine will emit diagnostics if there is an error.
11228 FunctionDecl *
11229 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11230                                          QualType TargetType,
11231                                          bool Complain,
11232                                          DeclAccessPair &FoundResult,
11233                                          bool *pHadMultipleCandidates) {
11234   assert(AddressOfExpr->getType() == Context.OverloadTy);
11235 
11236   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11237                                      Complain);
11238   int NumMatches = Resolver.getNumMatches();
11239   FunctionDecl *Fn = nullptr;
11240   bool ShouldComplain = Complain && !Resolver.hasComplained();
11241   if (NumMatches == 0 && ShouldComplain) {
11242     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11243       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11244     else
11245       Resolver.ComplainNoMatchesFound();
11246   }
11247   else if (NumMatches > 1 && ShouldComplain)
11248     Resolver.ComplainMultipleMatchesFound();
11249   else if (NumMatches == 1) {
11250     Fn = Resolver.getMatchingFunctionDecl();
11251     assert(Fn);
11252     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11253       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11254     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11255     if (Complain) {
11256       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11257         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11258       else
11259         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11260     }
11261   }
11262 
11263   if (pHadMultipleCandidates)
11264     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11265   return Fn;
11266 }
11267 
11268 /// Given an expression that refers to an overloaded function, try to
11269 /// resolve that function to a single function that can have its address taken.
11270 /// This will modify `Pair` iff it returns non-null.
11271 ///
11272 /// This routine can only realistically succeed if all but one candidates in the
11273 /// overload set for SrcExpr cannot have their addresses taken.
11274 FunctionDecl *
11275 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11276                                                   DeclAccessPair &Pair) {
11277   OverloadExpr::FindResult R = OverloadExpr::find(E);
11278   OverloadExpr *Ovl = R.Expression;
11279   FunctionDecl *Result = nullptr;
11280   DeclAccessPair DAP;
11281   // Don't use the AddressOfResolver because we're specifically looking for
11282   // cases where we have one overload candidate that lacks
11283   // enable_if/pass_object_size/...
11284   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11285     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11286     if (!FD)
11287       return nullptr;
11288 
11289     if (!checkAddressOfFunctionIsAvailable(FD))
11290       continue;
11291 
11292     // We have more than one result; quit.
11293     if (Result)
11294       return nullptr;
11295     DAP = I.getPair();
11296     Result = FD;
11297   }
11298 
11299   if (Result)
11300     Pair = DAP;
11301   return Result;
11302 }
11303 
11304 /// Given an overloaded function, tries to turn it into a non-overloaded
11305 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11306 /// will perform access checks, diagnose the use of the resultant decl, and, if
11307 /// requested, potentially perform a function-to-pointer decay.
11308 ///
11309 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11310 /// Otherwise, returns true. This may emit diagnostics and return true.
11311 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11312     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11313   Expr *E = SrcExpr.get();
11314   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11315 
11316   DeclAccessPair DAP;
11317   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11318   if (!Found)
11319     return false;
11320 
11321   // Emitting multiple diagnostics for a function that is both inaccessible and
11322   // unavailable is consistent with our behavior elsewhere. So, always check
11323   // for both.
11324   DiagnoseUseOfDecl(Found, E->getExprLoc());
11325   CheckAddressOfMemberAccess(E, DAP);
11326   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11327   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11328     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11329   else
11330     SrcExpr = Fixed;
11331   return true;
11332 }
11333 
11334 /// Given an expression that refers to an overloaded function, try to
11335 /// resolve that overloaded function expression down to a single function.
11336 ///
11337 /// This routine can only resolve template-ids that refer to a single function
11338 /// template, where that template-id refers to a single template whose template
11339 /// arguments are either provided by the template-id or have defaults,
11340 /// as described in C++0x [temp.arg.explicit]p3.
11341 ///
11342 /// If no template-ids are found, no diagnostics are emitted and NULL is
11343 /// returned.
11344 FunctionDecl *
11345 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11346                                                   bool Complain,
11347                                                   DeclAccessPair *FoundResult) {
11348   // C++ [over.over]p1:
11349   //   [...] [Note: any redundant set of parentheses surrounding the
11350   //   overloaded function name is ignored (5.1). ]
11351   // C++ [over.over]p1:
11352   //   [...] The overloaded function name can be preceded by the &
11353   //   operator.
11354 
11355   // If we didn't actually find any template-ids, we're done.
11356   if (!ovl->hasExplicitTemplateArgs())
11357     return nullptr;
11358 
11359   TemplateArgumentListInfo ExplicitTemplateArgs;
11360   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11361   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11362 
11363   // Look through all of the overloaded functions, searching for one
11364   // whose type matches exactly.
11365   FunctionDecl *Matched = nullptr;
11366   for (UnresolvedSetIterator I = ovl->decls_begin(),
11367          E = ovl->decls_end(); I != E; ++I) {
11368     // C++0x [temp.arg.explicit]p3:
11369     //   [...] In contexts where deduction is done and fails, or in contexts
11370     //   where deduction is not done, if a template argument list is
11371     //   specified and it, along with any default template arguments,
11372     //   identifies a single function template specialization, then the
11373     //   template-id is an lvalue for the function template specialization.
11374     FunctionTemplateDecl *FunctionTemplate
11375       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11376 
11377     // C++ [over.over]p2:
11378     //   If the name is a function template, template argument deduction is
11379     //   done (14.8.2.2), and if the argument deduction succeeds, the
11380     //   resulting template argument list is used to generate a single
11381     //   function template specialization, which is added to the set of
11382     //   overloaded functions considered.
11383     FunctionDecl *Specialization = nullptr;
11384     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11385     if (TemplateDeductionResult Result
11386           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11387                                     Specialization, Info,
11388                                     /*IsAddressOfFunction*/true)) {
11389       // Make a note of the failed deduction for diagnostics.
11390       // TODO: Actually use the failed-deduction info?
11391       FailedCandidates.addCandidate()
11392           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11393                MakeDeductionFailureInfo(Context, Result, Info));
11394       continue;
11395     }
11396 
11397     assert(Specialization && "no specialization and no error?");
11398 
11399     // Multiple matches; we can't resolve to a single declaration.
11400     if (Matched) {
11401       if (Complain) {
11402         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11403           << ovl->getName();
11404         NoteAllOverloadCandidates(ovl);
11405       }
11406       return nullptr;
11407     }
11408 
11409     Matched = Specialization;
11410     if (FoundResult) *FoundResult = I.getPair();
11411   }
11412 
11413   if (Matched &&
11414       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11415     return nullptr;
11416 
11417   return Matched;
11418 }
11419 
11420 // Resolve and fix an overloaded expression that can be resolved
11421 // because it identifies a single function template specialization.
11422 //
11423 // Last three arguments should only be supplied if Complain = true
11424 //
11425 // Return true if it was logically possible to so resolve the
11426 // expression, regardless of whether or not it succeeded.  Always
11427 // returns true if 'complain' is set.
11428 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11429                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11430                       bool complain, SourceRange OpRangeForComplaining,
11431                                            QualType DestTypeForComplaining,
11432                                             unsigned DiagIDForComplaining) {
11433   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11434 
11435   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11436 
11437   DeclAccessPair found;
11438   ExprResult SingleFunctionExpression;
11439   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11440                            ovl.Expression, /*complain*/ false, &found)) {
11441     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11442       SrcExpr = ExprError();
11443       return true;
11444     }
11445 
11446     // It is only correct to resolve to an instance method if we're
11447     // resolving a form that's permitted to be a pointer to member.
11448     // Otherwise we'll end up making a bound member expression, which
11449     // is illegal in all the contexts we resolve like this.
11450     if (!ovl.HasFormOfMemberPointer &&
11451         isa<CXXMethodDecl>(fn) &&
11452         cast<CXXMethodDecl>(fn)->isInstance()) {
11453       if (!complain) return false;
11454 
11455       Diag(ovl.Expression->getExprLoc(),
11456            diag::err_bound_member_function)
11457         << 0 << ovl.Expression->getSourceRange();
11458 
11459       // TODO: I believe we only end up here if there's a mix of
11460       // static and non-static candidates (otherwise the expression
11461       // would have 'bound member' type, not 'overload' type).
11462       // Ideally we would note which candidate was chosen and why
11463       // the static candidates were rejected.
11464       SrcExpr = ExprError();
11465       return true;
11466     }
11467 
11468     // Fix the expression to refer to 'fn'.
11469     SingleFunctionExpression =
11470         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11471 
11472     // If desired, do function-to-pointer decay.
11473     if (doFunctionPointerConverion) {
11474       SingleFunctionExpression =
11475         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11476       if (SingleFunctionExpression.isInvalid()) {
11477         SrcExpr = ExprError();
11478         return true;
11479       }
11480     }
11481   }
11482 
11483   if (!SingleFunctionExpression.isUsable()) {
11484     if (complain) {
11485       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11486         << ovl.Expression->getName()
11487         << DestTypeForComplaining
11488         << OpRangeForComplaining
11489         << ovl.Expression->getQualifierLoc().getSourceRange();
11490       NoteAllOverloadCandidates(SrcExpr.get());
11491 
11492       SrcExpr = ExprError();
11493       return true;
11494     }
11495 
11496     return false;
11497   }
11498 
11499   SrcExpr = SingleFunctionExpression;
11500   return true;
11501 }
11502 
11503 /// Add a single candidate to the overload set.
11504 static void AddOverloadedCallCandidate(Sema &S,
11505                                        DeclAccessPair FoundDecl,
11506                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11507                                        ArrayRef<Expr *> Args,
11508                                        OverloadCandidateSet &CandidateSet,
11509                                        bool PartialOverloading,
11510                                        bool KnownValid) {
11511   NamedDecl *Callee = FoundDecl.getDecl();
11512   if (isa<UsingShadowDecl>(Callee))
11513     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11514 
11515   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11516     if (ExplicitTemplateArgs) {
11517       assert(!KnownValid && "Explicit template arguments?");
11518       return;
11519     }
11520     // Prevent ill-formed function decls to be added as overload candidates.
11521     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11522       return;
11523 
11524     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11525                            /*SuppressUsedConversions=*/false,
11526                            PartialOverloading);
11527     return;
11528   }
11529 
11530   if (FunctionTemplateDecl *FuncTemplate
11531       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11532     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11533                                    ExplicitTemplateArgs, Args, CandidateSet,
11534                                    /*SuppressUsedConversions=*/false,
11535                                    PartialOverloading);
11536     return;
11537   }
11538 
11539   assert(!KnownValid && "unhandled case in overloaded call candidate");
11540 }
11541 
11542 /// Add the overload candidates named by callee and/or found by argument
11543 /// dependent lookup to the given overload set.
11544 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11545                                        ArrayRef<Expr *> Args,
11546                                        OverloadCandidateSet &CandidateSet,
11547                                        bool PartialOverloading) {
11548 
11549 #ifndef NDEBUG
11550   // Verify that ArgumentDependentLookup is consistent with the rules
11551   // in C++0x [basic.lookup.argdep]p3:
11552   //
11553   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11554   //   and let Y be the lookup set produced by argument dependent
11555   //   lookup (defined as follows). If X contains
11556   //
11557   //     -- a declaration of a class member, or
11558   //
11559   //     -- a block-scope function declaration that is not a
11560   //        using-declaration, or
11561   //
11562   //     -- a declaration that is neither a function or a function
11563   //        template
11564   //
11565   //   then Y is empty.
11566 
11567   if (ULE->requiresADL()) {
11568     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11569            E = ULE->decls_end(); I != E; ++I) {
11570       assert(!(*I)->getDeclContext()->isRecord());
11571       assert(isa<UsingShadowDecl>(*I) ||
11572              !(*I)->getDeclContext()->isFunctionOrMethod());
11573       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11574     }
11575   }
11576 #endif
11577 
11578   // It would be nice to avoid this copy.
11579   TemplateArgumentListInfo TABuffer;
11580   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11581   if (ULE->hasExplicitTemplateArgs()) {
11582     ULE->copyTemplateArgumentsInto(TABuffer);
11583     ExplicitTemplateArgs = &TABuffer;
11584   }
11585 
11586   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11587          E = ULE->decls_end(); I != E; ++I)
11588     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11589                                CandidateSet, PartialOverloading,
11590                                /*KnownValid*/ true);
11591 
11592   if (ULE->requiresADL())
11593     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11594                                          Args, ExplicitTemplateArgs,
11595                                          CandidateSet, PartialOverloading);
11596 }
11597 
11598 /// Determine whether a declaration with the specified name could be moved into
11599 /// a different namespace.
11600 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11601   switch (Name.getCXXOverloadedOperator()) {
11602   case OO_New: case OO_Array_New:
11603   case OO_Delete: case OO_Array_Delete:
11604     return false;
11605 
11606   default:
11607     return true;
11608   }
11609 }
11610 
11611 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11612 /// template, where the non-dependent name was declared after the template
11613 /// was defined. This is common in code written for a compilers which do not
11614 /// correctly implement two-stage name lookup.
11615 ///
11616 /// Returns true if a viable candidate was found and a diagnostic was issued.
11617 static bool
11618 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11619                        const CXXScopeSpec &SS, LookupResult &R,
11620                        OverloadCandidateSet::CandidateSetKind CSK,
11621                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11622                        ArrayRef<Expr *> Args,
11623                        bool *DoDiagnoseEmptyLookup = nullptr) {
11624   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11625     return false;
11626 
11627   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11628     if (DC->isTransparentContext())
11629       continue;
11630 
11631     SemaRef.LookupQualifiedName(R, DC);
11632 
11633     if (!R.empty()) {
11634       R.suppressDiagnostics();
11635 
11636       if (isa<CXXRecordDecl>(DC)) {
11637         // Don't diagnose names we find in classes; we get much better
11638         // diagnostics for these from DiagnoseEmptyLookup.
11639         R.clear();
11640         if (DoDiagnoseEmptyLookup)
11641           *DoDiagnoseEmptyLookup = true;
11642         return false;
11643       }
11644 
11645       OverloadCandidateSet Candidates(FnLoc, CSK);
11646       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11647         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11648                                    ExplicitTemplateArgs, Args,
11649                                    Candidates, false, /*KnownValid*/ false);
11650 
11651       OverloadCandidateSet::iterator Best;
11652       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11653         // No viable functions. Don't bother the user with notes for functions
11654         // which don't work and shouldn't be found anyway.
11655         R.clear();
11656         return false;
11657       }
11658 
11659       // Find the namespaces where ADL would have looked, and suggest
11660       // declaring the function there instead.
11661       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11662       Sema::AssociatedClassSet AssociatedClasses;
11663       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11664                                                  AssociatedNamespaces,
11665                                                  AssociatedClasses);
11666       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11667       if (canBeDeclaredInNamespace(R.getLookupName())) {
11668         DeclContext *Std = SemaRef.getStdNamespace();
11669         for (Sema::AssociatedNamespaceSet::iterator
11670                it = AssociatedNamespaces.begin(),
11671                end = AssociatedNamespaces.end(); it != end; ++it) {
11672           // Never suggest declaring a function within namespace 'std'.
11673           if (Std && Std->Encloses(*it))
11674             continue;
11675 
11676           // Never suggest declaring a function within a namespace with a
11677           // reserved name, like __gnu_cxx.
11678           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11679           if (NS &&
11680               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11681             continue;
11682 
11683           SuggestedNamespaces.insert(*it);
11684         }
11685       }
11686 
11687       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11688         << R.getLookupName();
11689       if (SuggestedNamespaces.empty()) {
11690         SemaRef.Diag(Best->Function->getLocation(),
11691                      diag::note_not_found_by_two_phase_lookup)
11692           << R.getLookupName() << 0;
11693       } else if (SuggestedNamespaces.size() == 1) {
11694         SemaRef.Diag(Best->Function->getLocation(),
11695                      diag::note_not_found_by_two_phase_lookup)
11696           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11697       } else {
11698         // FIXME: It would be useful to list the associated namespaces here,
11699         // but the diagnostics infrastructure doesn't provide a way to produce
11700         // a localized representation of a list of items.
11701         SemaRef.Diag(Best->Function->getLocation(),
11702                      diag::note_not_found_by_two_phase_lookup)
11703           << R.getLookupName() << 2;
11704       }
11705 
11706       // Try to recover by calling this function.
11707       return true;
11708     }
11709 
11710     R.clear();
11711   }
11712 
11713   return false;
11714 }
11715 
11716 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11717 /// template, where the non-dependent operator was declared after the template
11718 /// was defined.
11719 ///
11720 /// Returns true if a viable candidate was found and a diagnostic was issued.
11721 static bool
11722 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11723                                SourceLocation OpLoc,
11724                                ArrayRef<Expr *> Args) {
11725   DeclarationName OpName =
11726     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11727   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11728   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11729                                 OverloadCandidateSet::CSK_Operator,
11730                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11731 }
11732 
11733 namespace {
11734 class BuildRecoveryCallExprRAII {
11735   Sema &SemaRef;
11736 public:
11737   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11738     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11739     SemaRef.IsBuildingRecoveryCallExpr = true;
11740   }
11741 
11742   ~BuildRecoveryCallExprRAII() {
11743     SemaRef.IsBuildingRecoveryCallExpr = false;
11744   }
11745 };
11746 
11747 }
11748 
11749 static std::unique_ptr<CorrectionCandidateCallback>
11750 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11751               bool HasTemplateArgs, bool AllowTypoCorrection) {
11752   if (!AllowTypoCorrection)
11753     return llvm::make_unique<NoTypoCorrectionCCC>();
11754   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11755                                                   HasTemplateArgs, ME);
11756 }
11757 
11758 /// Attempts to recover from a call where no functions were found.
11759 ///
11760 /// Returns true if new candidates were found.
11761 static ExprResult
11762 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11763                       UnresolvedLookupExpr *ULE,
11764                       SourceLocation LParenLoc,
11765                       MutableArrayRef<Expr *> Args,
11766                       SourceLocation RParenLoc,
11767                       bool EmptyLookup, bool AllowTypoCorrection) {
11768   // Do not try to recover if it is already building a recovery call.
11769   // This stops infinite loops for template instantiations like
11770   //
11771   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11772   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11773   //
11774   if (SemaRef.IsBuildingRecoveryCallExpr)
11775     return ExprError();
11776   BuildRecoveryCallExprRAII RCE(SemaRef);
11777 
11778   CXXScopeSpec SS;
11779   SS.Adopt(ULE->getQualifierLoc());
11780   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11781 
11782   TemplateArgumentListInfo TABuffer;
11783   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11784   if (ULE->hasExplicitTemplateArgs()) {
11785     ULE->copyTemplateArgumentsInto(TABuffer);
11786     ExplicitTemplateArgs = &TABuffer;
11787   }
11788 
11789   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11790                  Sema::LookupOrdinaryName);
11791   bool DoDiagnoseEmptyLookup = EmptyLookup;
11792   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11793                               OverloadCandidateSet::CSK_Normal,
11794                               ExplicitTemplateArgs, Args,
11795                               &DoDiagnoseEmptyLookup) &&
11796     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11797         S, SS, R,
11798         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11799                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11800         ExplicitTemplateArgs, Args)))
11801     return ExprError();
11802 
11803   assert(!R.empty() && "lookup results empty despite recovery");
11804 
11805   // If recovery created an ambiguity, just bail out.
11806   if (R.isAmbiguous()) {
11807     R.suppressDiagnostics();
11808     return ExprError();
11809   }
11810 
11811   // Build an implicit member call if appropriate.  Just drop the
11812   // casts and such from the call, we don't really care.
11813   ExprResult NewFn = ExprError();
11814   if ((*R.begin())->isCXXClassMember())
11815     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11816                                                     ExplicitTemplateArgs, S);
11817   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11818     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11819                                         ExplicitTemplateArgs);
11820   else
11821     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11822 
11823   if (NewFn.isInvalid())
11824     return ExprError();
11825 
11826   // This shouldn't cause an infinite loop because we're giving it
11827   // an expression with viable lookup results, which should never
11828   // end up here.
11829   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11830                                MultiExprArg(Args.data(), Args.size()),
11831                                RParenLoc);
11832 }
11833 
11834 /// Constructs and populates an OverloadedCandidateSet from
11835 /// the given function.
11836 /// \returns true when an the ExprResult output parameter has been set.
11837 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11838                                   UnresolvedLookupExpr *ULE,
11839                                   MultiExprArg Args,
11840                                   SourceLocation RParenLoc,
11841                                   OverloadCandidateSet *CandidateSet,
11842                                   ExprResult *Result) {
11843 #ifndef NDEBUG
11844   if (ULE->requiresADL()) {
11845     // To do ADL, we must have found an unqualified name.
11846     assert(!ULE->getQualifier() && "qualified name with ADL");
11847 
11848     // We don't perform ADL for implicit declarations of builtins.
11849     // Verify that this was correctly set up.
11850     FunctionDecl *F;
11851     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11852         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11853         F->getBuiltinID() && F->isImplicit())
11854       llvm_unreachable("performing ADL for builtin");
11855 
11856     // We don't perform ADL in C.
11857     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11858   }
11859 #endif
11860 
11861   UnbridgedCastsSet UnbridgedCasts;
11862   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11863     *Result = ExprError();
11864     return true;
11865   }
11866 
11867   // Add the functions denoted by the callee to the set of candidate
11868   // functions, including those from argument-dependent lookup.
11869   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11870 
11871   if (getLangOpts().MSVCCompat &&
11872       CurContext->isDependentContext() && !isSFINAEContext() &&
11873       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11874 
11875     OverloadCandidateSet::iterator Best;
11876     if (CandidateSet->empty() ||
11877         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11878             OR_No_Viable_Function) {
11879       // In Microsoft mode, if we are inside a template class member function then
11880       // create a type dependent CallExpr. The goal is to postpone name lookup
11881       // to instantiation time to be able to search into type dependent base
11882       // classes.
11883       CallExpr *CE = new (Context) CallExpr(
11884           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11885       CE->setTypeDependent(true);
11886       CE->setValueDependent(true);
11887       CE->setInstantiationDependent(true);
11888       *Result = CE;
11889       return true;
11890     }
11891   }
11892 
11893   if (CandidateSet->empty())
11894     return false;
11895 
11896   UnbridgedCasts.restore();
11897   return false;
11898 }
11899 
11900 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11901 /// the completed call expression. If overload resolution fails, emits
11902 /// diagnostics and returns ExprError()
11903 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11904                                            UnresolvedLookupExpr *ULE,
11905                                            SourceLocation LParenLoc,
11906                                            MultiExprArg Args,
11907                                            SourceLocation RParenLoc,
11908                                            Expr *ExecConfig,
11909                                            OverloadCandidateSet *CandidateSet,
11910                                            OverloadCandidateSet::iterator *Best,
11911                                            OverloadingResult OverloadResult,
11912                                            bool AllowTypoCorrection) {
11913   if (CandidateSet->empty())
11914     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11915                                  RParenLoc, /*EmptyLookup=*/true,
11916                                  AllowTypoCorrection);
11917 
11918   switch (OverloadResult) {
11919   case OR_Success: {
11920     FunctionDecl *FDecl = (*Best)->Function;
11921     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11922     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11923       return ExprError();
11924     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11925     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11926                                          ExecConfig);
11927   }
11928 
11929   case OR_No_Viable_Function: {
11930     // Try to recover by looking for viable functions which the user might
11931     // have meant to call.
11932     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11933                                                 Args, RParenLoc,
11934                                                 /*EmptyLookup=*/false,
11935                                                 AllowTypoCorrection);
11936     if (!Recovery.isInvalid())
11937       return Recovery;
11938 
11939     // If the user passes in a function that we can't take the address of, we
11940     // generally end up emitting really bad error messages. Here, we attempt to
11941     // emit better ones.
11942     for (const Expr *Arg : Args) {
11943       if (!Arg->getType()->isFunctionType())
11944         continue;
11945       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11946         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11947         if (FD &&
11948             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11949                                                        Arg->getExprLoc()))
11950           return ExprError();
11951       }
11952     }
11953 
11954     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11955         << ULE->getName() << Fn->getSourceRange();
11956     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11957     break;
11958   }
11959 
11960   case OR_Ambiguous:
11961     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11962       << ULE->getName() << Fn->getSourceRange();
11963     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11964     break;
11965 
11966   case OR_Deleted: {
11967     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11968       << (*Best)->Function->isDeleted()
11969       << ULE->getName()
11970       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11971       << Fn->getSourceRange();
11972     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11973 
11974     // We emitted an error for the unavailable/deleted function call but keep
11975     // the call in the AST.
11976     FunctionDecl *FDecl = (*Best)->Function;
11977     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11978     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11979                                          ExecConfig);
11980   }
11981   }
11982 
11983   // Overload resolution failed.
11984   return ExprError();
11985 }
11986 
11987 static void markUnaddressableCandidatesUnviable(Sema &S,
11988                                                 OverloadCandidateSet &CS) {
11989   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11990     if (I->Viable &&
11991         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11992       I->Viable = false;
11993       I->FailureKind = ovl_fail_addr_not_available;
11994     }
11995   }
11996 }
11997 
11998 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11999 /// (which eventually refers to the declaration Func) and the call
12000 /// arguments Args/NumArgs, attempt to resolve the function call down
12001 /// to a specific function. If overload resolution succeeds, returns
12002 /// the call expression produced by overload resolution.
12003 /// Otherwise, emits diagnostics and returns ExprError.
12004 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12005                                          UnresolvedLookupExpr *ULE,
12006                                          SourceLocation LParenLoc,
12007                                          MultiExprArg Args,
12008                                          SourceLocation RParenLoc,
12009                                          Expr *ExecConfig,
12010                                          bool AllowTypoCorrection,
12011                                          bool CalleesAddressIsTaken) {
12012   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12013                                     OverloadCandidateSet::CSK_Normal);
12014   ExprResult result;
12015 
12016   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12017                              &result))
12018     return result;
12019 
12020   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12021   // functions that aren't addressible are considered unviable.
12022   if (CalleesAddressIsTaken)
12023     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12024 
12025   OverloadCandidateSet::iterator Best;
12026   OverloadingResult OverloadResult =
12027       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12028 
12029   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12030                                   RParenLoc, ExecConfig, &CandidateSet,
12031                                   &Best, OverloadResult,
12032                                   AllowTypoCorrection);
12033 }
12034 
12035 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12036   return Functions.size() > 1 ||
12037     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12038 }
12039 
12040 /// Create a unary operation that may resolve to an overloaded
12041 /// operator.
12042 ///
12043 /// \param OpLoc The location of the operator itself (e.g., '*').
12044 ///
12045 /// \param Opc The UnaryOperatorKind that describes this operator.
12046 ///
12047 /// \param Fns The set of non-member functions that will be
12048 /// considered by overload resolution. The caller needs to build this
12049 /// set based on the context using, e.g.,
12050 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12051 /// set should not contain any member functions; those will be added
12052 /// by CreateOverloadedUnaryOp().
12053 ///
12054 /// \param Input The input argument.
12055 ExprResult
12056 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12057                               const UnresolvedSetImpl &Fns,
12058                               Expr *Input, bool PerformADL) {
12059   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12060   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12061   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12062   // TODO: provide better source location info.
12063   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12064 
12065   if (checkPlaceholderForOverload(*this, Input))
12066     return ExprError();
12067 
12068   Expr *Args[2] = { Input, nullptr };
12069   unsigned NumArgs = 1;
12070 
12071   // For post-increment and post-decrement, add the implicit '0' as
12072   // the second argument, so that we know this is a post-increment or
12073   // post-decrement.
12074   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12075     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12076     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12077                                      SourceLocation());
12078     NumArgs = 2;
12079   }
12080 
12081   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12082 
12083   if (Input->isTypeDependent()) {
12084     if (Fns.empty())
12085       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12086                                          VK_RValue, OK_Ordinary, OpLoc, false);
12087 
12088     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12089     UnresolvedLookupExpr *Fn
12090       = UnresolvedLookupExpr::Create(Context, NamingClass,
12091                                      NestedNameSpecifierLoc(), OpNameInfo,
12092                                      /*ADL*/ true, IsOverloaded(Fns),
12093                                      Fns.begin(), Fns.end());
12094     return new (Context)
12095         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12096                             VK_RValue, OpLoc, FPOptions());
12097   }
12098 
12099   // Build an empty overload set.
12100   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12101 
12102   // Add the candidates from the given function set.
12103   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12104 
12105   // Add operator candidates that are member functions.
12106   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12107 
12108   // Add candidates from ADL.
12109   if (PerformADL) {
12110     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12111                                          /*ExplicitTemplateArgs*/nullptr,
12112                                          CandidateSet);
12113   }
12114 
12115   // Add builtin operator candidates.
12116   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12117 
12118   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12119 
12120   // Perform overload resolution.
12121   OverloadCandidateSet::iterator Best;
12122   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12123   case OR_Success: {
12124     // We found a built-in operator or an overloaded operator.
12125     FunctionDecl *FnDecl = Best->Function;
12126 
12127     if (FnDecl) {
12128       Expr *Base = nullptr;
12129       // We matched an overloaded operator. Build a call to that
12130       // operator.
12131 
12132       // Convert the arguments.
12133       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12134         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12135 
12136         ExprResult InputRes =
12137           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12138                                               Best->FoundDecl, Method);
12139         if (InputRes.isInvalid())
12140           return ExprError();
12141         Base = Input = InputRes.get();
12142       } else {
12143         // Convert the arguments.
12144         ExprResult InputInit
12145           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12146                                                       Context,
12147                                                       FnDecl->getParamDecl(0)),
12148                                       SourceLocation(),
12149                                       Input);
12150         if (InputInit.isInvalid())
12151           return ExprError();
12152         Input = InputInit.get();
12153       }
12154 
12155       // Build the actual expression node.
12156       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12157                                                 Base, HadMultipleCandidates,
12158                                                 OpLoc);
12159       if (FnExpr.isInvalid())
12160         return ExprError();
12161 
12162       // Determine the result type.
12163       QualType ResultTy = FnDecl->getReturnType();
12164       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12165       ResultTy = ResultTy.getNonLValueExprType(Context);
12166 
12167       Args[0] = Input;
12168       CallExpr *TheCall =
12169         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12170                                           ResultTy, VK, OpLoc, FPOptions());
12171 
12172       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12173         return ExprError();
12174 
12175       if (CheckFunctionCall(FnDecl, TheCall,
12176                             FnDecl->getType()->castAs<FunctionProtoType>()))
12177         return ExprError();
12178 
12179       return MaybeBindToTemporary(TheCall);
12180     } else {
12181       // We matched a built-in operator. Convert the arguments, then
12182       // break out so that we will build the appropriate built-in
12183       // operator node.
12184       ExprResult InputRes = PerformImplicitConversion(
12185           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12186       if (InputRes.isInvalid())
12187         return ExprError();
12188       Input = InputRes.get();
12189       break;
12190     }
12191   }
12192 
12193   case OR_No_Viable_Function:
12194     // This is an erroneous use of an operator which can be overloaded by
12195     // a non-member function. Check for non-member operators which were
12196     // defined too late to be candidates.
12197     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12198       // FIXME: Recover by calling the found function.
12199       return ExprError();
12200 
12201     // No viable function; fall through to handling this as a
12202     // built-in operator, which will produce an error message for us.
12203     break;
12204 
12205   case OR_Ambiguous:
12206     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12207         << UnaryOperator::getOpcodeStr(Opc)
12208         << Input->getType()
12209         << Input->getSourceRange();
12210     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12211                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12212     return ExprError();
12213 
12214   case OR_Deleted:
12215     Diag(OpLoc, diag::err_ovl_deleted_oper)
12216       << Best->Function->isDeleted()
12217       << UnaryOperator::getOpcodeStr(Opc)
12218       << getDeletedOrUnavailableSuffix(Best->Function)
12219       << Input->getSourceRange();
12220     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12221                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12222     return ExprError();
12223   }
12224 
12225   // Either we found no viable overloaded operator or we matched a
12226   // built-in operator. In either case, fall through to trying to
12227   // build a built-in operation.
12228   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12229 }
12230 
12231 /// Create a binary operation that may resolve to an overloaded
12232 /// operator.
12233 ///
12234 /// \param OpLoc The location of the operator itself (e.g., '+').
12235 ///
12236 /// \param Opc The BinaryOperatorKind that describes this operator.
12237 ///
12238 /// \param Fns The set of non-member functions that will be
12239 /// considered by overload resolution. The caller needs to build this
12240 /// set based on the context using, e.g.,
12241 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12242 /// set should not contain any member functions; those will be added
12243 /// by CreateOverloadedBinOp().
12244 ///
12245 /// \param LHS Left-hand argument.
12246 /// \param RHS Right-hand argument.
12247 ExprResult
12248 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12249                             BinaryOperatorKind Opc,
12250                             const UnresolvedSetImpl &Fns,
12251                             Expr *LHS, Expr *RHS, bool PerformADL) {
12252   Expr *Args[2] = { LHS, RHS };
12253   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12254 
12255   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12256   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12257 
12258   // If either side is type-dependent, create an appropriate dependent
12259   // expression.
12260   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12261     if (Fns.empty()) {
12262       // If there are no functions to store, just build a dependent
12263       // BinaryOperator or CompoundAssignment.
12264       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12265         return new (Context) BinaryOperator(
12266             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12267             OpLoc, FPFeatures);
12268 
12269       return new (Context) CompoundAssignOperator(
12270           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12271           Context.DependentTy, Context.DependentTy, OpLoc,
12272           FPFeatures);
12273     }
12274 
12275     // FIXME: save results of ADL from here?
12276     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12277     // TODO: provide better source location info in DNLoc component.
12278     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12279     UnresolvedLookupExpr *Fn
12280       = UnresolvedLookupExpr::Create(Context, NamingClass,
12281                                      NestedNameSpecifierLoc(), OpNameInfo,
12282                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12283                                      Fns.begin(), Fns.end());
12284     return new (Context)
12285         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12286                             VK_RValue, OpLoc, FPFeatures);
12287   }
12288 
12289   // Always do placeholder-like conversions on the RHS.
12290   if (checkPlaceholderForOverload(*this, Args[1]))
12291     return ExprError();
12292 
12293   // Do placeholder-like conversion on the LHS; note that we should
12294   // not get here with a PseudoObject LHS.
12295   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12296   if (checkPlaceholderForOverload(*this, Args[0]))
12297     return ExprError();
12298 
12299   // If this is the assignment operator, we only perform overload resolution
12300   // if the left-hand side is a class or enumeration type. This is actually
12301   // a hack. The standard requires that we do overload resolution between the
12302   // various built-in candidates, but as DR507 points out, this can lead to
12303   // problems. So we do it this way, which pretty much follows what GCC does.
12304   // Note that we go the traditional code path for compound assignment forms.
12305   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12306     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12307 
12308   // If this is the .* operator, which is not overloadable, just
12309   // create a built-in binary operator.
12310   if (Opc == BO_PtrMemD)
12311     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12312 
12313   // Build an empty overload set.
12314   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12315 
12316   // Add the candidates from the given function set.
12317   AddFunctionCandidates(Fns, Args, CandidateSet);
12318 
12319   // Add operator candidates that are member functions.
12320   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12321 
12322   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12323   // performed for an assignment operator (nor for operator[] nor operator->,
12324   // which don't get here).
12325   if (Opc != BO_Assign && PerformADL)
12326     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12327                                          /*ExplicitTemplateArgs*/ nullptr,
12328                                          CandidateSet);
12329 
12330   // Add builtin operator candidates.
12331   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12332 
12333   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12334 
12335   // Perform overload resolution.
12336   OverloadCandidateSet::iterator Best;
12337   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12338     case OR_Success: {
12339       // We found a built-in operator or an overloaded operator.
12340       FunctionDecl *FnDecl = Best->Function;
12341 
12342       if (FnDecl) {
12343         Expr *Base = nullptr;
12344         // We matched an overloaded operator. Build a call to that
12345         // operator.
12346 
12347         // Convert the arguments.
12348         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12349           // Best->Access is only meaningful for class members.
12350           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12351 
12352           ExprResult Arg1 =
12353             PerformCopyInitialization(
12354               InitializedEntity::InitializeParameter(Context,
12355                                                      FnDecl->getParamDecl(0)),
12356               SourceLocation(), Args[1]);
12357           if (Arg1.isInvalid())
12358             return ExprError();
12359 
12360           ExprResult Arg0 =
12361             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12362                                                 Best->FoundDecl, Method);
12363           if (Arg0.isInvalid())
12364             return ExprError();
12365           Base = Args[0] = Arg0.getAs<Expr>();
12366           Args[1] = RHS = Arg1.getAs<Expr>();
12367         } else {
12368           // Convert the arguments.
12369           ExprResult Arg0 = PerformCopyInitialization(
12370             InitializedEntity::InitializeParameter(Context,
12371                                                    FnDecl->getParamDecl(0)),
12372             SourceLocation(), Args[0]);
12373           if (Arg0.isInvalid())
12374             return ExprError();
12375 
12376           ExprResult Arg1 =
12377             PerformCopyInitialization(
12378               InitializedEntity::InitializeParameter(Context,
12379                                                      FnDecl->getParamDecl(1)),
12380               SourceLocation(), Args[1]);
12381           if (Arg1.isInvalid())
12382             return ExprError();
12383           Args[0] = LHS = Arg0.getAs<Expr>();
12384           Args[1] = RHS = Arg1.getAs<Expr>();
12385         }
12386 
12387         // Build the actual expression node.
12388         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12389                                                   Best->FoundDecl, Base,
12390                                                   HadMultipleCandidates, OpLoc);
12391         if (FnExpr.isInvalid())
12392           return ExprError();
12393 
12394         // Determine the result type.
12395         QualType ResultTy = FnDecl->getReturnType();
12396         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12397         ResultTy = ResultTy.getNonLValueExprType(Context);
12398 
12399         CXXOperatorCallExpr *TheCall =
12400           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12401                                             Args, ResultTy, VK, OpLoc,
12402                                             FPFeatures);
12403 
12404         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12405                                 FnDecl))
12406           return ExprError();
12407 
12408         ArrayRef<const Expr *> ArgsArray(Args, 2);
12409         const Expr *ImplicitThis = nullptr;
12410         // Cut off the implicit 'this'.
12411         if (isa<CXXMethodDecl>(FnDecl)) {
12412           ImplicitThis = ArgsArray[0];
12413           ArgsArray = ArgsArray.slice(1);
12414         }
12415 
12416         // Check for a self move.
12417         if (Op == OO_Equal)
12418           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12419 
12420         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12421                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12422                   VariadicDoesNotApply);
12423 
12424         return MaybeBindToTemporary(TheCall);
12425       } else {
12426         // We matched a built-in operator. Convert the arguments, then
12427         // break out so that we will build the appropriate built-in
12428         // operator node.
12429         ExprResult ArgsRes0 =
12430             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12431                                       Best->Conversions[0], AA_Passing);
12432         if (ArgsRes0.isInvalid())
12433           return ExprError();
12434         Args[0] = ArgsRes0.get();
12435 
12436         ExprResult ArgsRes1 =
12437             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12438                                       Best->Conversions[1], AA_Passing);
12439         if (ArgsRes1.isInvalid())
12440           return ExprError();
12441         Args[1] = ArgsRes1.get();
12442         break;
12443       }
12444     }
12445 
12446     case OR_No_Viable_Function: {
12447       // C++ [over.match.oper]p9:
12448       //   If the operator is the operator , [...] and there are no
12449       //   viable functions, then the operator is assumed to be the
12450       //   built-in operator and interpreted according to clause 5.
12451       if (Opc == BO_Comma)
12452         break;
12453 
12454       // For class as left operand for assignment or compound assignment
12455       // operator do not fall through to handling in built-in, but report that
12456       // no overloaded assignment operator found
12457       ExprResult Result = ExprError();
12458       if (Args[0]->getType()->isRecordType() &&
12459           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12460         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12461              << BinaryOperator::getOpcodeStr(Opc)
12462              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12463         if (Args[0]->getType()->isIncompleteType()) {
12464           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12465             << Args[0]->getType()
12466             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12467         }
12468       } else {
12469         // This is an erroneous use of an operator which can be overloaded by
12470         // a non-member function. Check for non-member operators which were
12471         // defined too late to be candidates.
12472         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12473           // FIXME: Recover by calling the found function.
12474           return ExprError();
12475 
12476         // No viable function; try to create a built-in operation, which will
12477         // produce an error. Then, show the non-viable candidates.
12478         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12479       }
12480       assert(Result.isInvalid() &&
12481              "C++ binary operator overloading is missing candidates!");
12482       if (Result.isInvalid())
12483         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12484                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12485       return Result;
12486     }
12487 
12488     case OR_Ambiguous:
12489       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12490           << BinaryOperator::getOpcodeStr(Opc)
12491           << Args[0]->getType() << Args[1]->getType()
12492           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12493       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12494                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12495       return ExprError();
12496 
12497     case OR_Deleted:
12498       if (isImplicitlyDeleted(Best->Function)) {
12499         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12500         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12501           << Context.getRecordType(Method->getParent())
12502           << getSpecialMember(Method);
12503 
12504         // The user probably meant to call this special member. Just
12505         // explain why it's deleted.
12506         NoteDeletedFunction(Method);
12507         return ExprError();
12508       } else {
12509         Diag(OpLoc, diag::err_ovl_deleted_oper)
12510           << Best->Function->isDeleted()
12511           << BinaryOperator::getOpcodeStr(Opc)
12512           << getDeletedOrUnavailableSuffix(Best->Function)
12513           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12514       }
12515       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12516                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12517       return ExprError();
12518   }
12519 
12520   // We matched a built-in operator; build it.
12521   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12522 }
12523 
12524 ExprResult
12525 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12526                                          SourceLocation RLoc,
12527                                          Expr *Base, Expr *Idx) {
12528   Expr *Args[2] = { Base, Idx };
12529   DeclarationName OpName =
12530       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12531 
12532   // If either side is type-dependent, create an appropriate dependent
12533   // expression.
12534   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12535 
12536     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12537     // CHECKME: no 'operator' keyword?
12538     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12539     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12540     UnresolvedLookupExpr *Fn
12541       = UnresolvedLookupExpr::Create(Context, NamingClass,
12542                                      NestedNameSpecifierLoc(), OpNameInfo,
12543                                      /*ADL*/ true, /*Overloaded*/ false,
12544                                      UnresolvedSetIterator(),
12545                                      UnresolvedSetIterator());
12546     // Can't add any actual overloads yet
12547 
12548     return new (Context)
12549         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12550                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12551   }
12552 
12553   // Handle placeholders on both operands.
12554   if (checkPlaceholderForOverload(*this, Args[0]))
12555     return ExprError();
12556   if (checkPlaceholderForOverload(*this, Args[1]))
12557     return ExprError();
12558 
12559   // Build an empty overload set.
12560   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12561 
12562   // Subscript can only be overloaded as a member function.
12563 
12564   // Add operator candidates that are member functions.
12565   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12566 
12567   // Add builtin operator candidates.
12568   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12569 
12570   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12571 
12572   // Perform overload resolution.
12573   OverloadCandidateSet::iterator Best;
12574   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12575     case OR_Success: {
12576       // We found a built-in operator or an overloaded operator.
12577       FunctionDecl *FnDecl = Best->Function;
12578 
12579       if (FnDecl) {
12580         // We matched an overloaded operator. Build a call to that
12581         // operator.
12582 
12583         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12584 
12585         // Convert the arguments.
12586         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12587         ExprResult Arg0 =
12588           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12589                                               Best->FoundDecl, Method);
12590         if (Arg0.isInvalid())
12591           return ExprError();
12592         Args[0] = Arg0.get();
12593 
12594         // Convert the arguments.
12595         ExprResult InputInit
12596           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12597                                                       Context,
12598                                                       FnDecl->getParamDecl(0)),
12599                                       SourceLocation(),
12600                                       Args[1]);
12601         if (InputInit.isInvalid())
12602           return ExprError();
12603 
12604         Args[1] = InputInit.getAs<Expr>();
12605 
12606         // Build the actual expression node.
12607         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12608         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12609         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12610                                                   Best->FoundDecl,
12611                                                   Base,
12612                                                   HadMultipleCandidates,
12613                                                   OpLocInfo.getLoc(),
12614                                                   OpLocInfo.getInfo());
12615         if (FnExpr.isInvalid())
12616           return ExprError();
12617 
12618         // Determine the result type
12619         QualType ResultTy = FnDecl->getReturnType();
12620         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12621         ResultTy = ResultTy.getNonLValueExprType(Context);
12622 
12623         CXXOperatorCallExpr *TheCall =
12624           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12625                                             FnExpr.get(), Args,
12626                                             ResultTy, VK, RLoc,
12627                                             FPOptions());
12628 
12629         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12630           return ExprError();
12631 
12632         if (CheckFunctionCall(Method, TheCall,
12633                               Method->getType()->castAs<FunctionProtoType>()))
12634           return ExprError();
12635 
12636         return MaybeBindToTemporary(TheCall);
12637       } else {
12638         // We matched a built-in operator. Convert the arguments, then
12639         // break out so that we will build the appropriate built-in
12640         // operator node.
12641         ExprResult ArgsRes0 =
12642             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12643                                       Best->Conversions[0], AA_Passing);
12644         if (ArgsRes0.isInvalid())
12645           return ExprError();
12646         Args[0] = ArgsRes0.get();
12647 
12648         ExprResult ArgsRes1 =
12649             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12650                                       Best->Conversions[1], AA_Passing);
12651         if (ArgsRes1.isInvalid())
12652           return ExprError();
12653         Args[1] = ArgsRes1.get();
12654 
12655         break;
12656       }
12657     }
12658 
12659     case OR_No_Viable_Function: {
12660       if (CandidateSet.empty())
12661         Diag(LLoc, diag::err_ovl_no_oper)
12662           << Args[0]->getType() << /*subscript*/ 0
12663           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12664       else
12665         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12666           << Args[0]->getType()
12667           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12668       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12669                                   "[]", LLoc);
12670       return ExprError();
12671     }
12672 
12673     case OR_Ambiguous:
12674       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12675           << "[]"
12676           << Args[0]->getType() << Args[1]->getType()
12677           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12678       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12679                                   "[]", LLoc);
12680       return ExprError();
12681 
12682     case OR_Deleted:
12683       Diag(LLoc, diag::err_ovl_deleted_oper)
12684         << Best->Function->isDeleted() << "[]"
12685         << getDeletedOrUnavailableSuffix(Best->Function)
12686         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12687       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12688                                   "[]", LLoc);
12689       return ExprError();
12690     }
12691 
12692   // We matched a built-in operator; build it.
12693   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12694 }
12695 
12696 /// BuildCallToMemberFunction - Build a call to a member
12697 /// function. MemExpr is the expression that refers to the member
12698 /// function (and includes the object parameter), Args/NumArgs are the
12699 /// arguments to the function call (not including the object
12700 /// parameter). The caller needs to validate that the member
12701 /// expression refers to a non-static member function or an overloaded
12702 /// member function.
12703 ExprResult
12704 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12705                                 SourceLocation LParenLoc,
12706                                 MultiExprArg Args,
12707                                 SourceLocation RParenLoc) {
12708   assert(MemExprE->getType() == Context.BoundMemberTy ||
12709          MemExprE->getType() == Context.OverloadTy);
12710 
12711   // Dig out the member expression. This holds both the object
12712   // argument and the member function we're referring to.
12713   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12714 
12715   // Determine whether this is a call to a pointer-to-member function.
12716   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12717     assert(op->getType() == Context.BoundMemberTy);
12718     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12719 
12720     QualType fnType =
12721       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12722 
12723     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12724     QualType resultType = proto->getCallResultType(Context);
12725     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12726 
12727     // Check that the object type isn't more qualified than the
12728     // member function we're calling.
12729     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12730 
12731     QualType objectType = op->getLHS()->getType();
12732     if (op->getOpcode() == BO_PtrMemI)
12733       objectType = objectType->castAs<PointerType>()->getPointeeType();
12734     Qualifiers objectQuals = objectType.getQualifiers();
12735 
12736     Qualifiers difference = objectQuals - funcQuals;
12737     difference.removeObjCGCAttr();
12738     difference.removeAddressSpace();
12739     if (difference) {
12740       std::string qualsString = difference.getAsString();
12741       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12742         << fnType.getUnqualifiedType()
12743         << qualsString
12744         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12745     }
12746 
12747     CXXMemberCallExpr *call
12748       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12749                                         resultType, valueKind, RParenLoc);
12750 
12751     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12752                             call, nullptr))
12753       return ExprError();
12754 
12755     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12756       return ExprError();
12757 
12758     if (CheckOtherCall(call, proto))
12759       return ExprError();
12760 
12761     return MaybeBindToTemporary(call);
12762   }
12763 
12764   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12765     return new (Context)
12766         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12767 
12768   UnbridgedCastsSet UnbridgedCasts;
12769   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12770     return ExprError();
12771 
12772   MemberExpr *MemExpr;
12773   CXXMethodDecl *Method = nullptr;
12774   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12775   NestedNameSpecifier *Qualifier = nullptr;
12776   if (isa<MemberExpr>(NakedMemExpr)) {
12777     MemExpr = cast<MemberExpr>(NakedMemExpr);
12778     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12779     FoundDecl = MemExpr->getFoundDecl();
12780     Qualifier = MemExpr->getQualifier();
12781     UnbridgedCasts.restore();
12782   } else {
12783     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12784     Qualifier = UnresExpr->getQualifier();
12785 
12786     QualType ObjectType = UnresExpr->getBaseType();
12787     Expr::Classification ObjectClassification
12788       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12789                             : UnresExpr->getBase()->Classify(Context);
12790 
12791     // Add overload candidates
12792     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12793                                       OverloadCandidateSet::CSK_Normal);
12794 
12795     // FIXME: avoid copy.
12796     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12797     if (UnresExpr->hasExplicitTemplateArgs()) {
12798       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12799       TemplateArgs = &TemplateArgsBuffer;
12800     }
12801 
12802     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12803            E = UnresExpr->decls_end(); I != E; ++I) {
12804 
12805       NamedDecl *Func = *I;
12806       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12807       if (isa<UsingShadowDecl>(Func))
12808         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12809 
12810 
12811       // Microsoft supports direct constructor calls.
12812       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12813         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12814                              Args, CandidateSet);
12815       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12816         // If explicit template arguments were provided, we can't call a
12817         // non-template member function.
12818         if (TemplateArgs)
12819           continue;
12820 
12821         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12822                            ObjectClassification, Args, CandidateSet,
12823                            /*SuppressUserConversions=*/false);
12824       } else {
12825         AddMethodTemplateCandidate(
12826             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12827             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12828             /*SuppressUsedConversions=*/false);
12829       }
12830     }
12831 
12832     DeclarationName DeclName = UnresExpr->getMemberName();
12833 
12834     UnbridgedCasts.restore();
12835 
12836     OverloadCandidateSet::iterator Best;
12837     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12838                                             Best)) {
12839     case OR_Success:
12840       Method = cast<CXXMethodDecl>(Best->Function);
12841       FoundDecl = Best->FoundDecl;
12842       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12843       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12844         return ExprError();
12845       // If FoundDecl is different from Method (such as if one is a template
12846       // and the other a specialization), make sure DiagnoseUseOfDecl is
12847       // called on both.
12848       // FIXME: This would be more comprehensively addressed by modifying
12849       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12850       // being used.
12851       if (Method != FoundDecl.getDecl() &&
12852                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12853         return ExprError();
12854       break;
12855 
12856     case OR_No_Viable_Function:
12857       Diag(UnresExpr->getMemberLoc(),
12858            diag::err_ovl_no_viable_member_function_in_call)
12859         << DeclName << MemExprE->getSourceRange();
12860       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12861       // FIXME: Leaking incoming expressions!
12862       return ExprError();
12863 
12864     case OR_Ambiguous:
12865       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12866         << DeclName << MemExprE->getSourceRange();
12867       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12868       // FIXME: Leaking incoming expressions!
12869       return ExprError();
12870 
12871     case OR_Deleted:
12872       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12873         << Best->Function->isDeleted()
12874         << DeclName
12875         << getDeletedOrUnavailableSuffix(Best->Function)
12876         << MemExprE->getSourceRange();
12877       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12878       // FIXME: Leaking incoming expressions!
12879       return ExprError();
12880     }
12881 
12882     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12883 
12884     // If overload resolution picked a static member, build a
12885     // non-member call based on that function.
12886     if (Method->isStatic()) {
12887       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12888                                    RParenLoc);
12889     }
12890 
12891     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12892   }
12893 
12894   QualType ResultType = Method->getReturnType();
12895   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12896   ResultType = ResultType.getNonLValueExprType(Context);
12897 
12898   assert(Method && "Member call to something that isn't a method?");
12899   CXXMemberCallExpr *TheCall =
12900     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12901                                     ResultType, VK, RParenLoc);
12902 
12903   // Check for a valid return type.
12904   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12905                           TheCall, Method))
12906     return ExprError();
12907 
12908   // Convert the object argument (for a non-static member function call).
12909   // We only need to do this if there was actually an overload; otherwise
12910   // it was done at lookup.
12911   if (!Method->isStatic()) {
12912     ExprResult ObjectArg =
12913       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12914                                           FoundDecl, Method);
12915     if (ObjectArg.isInvalid())
12916       return ExprError();
12917     MemExpr->setBase(ObjectArg.get());
12918   }
12919 
12920   // Convert the rest of the arguments
12921   const FunctionProtoType *Proto =
12922     Method->getType()->getAs<FunctionProtoType>();
12923   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12924                               RParenLoc))
12925     return ExprError();
12926 
12927   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12928 
12929   if (CheckFunctionCall(Method, TheCall, Proto))
12930     return ExprError();
12931 
12932   // In the case the method to call was not selected by the overloading
12933   // resolution process, we still need to handle the enable_if attribute. Do
12934   // that here, so it will not hide previous -- and more relevant -- errors.
12935   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12936     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12937       Diag(MemE->getMemberLoc(),
12938            diag::err_ovl_no_viable_member_function_in_call)
12939           << Method << Method->getSourceRange();
12940       Diag(Method->getLocation(),
12941            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12942           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12943       return ExprError();
12944     }
12945   }
12946 
12947   if ((isa<CXXConstructorDecl>(CurContext) ||
12948        isa<CXXDestructorDecl>(CurContext)) &&
12949       TheCall->getMethodDecl()->isPure()) {
12950     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12951 
12952     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12953         MemExpr->performsVirtualDispatch(getLangOpts())) {
12954       Diag(MemExpr->getLocStart(),
12955            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12956         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12957         << MD->getParent()->getDeclName();
12958 
12959       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12960       if (getLangOpts().AppleKext)
12961         Diag(MemExpr->getLocStart(),
12962              diag::note_pure_qualified_call_kext)
12963              << MD->getParent()->getDeclName()
12964              << MD->getDeclName();
12965     }
12966   }
12967 
12968   if (CXXDestructorDecl *DD =
12969           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12970     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12971     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12972     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12973                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12974                          MemExpr->getMemberLoc());
12975   }
12976 
12977   return MaybeBindToTemporary(TheCall);
12978 }
12979 
12980 /// BuildCallToObjectOfClassType - Build a call to an object of class
12981 /// type (C++ [over.call.object]), which can end up invoking an
12982 /// overloaded function call operator (@c operator()) or performing a
12983 /// user-defined conversion on the object argument.
12984 ExprResult
12985 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12986                                    SourceLocation LParenLoc,
12987                                    MultiExprArg Args,
12988                                    SourceLocation RParenLoc) {
12989   if (checkPlaceholderForOverload(*this, Obj))
12990     return ExprError();
12991   ExprResult Object = Obj;
12992 
12993   UnbridgedCastsSet UnbridgedCasts;
12994   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12995     return ExprError();
12996 
12997   assert(Object.get()->getType()->isRecordType() &&
12998          "Requires object type argument");
12999   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13000 
13001   // C++ [over.call.object]p1:
13002   //  If the primary-expression E in the function call syntax
13003   //  evaluates to a class object of type "cv T", then the set of
13004   //  candidate functions includes at least the function call
13005   //  operators of T. The function call operators of T are obtained by
13006   //  ordinary lookup of the name operator() in the context of
13007   //  (E).operator().
13008   OverloadCandidateSet CandidateSet(LParenLoc,
13009                                     OverloadCandidateSet::CSK_Operator);
13010   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13011 
13012   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13013                           diag::err_incomplete_object_call, Object.get()))
13014     return true;
13015 
13016   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13017   LookupQualifiedName(R, Record->getDecl());
13018   R.suppressDiagnostics();
13019 
13020   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13021        Oper != OperEnd; ++Oper) {
13022     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13023                        Object.get()->Classify(Context), Args, CandidateSet,
13024                        /*SuppressUserConversions=*/false);
13025   }
13026 
13027   // C++ [over.call.object]p2:
13028   //   In addition, for each (non-explicit in C++0x) conversion function
13029   //   declared in T of the form
13030   //
13031   //        operator conversion-type-id () cv-qualifier;
13032   //
13033   //   where cv-qualifier is the same cv-qualification as, or a
13034   //   greater cv-qualification than, cv, and where conversion-type-id
13035   //   denotes the type "pointer to function of (P1,...,Pn) returning
13036   //   R", or the type "reference to pointer to function of
13037   //   (P1,...,Pn) returning R", or the type "reference to function
13038   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13039   //   is also considered as a candidate function. Similarly,
13040   //   surrogate call functions are added to the set of candidate
13041   //   functions for each conversion function declared in an
13042   //   accessible base class provided the function is not hidden
13043   //   within T by another intervening declaration.
13044   const auto &Conversions =
13045       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13046   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13047     NamedDecl *D = *I;
13048     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13049     if (isa<UsingShadowDecl>(D))
13050       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13051 
13052     // Skip over templated conversion functions; they aren't
13053     // surrogates.
13054     if (isa<FunctionTemplateDecl>(D))
13055       continue;
13056 
13057     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13058     if (!Conv->isExplicit()) {
13059       // Strip the reference type (if any) and then the pointer type (if
13060       // any) to get down to what might be a function type.
13061       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13062       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13063         ConvType = ConvPtrType->getPointeeType();
13064 
13065       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13066       {
13067         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13068                               Object.get(), Args, CandidateSet);
13069       }
13070     }
13071   }
13072 
13073   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13074 
13075   // Perform overload resolution.
13076   OverloadCandidateSet::iterator Best;
13077   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13078                                           Best)) {
13079   case OR_Success:
13080     // Overload resolution succeeded; we'll build the appropriate call
13081     // below.
13082     break;
13083 
13084   case OR_No_Viable_Function:
13085     if (CandidateSet.empty())
13086       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13087         << Object.get()->getType() << /*call*/ 1
13088         << Object.get()->getSourceRange();
13089     else
13090       Diag(Object.get()->getLocStart(),
13091            diag::err_ovl_no_viable_object_call)
13092         << Object.get()->getType() << Object.get()->getSourceRange();
13093     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13094     break;
13095 
13096   case OR_Ambiguous:
13097     Diag(Object.get()->getLocStart(),
13098          diag::err_ovl_ambiguous_object_call)
13099       << Object.get()->getType() << Object.get()->getSourceRange();
13100     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13101     break;
13102 
13103   case OR_Deleted:
13104     Diag(Object.get()->getLocStart(),
13105          diag::err_ovl_deleted_object_call)
13106       << Best->Function->isDeleted()
13107       << Object.get()->getType()
13108       << getDeletedOrUnavailableSuffix(Best->Function)
13109       << Object.get()->getSourceRange();
13110     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13111     break;
13112   }
13113 
13114   if (Best == CandidateSet.end())
13115     return true;
13116 
13117   UnbridgedCasts.restore();
13118 
13119   if (Best->Function == nullptr) {
13120     // Since there is no function declaration, this is one of the
13121     // surrogate candidates. Dig out the conversion function.
13122     CXXConversionDecl *Conv
13123       = cast<CXXConversionDecl>(
13124                          Best->Conversions[0].UserDefined.ConversionFunction);
13125 
13126     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13127                               Best->FoundDecl);
13128     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13129       return ExprError();
13130     assert(Conv == Best->FoundDecl.getDecl() &&
13131              "Found Decl & conversion-to-functionptr should be same, right?!");
13132     // We selected one of the surrogate functions that converts the
13133     // object parameter to a function pointer. Perform the conversion
13134     // on the object argument, then let ActOnCallExpr finish the job.
13135 
13136     // Create an implicit member expr to refer to the conversion operator.
13137     // and then call it.
13138     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13139                                              Conv, HadMultipleCandidates);
13140     if (Call.isInvalid())
13141       return ExprError();
13142     // Record usage of conversion in an implicit cast.
13143     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13144                                     CK_UserDefinedConversion, Call.get(),
13145                                     nullptr, VK_RValue);
13146 
13147     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13148   }
13149 
13150   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13151 
13152   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13153   // that calls this method, using Object for the implicit object
13154   // parameter and passing along the remaining arguments.
13155   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13156 
13157   // An error diagnostic has already been printed when parsing the declaration.
13158   if (Method->isInvalidDecl())
13159     return ExprError();
13160 
13161   const FunctionProtoType *Proto =
13162     Method->getType()->getAs<FunctionProtoType>();
13163 
13164   unsigned NumParams = Proto->getNumParams();
13165 
13166   DeclarationNameInfo OpLocInfo(
13167                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13168   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13169   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13170                                            Obj, HadMultipleCandidates,
13171                                            OpLocInfo.getLoc(),
13172                                            OpLocInfo.getInfo());
13173   if (NewFn.isInvalid())
13174     return true;
13175 
13176   // Build the full argument list for the method call (the implicit object
13177   // parameter is placed at the beginning of the list).
13178   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13179   MethodArgs[0] = Object.get();
13180   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13181 
13182   // Once we've built TheCall, all of the expressions are properly
13183   // owned.
13184   QualType ResultTy = Method->getReturnType();
13185   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13186   ResultTy = ResultTy.getNonLValueExprType(Context);
13187 
13188   CXXOperatorCallExpr *TheCall = new (Context)
13189       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13190                           VK, RParenLoc, FPOptions());
13191 
13192   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13193     return true;
13194 
13195   // We may have default arguments. If so, we need to allocate more
13196   // slots in the call for them.
13197   if (Args.size() < NumParams)
13198     TheCall->setNumArgs(Context, NumParams + 1);
13199 
13200   bool IsError = false;
13201 
13202   // Initialize the implicit object parameter.
13203   ExprResult ObjRes =
13204     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13205                                         Best->FoundDecl, Method);
13206   if (ObjRes.isInvalid())
13207     IsError = true;
13208   else
13209     Object = ObjRes;
13210   TheCall->setArg(0, Object.get());
13211 
13212   // Check the argument types.
13213   for (unsigned i = 0; i != NumParams; i++) {
13214     Expr *Arg;
13215     if (i < Args.size()) {
13216       Arg = Args[i];
13217 
13218       // Pass the argument.
13219 
13220       ExprResult InputInit
13221         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13222                                                     Context,
13223                                                     Method->getParamDecl(i)),
13224                                     SourceLocation(), Arg);
13225 
13226       IsError |= InputInit.isInvalid();
13227       Arg = InputInit.getAs<Expr>();
13228     } else {
13229       ExprResult DefArg
13230         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13231       if (DefArg.isInvalid()) {
13232         IsError = true;
13233         break;
13234       }
13235 
13236       Arg = DefArg.getAs<Expr>();
13237     }
13238 
13239     TheCall->setArg(i + 1, Arg);
13240   }
13241 
13242   // If this is a variadic call, handle args passed through "...".
13243   if (Proto->isVariadic()) {
13244     // Promote the arguments (C99 6.5.2.2p7).
13245     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13246       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13247                                                         nullptr);
13248       IsError |= Arg.isInvalid();
13249       TheCall->setArg(i + 1, Arg.get());
13250     }
13251   }
13252 
13253   if (IsError) return true;
13254 
13255   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13256 
13257   if (CheckFunctionCall(Method, TheCall, Proto))
13258     return true;
13259 
13260   return MaybeBindToTemporary(TheCall);
13261 }
13262 
13263 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13264 ///  (if one exists), where @c Base is an expression of class type and
13265 /// @c Member is the name of the member we're trying to find.
13266 ExprResult
13267 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13268                                bool *NoArrowOperatorFound) {
13269   assert(Base->getType()->isRecordType() &&
13270          "left-hand side must have class type");
13271 
13272   if (checkPlaceholderForOverload(*this, Base))
13273     return ExprError();
13274 
13275   SourceLocation Loc = Base->getExprLoc();
13276 
13277   // C++ [over.ref]p1:
13278   //
13279   //   [...] An expression x->m is interpreted as (x.operator->())->m
13280   //   for a class object x of type T if T::operator->() exists and if
13281   //   the operator is selected as the best match function by the
13282   //   overload resolution mechanism (13.3).
13283   DeclarationName OpName =
13284     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13285   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13286   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13287 
13288   if (RequireCompleteType(Loc, Base->getType(),
13289                           diag::err_typecheck_incomplete_tag, Base))
13290     return ExprError();
13291 
13292   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13293   LookupQualifiedName(R, BaseRecord->getDecl());
13294   R.suppressDiagnostics();
13295 
13296   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13297        Oper != OperEnd; ++Oper) {
13298     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13299                        None, CandidateSet, /*SuppressUserConversions=*/false);
13300   }
13301 
13302   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13303 
13304   // Perform overload resolution.
13305   OverloadCandidateSet::iterator Best;
13306   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13307   case OR_Success:
13308     // Overload resolution succeeded; we'll build the call below.
13309     break;
13310 
13311   case OR_No_Viable_Function:
13312     if (CandidateSet.empty()) {
13313       QualType BaseType = Base->getType();
13314       if (NoArrowOperatorFound) {
13315         // Report this specific error to the caller instead of emitting a
13316         // diagnostic, as requested.
13317         *NoArrowOperatorFound = true;
13318         return ExprError();
13319       }
13320       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13321         << BaseType << Base->getSourceRange();
13322       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13323         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13324           << FixItHint::CreateReplacement(OpLoc, ".");
13325       }
13326     } else
13327       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13328         << "operator->" << Base->getSourceRange();
13329     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13330     return ExprError();
13331 
13332   case OR_Ambiguous:
13333     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13334       << "->" << Base->getType() << Base->getSourceRange();
13335     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13336     return ExprError();
13337 
13338   case OR_Deleted:
13339     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13340       << Best->Function->isDeleted()
13341       << "->"
13342       << getDeletedOrUnavailableSuffix(Best->Function)
13343       << Base->getSourceRange();
13344     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13345     return ExprError();
13346   }
13347 
13348   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13349 
13350   // Convert the object parameter.
13351   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13352   ExprResult BaseResult =
13353     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13354                                         Best->FoundDecl, Method);
13355   if (BaseResult.isInvalid())
13356     return ExprError();
13357   Base = BaseResult.get();
13358 
13359   // Build the operator call.
13360   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13361                                             Base, HadMultipleCandidates, OpLoc);
13362   if (FnExpr.isInvalid())
13363     return ExprError();
13364 
13365   QualType ResultTy = Method->getReturnType();
13366   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13367   ResultTy = ResultTy.getNonLValueExprType(Context);
13368   CXXOperatorCallExpr *TheCall =
13369     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13370                                       Base, ResultTy, VK, OpLoc, FPOptions());
13371 
13372   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13373     return ExprError();
13374 
13375   if (CheckFunctionCall(Method, TheCall,
13376                         Method->getType()->castAs<FunctionProtoType>()))
13377     return ExprError();
13378 
13379   return MaybeBindToTemporary(TheCall);
13380 }
13381 
13382 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13383 /// a literal operator described by the provided lookup results.
13384 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13385                                           DeclarationNameInfo &SuffixInfo,
13386                                           ArrayRef<Expr*> Args,
13387                                           SourceLocation LitEndLoc,
13388                                        TemplateArgumentListInfo *TemplateArgs) {
13389   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13390 
13391   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13392                                     OverloadCandidateSet::CSK_Normal);
13393   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13394                         /*SuppressUserConversions=*/true);
13395 
13396   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13397 
13398   // Perform overload resolution. This will usually be trivial, but might need
13399   // to perform substitutions for a literal operator template.
13400   OverloadCandidateSet::iterator Best;
13401   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13402   case OR_Success:
13403   case OR_Deleted:
13404     break;
13405 
13406   case OR_No_Viable_Function:
13407     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13408       << R.getLookupName();
13409     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13410     return ExprError();
13411 
13412   case OR_Ambiguous:
13413     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13414     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13415     return ExprError();
13416   }
13417 
13418   FunctionDecl *FD = Best->Function;
13419   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13420                                         nullptr, HadMultipleCandidates,
13421                                         SuffixInfo.getLoc(),
13422                                         SuffixInfo.getInfo());
13423   if (Fn.isInvalid())
13424     return true;
13425 
13426   // Check the argument types. This should almost always be a no-op, except
13427   // that array-to-pointer decay is applied to string literals.
13428   Expr *ConvArgs[2];
13429   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13430     ExprResult InputInit = PerformCopyInitialization(
13431       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13432       SourceLocation(), Args[ArgIdx]);
13433     if (InputInit.isInvalid())
13434       return true;
13435     ConvArgs[ArgIdx] = InputInit.get();
13436   }
13437 
13438   QualType ResultTy = FD->getReturnType();
13439   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13440   ResultTy = ResultTy.getNonLValueExprType(Context);
13441 
13442   UserDefinedLiteral *UDL =
13443     new (Context) UserDefinedLiteral(Context, Fn.get(),
13444                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13445                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13446 
13447   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13448     return ExprError();
13449 
13450   if (CheckFunctionCall(FD, UDL, nullptr))
13451     return ExprError();
13452 
13453   return MaybeBindToTemporary(UDL);
13454 }
13455 
13456 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13457 /// given LookupResult is non-empty, it is assumed to describe a member which
13458 /// will be invoked. Otherwise, the function will be found via argument
13459 /// dependent lookup.
13460 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13461 /// otherwise CallExpr is set to ExprError() and some non-success value
13462 /// is returned.
13463 Sema::ForRangeStatus
13464 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13465                                 SourceLocation RangeLoc,
13466                                 const DeclarationNameInfo &NameInfo,
13467                                 LookupResult &MemberLookup,
13468                                 OverloadCandidateSet *CandidateSet,
13469                                 Expr *Range, ExprResult *CallExpr) {
13470   Scope *S = nullptr;
13471 
13472   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13473   if (!MemberLookup.empty()) {
13474     ExprResult MemberRef =
13475         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13476                                  /*IsPtr=*/false, CXXScopeSpec(),
13477                                  /*TemplateKWLoc=*/SourceLocation(),
13478                                  /*FirstQualifierInScope=*/nullptr,
13479                                  MemberLookup,
13480                                  /*TemplateArgs=*/nullptr, S);
13481     if (MemberRef.isInvalid()) {
13482       *CallExpr = ExprError();
13483       return FRS_DiagnosticIssued;
13484     }
13485     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13486     if (CallExpr->isInvalid()) {
13487       *CallExpr = ExprError();
13488       return FRS_DiagnosticIssued;
13489     }
13490   } else {
13491     UnresolvedSet<0> FoundNames;
13492     UnresolvedLookupExpr *Fn =
13493       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13494                                    NestedNameSpecifierLoc(), NameInfo,
13495                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13496                                    FoundNames.begin(), FoundNames.end());
13497 
13498     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13499                                                     CandidateSet, CallExpr);
13500     if (CandidateSet->empty() || CandidateSetError) {
13501       *CallExpr = ExprError();
13502       return FRS_NoViableFunction;
13503     }
13504     OverloadCandidateSet::iterator Best;
13505     OverloadingResult OverloadResult =
13506         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13507 
13508     if (OverloadResult == OR_No_Viable_Function) {
13509       *CallExpr = ExprError();
13510       return FRS_NoViableFunction;
13511     }
13512     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13513                                          Loc, nullptr, CandidateSet, &Best,
13514                                          OverloadResult,
13515                                          /*AllowTypoCorrection=*/false);
13516     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13517       *CallExpr = ExprError();
13518       return FRS_DiagnosticIssued;
13519     }
13520   }
13521   return FRS_Success;
13522 }
13523 
13524 
13525 /// FixOverloadedFunctionReference - E is an expression that refers to
13526 /// a C++ overloaded function (possibly with some parentheses and
13527 /// perhaps a '&' around it). We have resolved the overloaded function
13528 /// to the function declaration Fn, so patch up the expression E to
13529 /// refer (possibly indirectly) to Fn. Returns the new expr.
13530 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13531                                            FunctionDecl *Fn) {
13532   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13533     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13534                                                    Found, Fn);
13535     if (SubExpr == PE->getSubExpr())
13536       return PE;
13537 
13538     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13539   }
13540 
13541   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13542     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13543                                                    Found, Fn);
13544     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13545                                SubExpr->getType()) &&
13546            "Implicit cast type cannot be determined from overload");
13547     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13548     if (SubExpr == ICE->getSubExpr())
13549       return ICE;
13550 
13551     return ImplicitCastExpr::Create(Context, ICE->getType(),
13552                                     ICE->getCastKind(),
13553                                     SubExpr, nullptr,
13554                                     ICE->getValueKind());
13555   }
13556 
13557   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13558     if (!GSE->isResultDependent()) {
13559       Expr *SubExpr =
13560           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13561       if (SubExpr == GSE->getResultExpr())
13562         return GSE;
13563 
13564       // Replace the resulting type information before rebuilding the generic
13565       // selection expression.
13566       ArrayRef<Expr *> A = GSE->getAssocExprs();
13567       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13568       unsigned ResultIdx = GSE->getResultIndex();
13569       AssocExprs[ResultIdx] = SubExpr;
13570 
13571       return new (Context) GenericSelectionExpr(
13572           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13573           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13574           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13575           ResultIdx);
13576     }
13577     // Rather than fall through to the unreachable, return the original generic
13578     // selection expression.
13579     return GSE;
13580   }
13581 
13582   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13583     assert(UnOp->getOpcode() == UO_AddrOf &&
13584            "Can only take the address of an overloaded function");
13585     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13586       if (Method->isStatic()) {
13587         // Do nothing: static member functions aren't any different
13588         // from non-member functions.
13589       } else {
13590         // Fix the subexpression, which really has to be an
13591         // UnresolvedLookupExpr holding an overloaded member function
13592         // or template.
13593         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13594                                                        Found, Fn);
13595         if (SubExpr == UnOp->getSubExpr())
13596           return UnOp;
13597 
13598         assert(isa<DeclRefExpr>(SubExpr)
13599                && "fixed to something other than a decl ref");
13600         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13601                && "fixed to a member ref with no nested name qualifier");
13602 
13603         // We have taken the address of a pointer to member
13604         // function. Perform the computation here so that we get the
13605         // appropriate pointer to member type.
13606         QualType ClassType
13607           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13608         QualType MemPtrType
13609           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13610         // Under the MS ABI, lock down the inheritance model now.
13611         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13612           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13613 
13614         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13615                                            VK_RValue, OK_Ordinary,
13616                                            UnOp->getOperatorLoc(), false);
13617       }
13618     }
13619     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13620                                                    Found, Fn);
13621     if (SubExpr == UnOp->getSubExpr())
13622       return UnOp;
13623 
13624     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13625                                      Context.getPointerType(SubExpr->getType()),
13626                                        VK_RValue, OK_Ordinary,
13627                                        UnOp->getOperatorLoc(), false);
13628   }
13629 
13630   // C++ [except.spec]p17:
13631   //   An exception-specification is considered to be needed when:
13632   //   - in an expression the function is the unique lookup result or the
13633   //     selected member of a set of overloaded functions
13634   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13635     ResolveExceptionSpec(E->getExprLoc(), FPT);
13636 
13637   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13638     // FIXME: avoid copy.
13639     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13640     if (ULE->hasExplicitTemplateArgs()) {
13641       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13642       TemplateArgs = &TemplateArgsBuffer;
13643     }
13644 
13645     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13646                                            ULE->getQualifierLoc(),
13647                                            ULE->getTemplateKeywordLoc(),
13648                                            Fn,
13649                                            /*enclosing*/ false, // FIXME?
13650                                            ULE->getNameLoc(),
13651                                            Fn->getType(),
13652                                            VK_LValue,
13653                                            Found.getDecl(),
13654                                            TemplateArgs);
13655     MarkDeclRefReferenced(DRE);
13656     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13657     return DRE;
13658   }
13659 
13660   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13661     // FIXME: avoid copy.
13662     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13663     if (MemExpr->hasExplicitTemplateArgs()) {
13664       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13665       TemplateArgs = &TemplateArgsBuffer;
13666     }
13667 
13668     Expr *Base;
13669 
13670     // If we're filling in a static method where we used to have an
13671     // implicit member access, rewrite to a simple decl ref.
13672     if (MemExpr->isImplicitAccess()) {
13673       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13674         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13675                                                MemExpr->getQualifierLoc(),
13676                                                MemExpr->getTemplateKeywordLoc(),
13677                                                Fn,
13678                                                /*enclosing*/ false,
13679                                                MemExpr->getMemberLoc(),
13680                                                Fn->getType(),
13681                                                VK_LValue,
13682                                                Found.getDecl(),
13683                                                TemplateArgs);
13684         MarkDeclRefReferenced(DRE);
13685         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13686         return DRE;
13687       } else {
13688         SourceLocation Loc = MemExpr->getMemberLoc();
13689         if (MemExpr->getQualifier())
13690           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13691         CheckCXXThisCapture(Loc);
13692         Base = new (Context) CXXThisExpr(Loc,
13693                                          MemExpr->getBaseType(),
13694                                          /*isImplicit=*/true);
13695       }
13696     } else
13697       Base = MemExpr->getBase();
13698 
13699     ExprValueKind valueKind;
13700     QualType type;
13701     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13702       valueKind = VK_LValue;
13703       type = Fn->getType();
13704     } else {
13705       valueKind = VK_RValue;
13706       type = Context.BoundMemberTy;
13707     }
13708 
13709     MemberExpr *ME = MemberExpr::Create(
13710         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13711         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13712         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13713         OK_Ordinary);
13714     ME->setHadMultipleCandidates(true);
13715     MarkMemberReferenced(ME);
13716     return ME;
13717   }
13718 
13719   llvm_unreachable("Invalid reference to overloaded function");
13720 }
13721 
13722 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13723                                                 DeclAccessPair Found,
13724                                                 FunctionDecl *Fn) {
13725   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13726 }
13727