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   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5411                                    ? Expr::EvaluateForMangling
5412                                    : Expr::EvaluateForCodeGen;
5413 
5414   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5415       (RequireInt && !Eval.Val.isInt())) {
5416     // The expression can't be folded, so we can't keep it at this position in
5417     // the AST.
5418     Result = ExprError();
5419   } else {
5420     Value = Eval.Val;
5421 
5422     if (Notes.empty()) {
5423       // It's a constant expression.
5424       return Result;
5425     }
5426   }
5427 
5428   // It's not a constant expression. Produce an appropriate diagnostic.
5429   if (Notes.size() == 1 &&
5430       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5431     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5432   else {
5433     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5434       << CCE << From->getSourceRange();
5435     for (unsigned I = 0; I < Notes.size(); ++I)
5436       S.Diag(Notes[I].first, Notes[I].second);
5437   }
5438   return ExprError();
5439 }
5440 
5441 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5442                                                   APValue &Value, CCEKind CCE) {
5443   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5444 }
5445 
5446 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5447                                                   llvm::APSInt &Value,
5448                                                   CCEKind CCE) {
5449   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5450 
5451   APValue V;
5452   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5453   if (!R.isInvalid() && !R.get()->isValueDependent())
5454     Value = V.getInt();
5455   return R;
5456 }
5457 
5458 
5459 /// dropPointerConversions - If the given standard conversion sequence
5460 /// involves any pointer conversions, remove them.  This may change
5461 /// the result type of the conversion sequence.
5462 static void dropPointerConversion(StandardConversionSequence &SCS) {
5463   if (SCS.Second == ICK_Pointer_Conversion) {
5464     SCS.Second = ICK_Identity;
5465     SCS.Third = ICK_Identity;
5466     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5467   }
5468 }
5469 
5470 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5471 /// convert the expression From to an Objective-C pointer type.
5472 static ImplicitConversionSequence
5473 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5474   // Do an implicit conversion to 'id'.
5475   QualType Ty = S.Context.getObjCIdType();
5476   ImplicitConversionSequence ICS
5477     = TryImplicitConversion(S, From, Ty,
5478                             // FIXME: Are these flags correct?
5479                             /*SuppressUserConversions=*/false,
5480                             /*AllowExplicit=*/true,
5481                             /*InOverloadResolution=*/false,
5482                             /*CStyle=*/false,
5483                             /*AllowObjCWritebackConversion=*/false,
5484                             /*AllowObjCConversionOnExplicit=*/true);
5485 
5486   // Strip off any final conversions to 'id'.
5487   switch (ICS.getKind()) {
5488   case ImplicitConversionSequence::BadConversion:
5489   case ImplicitConversionSequence::AmbiguousConversion:
5490   case ImplicitConversionSequence::EllipsisConversion:
5491     break;
5492 
5493   case ImplicitConversionSequence::UserDefinedConversion:
5494     dropPointerConversion(ICS.UserDefined.After);
5495     break;
5496 
5497   case ImplicitConversionSequence::StandardConversion:
5498     dropPointerConversion(ICS.Standard);
5499     break;
5500   }
5501 
5502   return ICS;
5503 }
5504 
5505 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5506 /// conversion of the expression From to an Objective-C pointer type.
5507 /// Returns a valid but null ExprResult if no conversion sequence exists.
5508 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5509   if (checkPlaceholderForOverload(*this, From))
5510     return ExprError();
5511 
5512   QualType Ty = Context.getObjCIdType();
5513   ImplicitConversionSequence ICS =
5514     TryContextuallyConvertToObjCPointer(*this, From);
5515   if (!ICS.isBad())
5516     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5517   return ExprResult();
5518 }
5519 
5520 /// Determine whether the provided type is an integral type, or an enumeration
5521 /// type of a permitted flavor.
5522 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5523   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5524                                  : T->isIntegralOrUnscopedEnumerationType();
5525 }
5526 
5527 static ExprResult
5528 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5529                             Sema::ContextualImplicitConverter &Converter,
5530                             QualType T, UnresolvedSetImpl &ViableConversions) {
5531 
5532   if (Converter.Suppress)
5533     return ExprError();
5534 
5535   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5536   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5537     CXXConversionDecl *Conv =
5538         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5539     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5540     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5541   }
5542   return From;
5543 }
5544 
5545 static bool
5546 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5547                            Sema::ContextualImplicitConverter &Converter,
5548                            QualType T, bool HadMultipleCandidates,
5549                            UnresolvedSetImpl &ExplicitConversions) {
5550   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5551     DeclAccessPair Found = ExplicitConversions[0];
5552     CXXConversionDecl *Conversion =
5553         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5554 
5555     // The user probably meant to invoke the given explicit
5556     // conversion; use it.
5557     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5558     std::string TypeStr;
5559     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5560 
5561     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5562         << FixItHint::CreateInsertion(From->getLocStart(),
5563                                       "static_cast<" + TypeStr + ">(")
5564         << FixItHint::CreateInsertion(
5565                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5566     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5567 
5568     // If we aren't in a SFINAE context, build a call to the
5569     // explicit conversion function.
5570     if (SemaRef.isSFINAEContext())
5571       return true;
5572 
5573     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5574     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5575                                                        HadMultipleCandidates);
5576     if (Result.isInvalid())
5577       return true;
5578     // Record usage of conversion in an implicit cast.
5579     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5580                                     CK_UserDefinedConversion, Result.get(),
5581                                     nullptr, Result.get()->getValueKind());
5582   }
5583   return false;
5584 }
5585 
5586 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5587                              Sema::ContextualImplicitConverter &Converter,
5588                              QualType T, bool HadMultipleCandidates,
5589                              DeclAccessPair &Found) {
5590   CXXConversionDecl *Conversion =
5591       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5592   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5593 
5594   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5595   if (!Converter.SuppressConversion) {
5596     if (SemaRef.isSFINAEContext())
5597       return true;
5598 
5599     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5600         << From->getSourceRange();
5601   }
5602 
5603   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5604                                                      HadMultipleCandidates);
5605   if (Result.isInvalid())
5606     return true;
5607   // Record usage of conversion in an implicit cast.
5608   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5609                                   CK_UserDefinedConversion, Result.get(),
5610                                   nullptr, Result.get()->getValueKind());
5611   return false;
5612 }
5613 
5614 static ExprResult finishContextualImplicitConversion(
5615     Sema &SemaRef, SourceLocation Loc, Expr *From,
5616     Sema::ContextualImplicitConverter &Converter) {
5617   if (!Converter.match(From->getType()) && !Converter.Suppress)
5618     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5619         << From->getSourceRange();
5620 
5621   return SemaRef.DefaultLvalueConversion(From);
5622 }
5623 
5624 static void
5625 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5626                                   UnresolvedSetImpl &ViableConversions,
5627                                   OverloadCandidateSet &CandidateSet) {
5628   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5629     DeclAccessPair FoundDecl = ViableConversions[I];
5630     NamedDecl *D = FoundDecl.getDecl();
5631     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5632     if (isa<UsingShadowDecl>(D))
5633       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5634 
5635     CXXConversionDecl *Conv;
5636     FunctionTemplateDecl *ConvTemplate;
5637     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5638       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5639     else
5640       Conv = cast<CXXConversionDecl>(D);
5641 
5642     if (ConvTemplate)
5643       SemaRef.AddTemplateConversionCandidate(
5644         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5645         /*AllowObjCConversionOnExplicit=*/false);
5646     else
5647       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5648                                      ToType, CandidateSet,
5649                                      /*AllowObjCConversionOnExplicit=*/false);
5650   }
5651 }
5652 
5653 /// Attempt to convert the given expression to a type which is accepted
5654 /// by the given converter.
5655 ///
5656 /// This routine will attempt to convert an expression of class type to a
5657 /// type accepted by the specified converter. In C++11 and before, the class
5658 /// must have a single non-explicit conversion function converting to a matching
5659 /// type. In C++1y, there can be multiple such conversion functions, but only
5660 /// one target type.
5661 ///
5662 /// \param Loc The source location of the construct that requires the
5663 /// conversion.
5664 ///
5665 /// \param From The expression we're converting from.
5666 ///
5667 /// \param Converter Used to control and diagnose the conversion process.
5668 ///
5669 /// \returns The expression, converted to an integral or enumeration type if
5670 /// successful.
5671 ExprResult Sema::PerformContextualImplicitConversion(
5672     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5673   // We can't perform any more checking for type-dependent expressions.
5674   if (From->isTypeDependent())
5675     return From;
5676 
5677   // Process placeholders immediately.
5678   if (From->hasPlaceholderType()) {
5679     ExprResult result = CheckPlaceholderExpr(From);
5680     if (result.isInvalid())
5681       return result;
5682     From = result.get();
5683   }
5684 
5685   // If the expression already has a matching type, we're golden.
5686   QualType T = From->getType();
5687   if (Converter.match(T))
5688     return DefaultLvalueConversion(From);
5689 
5690   // FIXME: Check for missing '()' if T is a function type?
5691 
5692   // We can only perform contextual implicit conversions on objects of class
5693   // type.
5694   const RecordType *RecordTy = T->getAs<RecordType>();
5695   if (!RecordTy || !getLangOpts().CPlusPlus) {
5696     if (!Converter.Suppress)
5697       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5698     return From;
5699   }
5700 
5701   // We must have a complete class type.
5702   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5703     ContextualImplicitConverter &Converter;
5704     Expr *From;
5705 
5706     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5707         : Converter(Converter), From(From) {}
5708 
5709     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5710       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5711     }
5712   } IncompleteDiagnoser(Converter, From);
5713 
5714   if (Converter.Suppress ? !isCompleteType(Loc, T)
5715                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5716     return From;
5717 
5718   // Look for a conversion to an integral or enumeration type.
5719   UnresolvedSet<4>
5720       ViableConversions; // These are *potentially* viable in C++1y.
5721   UnresolvedSet<4> ExplicitConversions;
5722   const auto &Conversions =
5723       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5724 
5725   bool HadMultipleCandidates =
5726       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5727 
5728   // To check that there is only one target type, in C++1y:
5729   QualType ToType;
5730   bool HasUniqueTargetType = true;
5731 
5732   // Collect explicit or viable (potentially in C++1y) conversions.
5733   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5734     NamedDecl *D = (*I)->getUnderlyingDecl();
5735     CXXConversionDecl *Conversion;
5736     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5737     if (ConvTemplate) {
5738       if (getLangOpts().CPlusPlus14)
5739         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5740       else
5741         continue; // C++11 does not consider conversion operator templates(?).
5742     } else
5743       Conversion = cast<CXXConversionDecl>(D);
5744 
5745     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5746            "Conversion operator templates are considered potentially "
5747            "viable in C++1y");
5748 
5749     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5750     if (Converter.match(CurToType) || ConvTemplate) {
5751 
5752       if (Conversion->isExplicit()) {
5753         // FIXME: For C++1y, do we need this restriction?
5754         // cf. diagnoseNoViableConversion()
5755         if (!ConvTemplate)
5756           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5757       } else {
5758         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5759           if (ToType.isNull())
5760             ToType = CurToType.getUnqualifiedType();
5761           else if (HasUniqueTargetType &&
5762                    (CurToType.getUnqualifiedType() != ToType))
5763             HasUniqueTargetType = false;
5764         }
5765         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5766       }
5767     }
5768   }
5769 
5770   if (getLangOpts().CPlusPlus14) {
5771     // C++1y [conv]p6:
5772     // ... An expression e of class type E appearing in such a context
5773     // is said to be contextually implicitly converted to a specified
5774     // type T and is well-formed if and only if e can be implicitly
5775     // converted to a type T that is determined as follows: E is searched
5776     // for conversion functions whose return type is cv T or reference to
5777     // cv T such that T is allowed by the context. There shall be
5778     // exactly one such T.
5779 
5780     // If no unique T is found:
5781     if (ToType.isNull()) {
5782       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5783                                      HadMultipleCandidates,
5784                                      ExplicitConversions))
5785         return ExprError();
5786       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5787     }
5788 
5789     // If more than one unique Ts are found:
5790     if (!HasUniqueTargetType)
5791       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5792                                          ViableConversions);
5793 
5794     // If one unique T is found:
5795     // First, build a candidate set from the previously recorded
5796     // potentially viable conversions.
5797     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5798     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5799                                       CandidateSet);
5800 
5801     // Then, perform overload resolution over the candidate set.
5802     OverloadCandidateSet::iterator Best;
5803     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5804     case OR_Success: {
5805       // Apply this conversion.
5806       DeclAccessPair Found =
5807           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5808       if (recordConversion(*this, Loc, From, Converter, T,
5809                            HadMultipleCandidates, Found))
5810         return ExprError();
5811       break;
5812     }
5813     case OR_Ambiguous:
5814       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5815                                          ViableConversions);
5816     case OR_No_Viable_Function:
5817       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5818                                      HadMultipleCandidates,
5819                                      ExplicitConversions))
5820         return ExprError();
5821       LLVM_FALLTHROUGH;
5822     case OR_Deleted:
5823       // We'll complain below about a non-integral condition type.
5824       break;
5825     }
5826   } else {
5827     switch (ViableConversions.size()) {
5828     case 0: {
5829       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5830                                      HadMultipleCandidates,
5831                                      ExplicitConversions))
5832         return ExprError();
5833 
5834       // We'll complain below about a non-integral condition type.
5835       break;
5836     }
5837     case 1: {
5838       // Apply this conversion.
5839       DeclAccessPair Found = ViableConversions[0];
5840       if (recordConversion(*this, Loc, From, Converter, T,
5841                            HadMultipleCandidates, Found))
5842         return ExprError();
5843       break;
5844     }
5845     default:
5846       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5847                                          ViableConversions);
5848     }
5849   }
5850 
5851   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5852 }
5853 
5854 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5855 /// an acceptable non-member overloaded operator for a call whose
5856 /// arguments have types T1 (and, if non-empty, T2). This routine
5857 /// implements the check in C++ [over.match.oper]p3b2 concerning
5858 /// enumeration types.
5859 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5860                                                    FunctionDecl *Fn,
5861                                                    ArrayRef<Expr *> Args) {
5862   QualType T1 = Args[0]->getType();
5863   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5864 
5865   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5866     return true;
5867 
5868   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5869     return true;
5870 
5871   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5872   if (Proto->getNumParams() < 1)
5873     return false;
5874 
5875   if (T1->isEnumeralType()) {
5876     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5877     if (Context.hasSameUnqualifiedType(T1, ArgType))
5878       return true;
5879   }
5880 
5881   if (Proto->getNumParams() < 2)
5882     return false;
5883 
5884   if (!T2.isNull() && T2->isEnumeralType()) {
5885     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5886     if (Context.hasSameUnqualifiedType(T2, ArgType))
5887       return true;
5888   }
5889 
5890   return false;
5891 }
5892 
5893 /// AddOverloadCandidate - Adds the given function to the set of
5894 /// candidate functions, using the given function call arguments.  If
5895 /// @p SuppressUserConversions, then don't allow user-defined
5896 /// conversions via constructors or conversion operators.
5897 ///
5898 /// \param PartialOverloading true if we are performing "partial" overloading
5899 /// based on an incomplete set of function arguments. This feature is used by
5900 /// code completion.
5901 void
5902 Sema::AddOverloadCandidate(FunctionDecl *Function,
5903                            DeclAccessPair FoundDecl,
5904                            ArrayRef<Expr *> Args,
5905                            OverloadCandidateSet &CandidateSet,
5906                            bool SuppressUserConversions,
5907                            bool PartialOverloading,
5908                            bool AllowExplicit,
5909                            ConversionSequenceList EarlyConversions) {
5910   const FunctionProtoType *Proto
5911     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5912   assert(Proto && "Functions without a prototype cannot be overloaded");
5913   assert(!Function->getDescribedFunctionTemplate() &&
5914          "Use AddTemplateOverloadCandidate for function templates");
5915 
5916   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5917     if (!isa<CXXConstructorDecl>(Method)) {
5918       // If we get here, it's because we're calling a member function
5919       // that is named without a member access expression (e.g.,
5920       // "this->f") that was either written explicitly or created
5921       // implicitly. This can happen with a qualified call to a member
5922       // function, e.g., X::f(). We use an empty type for the implied
5923       // object argument (C++ [over.call.func]p3), and the acting context
5924       // is irrelevant.
5925       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5926                          Expr::Classification::makeSimpleLValue(), Args,
5927                          CandidateSet, SuppressUserConversions,
5928                          PartialOverloading, EarlyConversions);
5929       return;
5930     }
5931     // We treat a constructor like a non-member function, since its object
5932     // argument doesn't participate in overload resolution.
5933   }
5934 
5935   if (!CandidateSet.isNewCandidate(Function))
5936     return;
5937 
5938   // C++ [over.match.oper]p3:
5939   //   if no operand has a class type, only those non-member functions in the
5940   //   lookup set that have a first parameter of type T1 or "reference to
5941   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5942   //   is a right operand) a second parameter of type T2 or "reference to
5943   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5944   //   candidate functions.
5945   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5946       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5947     return;
5948 
5949   // C++11 [class.copy]p11: [DR1402]
5950   //   A defaulted move constructor that is defined as deleted is ignored by
5951   //   overload resolution.
5952   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5953   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5954       Constructor->isMoveConstructor())
5955     return;
5956 
5957   // Overload resolution is always an unevaluated context.
5958   EnterExpressionEvaluationContext Unevaluated(
5959       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5960 
5961   // Add this candidate
5962   OverloadCandidate &Candidate =
5963       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5964   Candidate.FoundDecl = FoundDecl;
5965   Candidate.Function = Function;
5966   Candidate.Viable = true;
5967   Candidate.IsSurrogate = false;
5968   Candidate.IgnoreObjectArgument = false;
5969   Candidate.ExplicitCallArguments = Args.size();
5970 
5971   if (Function->isMultiVersion() &&
5972       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5973     Candidate.Viable = false;
5974     Candidate.FailureKind = ovl_non_default_multiversion_function;
5975     return;
5976   }
5977 
5978   if (Constructor) {
5979     // C++ [class.copy]p3:
5980     //   A member function template is never instantiated to perform the copy
5981     //   of a class object to an object of its class type.
5982     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5983     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5984         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5985          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5986                        ClassType))) {
5987       Candidate.Viable = false;
5988       Candidate.FailureKind = ovl_fail_illegal_constructor;
5989       return;
5990     }
5991 
5992     // C++ [over.match.funcs]p8: (proposed DR resolution)
5993     //   A constructor inherited from class type C that has a first parameter
5994     //   of type "reference to P" (including such a constructor instantiated
5995     //   from a template) is excluded from the set of candidate functions when
5996     //   constructing an object of type cv D if the argument list has exactly
5997     //   one argument and D is reference-related to P and P is reference-related
5998     //   to C.
5999     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6000     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6001         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6002       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6003       QualType C = Context.getRecordType(Constructor->getParent());
6004       QualType D = Context.getRecordType(Shadow->getParent());
6005       SourceLocation Loc = Args.front()->getExprLoc();
6006       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6007           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6008         Candidate.Viable = false;
6009         Candidate.FailureKind = ovl_fail_inhctor_slice;
6010         return;
6011       }
6012     }
6013   }
6014 
6015   unsigned NumParams = Proto->getNumParams();
6016 
6017   // (C++ 13.3.2p2): A candidate function having fewer than m
6018   // parameters is viable only if it has an ellipsis in its parameter
6019   // list (8.3.5).
6020   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6021       !Proto->isVariadic()) {
6022     Candidate.Viable = false;
6023     Candidate.FailureKind = ovl_fail_too_many_arguments;
6024     return;
6025   }
6026 
6027   // (C++ 13.3.2p2): A candidate function having more than m parameters
6028   // is viable only if the (m+1)st parameter has a default argument
6029   // (8.3.6). For the purposes of overload resolution, the
6030   // parameter list is truncated on the right, so that there are
6031   // exactly m parameters.
6032   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6033   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6034     // Not enough arguments.
6035     Candidate.Viable = false;
6036     Candidate.FailureKind = ovl_fail_too_few_arguments;
6037     return;
6038   }
6039 
6040   // (CUDA B.1): Check for invalid calls between targets.
6041   if (getLangOpts().CUDA)
6042     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6043       // Skip the check for callers that are implicit members, because in this
6044       // case we may not yet know what the member's target is; the target is
6045       // inferred for the member automatically, based on the bases and fields of
6046       // the class.
6047       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6048         Candidate.Viable = false;
6049         Candidate.FailureKind = ovl_fail_bad_target;
6050         return;
6051       }
6052 
6053   // Determine the implicit conversion sequences for each of the
6054   // arguments.
6055   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6056     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6057       // We already formed a conversion sequence for this parameter during
6058       // template argument deduction.
6059     } else if (ArgIdx < NumParams) {
6060       // (C++ 13.3.2p3): for F to be a viable function, there shall
6061       // exist for each argument an implicit conversion sequence
6062       // (13.3.3.1) that converts that argument to the corresponding
6063       // parameter of F.
6064       QualType ParamType = Proto->getParamType(ArgIdx);
6065       Candidate.Conversions[ArgIdx]
6066         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6067                                 SuppressUserConversions,
6068                                 /*InOverloadResolution=*/true,
6069                                 /*AllowObjCWritebackConversion=*/
6070                                   getLangOpts().ObjCAutoRefCount,
6071                                 AllowExplicit);
6072       if (Candidate.Conversions[ArgIdx].isBad()) {
6073         Candidate.Viable = false;
6074         Candidate.FailureKind = ovl_fail_bad_conversion;
6075         return;
6076       }
6077     } else {
6078       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6079       // argument for which there is no corresponding parameter is
6080       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6081       Candidate.Conversions[ArgIdx].setEllipsis();
6082     }
6083   }
6084 
6085   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6086     Candidate.Viable = false;
6087     Candidate.FailureKind = ovl_fail_enable_if;
6088     Candidate.DeductionFailure.Data = FailedAttr;
6089     return;
6090   }
6091 
6092   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6093     Candidate.Viable = false;
6094     Candidate.FailureKind = ovl_fail_ext_disabled;
6095     return;
6096   }
6097 }
6098 
6099 ObjCMethodDecl *
6100 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6101                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6102   if (Methods.size() <= 1)
6103     return nullptr;
6104 
6105   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6106     bool Match = true;
6107     ObjCMethodDecl *Method = Methods[b];
6108     unsigned NumNamedArgs = Sel.getNumArgs();
6109     // Method might have more arguments than selector indicates. This is due
6110     // to addition of c-style arguments in method.
6111     if (Method->param_size() > NumNamedArgs)
6112       NumNamedArgs = Method->param_size();
6113     if (Args.size() < NumNamedArgs)
6114       continue;
6115 
6116     for (unsigned i = 0; i < NumNamedArgs; i++) {
6117       // We can't do any type-checking on a type-dependent argument.
6118       if (Args[i]->isTypeDependent()) {
6119         Match = false;
6120         break;
6121       }
6122 
6123       ParmVarDecl *param = Method->parameters()[i];
6124       Expr *argExpr = Args[i];
6125       assert(argExpr && "SelectBestMethod(): missing expression");
6126 
6127       // Strip the unbridged-cast placeholder expression off unless it's
6128       // a consumed argument.
6129       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6130           !param->hasAttr<CFConsumedAttr>())
6131         argExpr = stripARCUnbridgedCast(argExpr);
6132 
6133       // If the parameter is __unknown_anytype, move on to the next method.
6134       if (param->getType() == Context.UnknownAnyTy) {
6135         Match = false;
6136         break;
6137       }
6138 
6139       ImplicitConversionSequence ConversionState
6140         = TryCopyInitialization(*this, argExpr, param->getType(),
6141                                 /*SuppressUserConversions*/false,
6142                                 /*InOverloadResolution=*/true,
6143                                 /*AllowObjCWritebackConversion=*/
6144                                 getLangOpts().ObjCAutoRefCount,
6145                                 /*AllowExplicit*/false);
6146       // This function looks for a reasonably-exact match, so we consider
6147       // incompatible pointer conversions to be a failure here.
6148       if (ConversionState.isBad() ||
6149           (ConversionState.isStandard() &&
6150            ConversionState.Standard.Second ==
6151                ICK_Incompatible_Pointer_Conversion)) {
6152         Match = false;
6153         break;
6154       }
6155     }
6156     // Promote additional arguments to variadic methods.
6157     if (Match && Method->isVariadic()) {
6158       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6159         if (Args[i]->isTypeDependent()) {
6160           Match = false;
6161           break;
6162         }
6163         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6164                                                           nullptr);
6165         if (Arg.isInvalid()) {
6166           Match = false;
6167           break;
6168         }
6169       }
6170     } else {
6171       // Check for extra arguments to non-variadic methods.
6172       if (Args.size() != NumNamedArgs)
6173         Match = false;
6174       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6175         // Special case when selectors have no argument. In this case, select
6176         // one with the most general result type of 'id'.
6177         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6178           QualType ReturnT = Methods[b]->getReturnType();
6179           if (ReturnT->isObjCIdType())
6180             return Methods[b];
6181         }
6182       }
6183     }
6184 
6185     if (Match)
6186       return Method;
6187   }
6188   return nullptr;
6189 }
6190 
6191 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6192 // enable_if is order-sensitive. As a result, we need to reverse things
6193 // sometimes. Size of 4 elements is arbitrary.
6194 static SmallVector<EnableIfAttr *, 4>
6195 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6196   SmallVector<EnableIfAttr *, 4> Result;
6197   if (!Function->hasAttrs())
6198     return Result;
6199 
6200   const auto &FuncAttrs = Function->getAttrs();
6201   for (Attr *Attr : FuncAttrs)
6202     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6203       Result.push_back(EnableIf);
6204 
6205   std::reverse(Result.begin(), Result.end());
6206   return Result;
6207 }
6208 
6209 static bool
6210 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6211                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6212                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6213                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6214   if (ThisArg) {
6215     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6216     assert(!isa<CXXConstructorDecl>(Method) &&
6217            "Shouldn't have `this` for ctors!");
6218     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6219     ExprResult R = S.PerformObjectArgumentInitialization(
6220         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6221     if (R.isInvalid())
6222       return false;
6223     ConvertedThis = R.get();
6224   } else {
6225     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6226       (void)MD;
6227       assert((MissingImplicitThis || MD->isStatic() ||
6228               isa<CXXConstructorDecl>(MD)) &&
6229              "Expected `this` for non-ctor instance methods");
6230     }
6231     ConvertedThis = nullptr;
6232   }
6233 
6234   // Ignore any variadic arguments. Converting them is pointless, since the
6235   // user can't refer to them in the function condition.
6236   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6237 
6238   // Convert the arguments.
6239   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6240     ExprResult R;
6241     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6242                                         S.Context, Function->getParamDecl(I)),
6243                                     SourceLocation(), Args[I]);
6244 
6245     if (R.isInvalid())
6246       return false;
6247 
6248     ConvertedArgs.push_back(R.get());
6249   }
6250 
6251   if (Trap.hasErrorOccurred())
6252     return false;
6253 
6254   // Push default arguments if needed.
6255   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6256     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6257       ParmVarDecl *P = Function->getParamDecl(i);
6258       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6259                          ? P->getUninstantiatedDefaultArg()
6260                          : P->getDefaultArg();
6261       // This can only happen in code completion, i.e. when PartialOverloading
6262       // is true.
6263       if (!DefArg)
6264         return false;
6265       ExprResult R =
6266           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6267                                           S.Context, Function->getParamDecl(i)),
6268                                       SourceLocation(), DefArg);
6269       if (R.isInvalid())
6270         return false;
6271       ConvertedArgs.push_back(R.get());
6272     }
6273 
6274     if (Trap.hasErrorOccurred())
6275       return false;
6276   }
6277   return true;
6278 }
6279 
6280 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6281                                   bool MissingImplicitThis) {
6282   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6283       getOrderedEnableIfAttrs(Function);
6284   if (EnableIfAttrs.empty())
6285     return nullptr;
6286 
6287   SFINAETrap Trap(*this);
6288   SmallVector<Expr *, 16> ConvertedArgs;
6289   // FIXME: We should look into making enable_if late-parsed.
6290   Expr *DiscardedThis;
6291   if (!convertArgsForAvailabilityChecks(
6292           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6293           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6294     return EnableIfAttrs[0];
6295 
6296   for (auto *EIA : EnableIfAttrs) {
6297     APValue Result;
6298     // FIXME: This doesn't consider value-dependent cases, because doing so is
6299     // very difficult. Ideally, we should handle them more gracefully.
6300     if (!EIA->getCond()->EvaluateWithSubstitution(
6301             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6302       return EIA;
6303 
6304     if (!Result.isInt() || !Result.getInt().getBoolValue())
6305       return EIA;
6306   }
6307   return nullptr;
6308 }
6309 
6310 template <typename CheckFn>
6311 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6312                                         bool ArgDependent, SourceLocation Loc,
6313                                         CheckFn &&IsSuccessful) {
6314   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6315   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6316     if (ArgDependent == DIA->getArgDependent())
6317       Attrs.push_back(DIA);
6318   }
6319 
6320   // Common case: No diagnose_if attributes, so we can quit early.
6321   if (Attrs.empty())
6322     return false;
6323 
6324   auto WarningBegin = std::stable_partition(
6325       Attrs.begin(), Attrs.end(),
6326       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6327 
6328   // Note that diagnose_if attributes are late-parsed, so they appear in the
6329   // correct order (unlike enable_if attributes).
6330   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6331                                IsSuccessful);
6332   if (ErrAttr != WarningBegin) {
6333     const DiagnoseIfAttr *DIA = *ErrAttr;
6334     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6335     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6336         << DIA->getParent() << DIA->getCond()->getSourceRange();
6337     return true;
6338   }
6339 
6340   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6341     if (IsSuccessful(DIA)) {
6342       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6343       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6344           << DIA->getParent() << DIA->getCond()->getSourceRange();
6345     }
6346 
6347   return false;
6348 }
6349 
6350 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6351                                                const Expr *ThisArg,
6352                                                ArrayRef<const Expr *> Args,
6353                                                SourceLocation Loc) {
6354   return diagnoseDiagnoseIfAttrsWith(
6355       *this, Function, /*ArgDependent=*/true, Loc,
6356       [&](const DiagnoseIfAttr *DIA) {
6357         APValue Result;
6358         // It's sane to use the same Args for any redecl of this function, since
6359         // EvaluateWithSubstitution only cares about the position of each
6360         // argument in the arg list, not the ParmVarDecl* it maps to.
6361         if (!DIA->getCond()->EvaluateWithSubstitution(
6362                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6363           return false;
6364         return Result.isInt() && Result.getInt().getBoolValue();
6365       });
6366 }
6367 
6368 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6369                                                  SourceLocation Loc) {
6370   return diagnoseDiagnoseIfAttrsWith(
6371       *this, ND, /*ArgDependent=*/false, Loc,
6372       [&](const DiagnoseIfAttr *DIA) {
6373         bool Result;
6374         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6375                Result;
6376       });
6377 }
6378 
6379 /// Add all of the function declarations in the given function set to
6380 /// the overload candidate set.
6381 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6382                                  ArrayRef<Expr *> Args,
6383                                  OverloadCandidateSet& CandidateSet,
6384                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6385                                  bool SuppressUserConversions,
6386                                  bool PartialOverloading,
6387                                  bool FirstArgumentIsBase) {
6388   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6389     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6390     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6391       ArrayRef<Expr *> FunctionArgs = Args;
6392       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6393         QualType ObjectType;
6394         Expr::Classification ObjectClassification;
6395         if (Args.size() > 0) {
6396           if (Expr *E = Args[0]) {
6397             // Use the explicit base to restrict the lookup:
6398             ObjectType = E->getType();
6399             ObjectClassification = E->Classify(Context);
6400           } // .. else there is an implit base.
6401           FunctionArgs = Args.slice(1);
6402         }
6403         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6404                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6405                            ObjectClassification, FunctionArgs, CandidateSet,
6406                            SuppressUserConversions, PartialOverloading);
6407       } else {
6408         // Slice the first argument (which is the base) when we access
6409         // static method as non-static
6410         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6411                                              !isa<CXXConstructorDecl>(FD)))) {
6412           assert(cast<CXXMethodDecl>(FD)->isStatic());
6413           FunctionArgs = Args.slice(1);
6414         }
6415         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6416                              SuppressUserConversions, PartialOverloading);
6417       }
6418     } else {
6419       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6420       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6421           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6422         QualType ObjectType;
6423         Expr::Classification ObjectClassification;
6424         if (Expr *E = Args[0]) {
6425           // Use the explicit base to restrict the lookup:
6426           ObjectType = E->getType();
6427           ObjectClassification = E->Classify(Context);
6428         } // .. else there is an implit base.
6429         AddMethodTemplateCandidate(
6430             FunTmpl, F.getPair(),
6431             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6432             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6433             Args.slice(1), CandidateSet, SuppressUserConversions,
6434             PartialOverloading);
6435       } else {
6436         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6437                                      ExplicitTemplateArgs, Args,
6438                                      CandidateSet, SuppressUserConversions,
6439                                      PartialOverloading);
6440       }
6441     }
6442   }
6443 }
6444 
6445 /// AddMethodCandidate - Adds a named decl (which is some kind of
6446 /// method) as a method candidate to the given overload set.
6447 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6448                               QualType ObjectType,
6449                               Expr::Classification ObjectClassification,
6450                               ArrayRef<Expr *> Args,
6451                               OverloadCandidateSet& CandidateSet,
6452                               bool SuppressUserConversions) {
6453   NamedDecl *Decl = FoundDecl.getDecl();
6454   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6455 
6456   if (isa<UsingShadowDecl>(Decl))
6457     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6458 
6459   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6460     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6461            "Expected a member function template");
6462     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6463                                /*ExplicitArgs*/ nullptr, ObjectType,
6464                                ObjectClassification, Args, CandidateSet,
6465                                SuppressUserConversions);
6466   } else {
6467     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6468                        ObjectType, ObjectClassification, Args, CandidateSet,
6469                        SuppressUserConversions);
6470   }
6471 }
6472 
6473 /// AddMethodCandidate - Adds the given C++ member function to the set
6474 /// of candidate functions, using the given function call arguments
6475 /// and the object argument (@c Object). For example, in a call
6476 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6477 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6478 /// allow user-defined conversions via constructors or conversion
6479 /// operators.
6480 void
6481 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6482                          CXXRecordDecl *ActingContext, QualType ObjectType,
6483                          Expr::Classification ObjectClassification,
6484                          ArrayRef<Expr *> Args,
6485                          OverloadCandidateSet &CandidateSet,
6486                          bool SuppressUserConversions,
6487                          bool PartialOverloading,
6488                          ConversionSequenceList EarlyConversions) {
6489   const FunctionProtoType *Proto
6490     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6491   assert(Proto && "Methods without a prototype cannot be overloaded");
6492   assert(!isa<CXXConstructorDecl>(Method) &&
6493          "Use AddOverloadCandidate for constructors");
6494 
6495   if (!CandidateSet.isNewCandidate(Method))
6496     return;
6497 
6498   // C++11 [class.copy]p23: [DR1402]
6499   //   A defaulted move assignment operator that is defined as deleted is
6500   //   ignored by overload resolution.
6501   if (Method->isDefaulted() && Method->isDeleted() &&
6502       Method->isMoveAssignmentOperator())
6503     return;
6504 
6505   // Overload resolution is always an unevaluated context.
6506   EnterExpressionEvaluationContext Unevaluated(
6507       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6508 
6509   // Add this candidate
6510   OverloadCandidate &Candidate =
6511       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6512   Candidate.FoundDecl = FoundDecl;
6513   Candidate.Function = Method;
6514   Candidate.IsSurrogate = false;
6515   Candidate.IgnoreObjectArgument = false;
6516   Candidate.ExplicitCallArguments = Args.size();
6517 
6518   unsigned NumParams = Proto->getNumParams();
6519 
6520   // (C++ 13.3.2p2): A candidate function having fewer than m
6521   // parameters is viable only if it has an ellipsis in its parameter
6522   // list (8.3.5).
6523   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6524       !Proto->isVariadic()) {
6525     Candidate.Viable = false;
6526     Candidate.FailureKind = ovl_fail_too_many_arguments;
6527     return;
6528   }
6529 
6530   // (C++ 13.3.2p2): A candidate function having more than m parameters
6531   // is viable only if the (m+1)st parameter has a default argument
6532   // (8.3.6). For the purposes of overload resolution, the
6533   // parameter list is truncated on the right, so that there are
6534   // exactly m parameters.
6535   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6536   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6537     // Not enough arguments.
6538     Candidate.Viable = false;
6539     Candidate.FailureKind = ovl_fail_too_few_arguments;
6540     return;
6541   }
6542 
6543   Candidate.Viable = true;
6544 
6545   if (Method->isStatic() || ObjectType.isNull())
6546     // The implicit object argument is ignored.
6547     Candidate.IgnoreObjectArgument = true;
6548   else {
6549     // Determine the implicit conversion sequence for the object
6550     // parameter.
6551     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6552         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6553         Method, ActingContext);
6554     if (Candidate.Conversions[0].isBad()) {
6555       Candidate.Viable = false;
6556       Candidate.FailureKind = ovl_fail_bad_conversion;
6557       return;
6558     }
6559   }
6560 
6561   // (CUDA B.1): Check for invalid calls between targets.
6562   if (getLangOpts().CUDA)
6563     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6564       if (!IsAllowedCUDACall(Caller, Method)) {
6565         Candidate.Viable = false;
6566         Candidate.FailureKind = ovl_fail_bad_target;
6567         return;
6568       }
6569 
6570   // Determine the implicit conversion sequences for each of the
6571   // arguments.
6572   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6573     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6574       // We already formed a conversion sequence for this parameter during
6575       // template argument deduction.
6576     } else if (ArgIdx < NumParams) {
6577       // (C++ 13.3.2p3): for F to be a viable function, there shall
6578       // exist for each argument an implicit conversion sequence
6579       // (13.3.3.1) that converts that argument to the corresponding
6580       // parameter of F.
6581       QualType ParamType = Proto->getParamType(ArgIdx);
6582       Candidate.Conversions[ArgIdx + 1]
6583         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6584                                 SuppressUserConversions,
6585                                 /*InOverloadResolution=*/true,
6586                                 /*AllowObjCWritebackConversion=*/
6587                                   getLangOpts().ObjCAutoRefCount);
6588       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6589         Candidate.Viable = false;
6590         Candidate.FailureKind = ovl_fail_bad_conversion;
6591         return;
6592       }
6593     } else {
6594       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6595       // argument for which there is no corresponding parameter is
6596       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6597       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6598     }
6599   }
6600 
6601   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6602     Candidate.Viable = false;
6603     Candidate.FailureKind = ovl_fail_enable_if;
6604     Candidate.DeductionFailure.Data = FailedAttr;
6605     return;
6606   }
6607 
6608   if (Method->isMultiVersion() &&
6609       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6610     Candidate.Viable = false;
6611     Candidate.FailureKind = ovl_non_default_multiversion_function;
6612   }
6613 }
6614 
6615 /// Add a C++ member function template as a candidate to the candidate
6616 /// set, using template argument deduction to produce an appropriate member
6617 /// function template specialization.
6618 void
6619 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6620                                  DeclAccessPair FoundDecl,
6621                                  CXXRecordDecl *ActingContext,
6622                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6623                                  QualType ObjectType,
6624                                  Expr::Classification ObjectClassification,
6625                                  ArrayRef<Expr *> Args,
6626                                  OverloadCandidateSet& CandidateSet,
6627                                  bool SuppressUserConversions,
6628                                  bool PartialOverloading) {
6629   if (!CandidateSet.isNewCandidate(MethodTmpl))
6630     return;
6631 
6632   // C++ [over.match.funcs]p7:
6633   //   In each case where a candidate is a function template, candidate
6634   //   function template specializations are generated using template argument
6635   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6636   //   candidate functions in the usual way.113) A given name can refer to one
6637   //   or more function templates and also to a set of overloaded non-template
6638   //   functions. In such a case, the candidate functions generated from each
6639   //   function template are combined with the set of non-template candidate
6640   //   functions.
6641   TemplateDeductionInfo Info(CandidateSet.getLocation());
6642   FunctionDecl *Specialization = nullptr;
6643   ConversionSequenceList Conversions;
6644   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6645           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6646           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6647             return CheckNonDependentConversions(
6648                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6649                 SuppressUserConversions, ActingContext, ObjectType,
6650                 ObjectClassification);
6651           })) {
6652     OverloadCandidate &Candidate =
6653         CandidateSet.addCandidate(Conversions.size(), Conversions);
6654     Candidate.FoundDecl = FoundDecl;
6655     Candidate.Function = MethodTmpl->getTemplatedDecl();
6656     Candidate.Viable = false;
6657     Candidate.IsSurrogate = false;
6658     Candidate.IgnoreObjectArgument =
6659         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6660         ObjectType.isNull();
6661     Candidate.ExplicitCallArguments = Args.size();
6662     if (Result == TDK_NonDependentConversionFailure)
6663       Candidate.FailureKind = ovl_fail_bad_conversion;
6664     else {
6665       Candidate.FailureKind = ovl_fail_bad_deduction;
6666       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6667                                                             Info);
6668     }
6669     return;
6670   }
6671 
6672   // Add the function template specialization produced by template argument
6673   // deduction as a candidate.
6674   assert(Specialization && "Missing member function template specialization?");
6675   assert(isa<CXXMethodDecl>(Specialization) &&
6676          "Specialization is not a member function?");
6677   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6678                      ActingContext, ObjectType, ObjectClassification, Args,
6679                      CandidateSet, SuppressUserConversions, PartialOverloading,
6680                      Conversions);
6681 }
6682 
6683 /// Add a C++ function template specialization as a candidate
6684 /// in the candidate set, using template argument deduction to produce
6685 /// an appropriate function template specialization.
6686 void
6687 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6688                                    DeclAccessPair FoundDecl,
6689                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6690                                    ArrayRef<Expr *> Args,
6691                                    OverloadCandidateSet& CandidateSet,
6692                                    bool SuppressUserConversions,
6693                                    bool PartialOverloading) {
6694   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6695     return;
6696 
6697   // C++ [over.match.funcs]p7:
6698   //   In each case where a candidate is a function template, candidate
6699   //   function template specializations are generated using template argument
6700   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6701   //   candidate functions in the usual way.113) A given name can refer to one
6702   //   or more function templates and also to a set of overloaded non-template
6703   //   functions. In such a case, the candidate functions generated from each
6704   //   function template are combined with the set of non-template candidate
6705   //   functions.
6706   TemplateDeductionInfo Info(CandidateSet.getLocation());
6707   FunctionDecl *Specialization = nullptr;
6708   ConversionSequenceList Conversions;
6709   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6710           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6711           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6712             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6713                                                 Args, CandidateSet, Conversions,
6714                                                 SuppressUserConversions);
6715           })) {
6716     OverloadCandidate &Candidate =
6717         CandidateSet.addCandidate(Conversions.size(), Conversions);
6718     Candidate.FoundDecl = FoundDecl;
6719     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6720     Candidate.Viable = false;
6721     Candidate.IsSurrogate = false;
6722     // Ignore the object argument if there is one, since we don't have an object
6723     // type.
6724     Candidate.IgnoreObjectArgument =
6725         isa<CXXMethodDecl>(Candidate.Function) &&
6726         !isa<CXXConstructorDecl>(Candidate.Function);
6727     Candidate.ExplicitCallArguments = Args.size();
6728     if (Result == TDK_NonDependentConversionFailure)
6729       Candidate.FailureKind = ovl_fail_bad_conversion;
6730     else {
6731       Candidate.FailureKind = ovl_fail_bad_deduction;
6732       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6733                                                             Info);
6734     }
6735     return;
6736   }
6737 
6738   // Add the function template specialization produced by template argument
6739   // deduction as a candidate.
6740   assert(Specialization && "Missing function template specialization?");
6741   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6742                        SuppressUserConversions, PartialOverloading,
6743                        /*AllowExplicit*/false, Conversions);
6744 }
6745 
6746 /// Check that implicit conversion sequences can be formed for each argument
6747 /// whose corresponding parameter has a non-dependent type, per DR1391's
6748 /// [temp.deduct.call]p10.
6749 bool Sema::CheckNonDependentConversions(
6750     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6751     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6752     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6753     CXXRecordDecl *ActingContext, QualType ObjectType,
6754     Expr::Classification ObjectClassification) {
6755   // FIXME: The cases in which we allow explicit conversions for constructor
6756   // arguments never consider calling a constructor template. It's not clear
6757   // that is correct.
6758   const bool AllowExplicit = false;
6759 
6760   auto *FD = FunctionTemplate->getTemplatedDecl();
6761   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6762   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6763   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6764 
6765   Conversions =
6766       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6767 
6768   // Overload resolution is always an unevaluated context.
6769   EnterExpressionEvaluationContext Unevaluated(
6770       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6771 
6772   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6773   // require that, but this check should never result in a hard error, and
6774   // overload resolution is permitted to sidestep instantiations.
6775   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6776       !ObjectType.isNull()) {
6777     Conversions[0] = TryObjectArgumentInitialization(
6778         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6779         Method, ActingContext);
6780     if (Conversions[0].isBad())
6781       return true;
6782   }
6783 
6784   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6785        ++I) {
6786     QualType ParamType = ParamTypes[I];
6787     if (!ParamType->isDependentType()) {
6788       Conversions[ThisConversions + I]
6789         = TryCopyInitialization(*this, Args[I], ParamType,
6790                                 SuppressUserConversions,
6791                                 /*InOverloadResolution=*/true,
6792                                 /*AllowObjCWritebackConversion=*/
6793                                   getLangOpts().ObjCAutoRefCount,
6794                                 AllowExplicit);
6795       if (Conversions[ThisConversions + I].isBad())
6796         return true;
6797     }
6798   }
6799 
6800   return false;
6801 }
6802 
6803 /// Determine whether this is an allowable conversion from the result
6804 /// of an explicit conversion operator to the expected type, per C++
6805 /// [over.match.conv]p1 and [over.match.ref]p1.
6806 ///
6807 /// \param ConvType The return type of the conversion function.
6808 ///
6809 /// \param ToType The type we are converting to.
6810 ///
6811 /// \param AllowObjCPointerConversion Allow a conversion from one
6812 /// Objective-C pointer to another.
6813 ///
6814 /// \returns true if the conversion is allowable, false otherwise.
6815 static bool isAllowableExplicitConversion(Sema &S,
6816                                           QualType ConvType, QualType ToType,
6817                                           bool AllowObjCPointerConversion) {
6818   QualType ToNonRefType = ToType.getNonReferenceType();
6819 
6820   // Easy case: the types are the same.
6821   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6822     return true;
6823 
6824   // Allow qualification conversions.
6825   bool ObjCLifetimeConversion;
6826   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6827                                   ObjCLifetimeConversion))
6828     return true;
6829 
6830   // If we're not allowed to consider Objective-C pointer conversions,
6831   // we're done.
6832   if (!AllowObjCPointerConversion)
6833     return false;
6834 
6835   // Is this an Objective-C pointer conversion?
6836   bool IncompatibleObjC = false;
6837   QualType ConvertedType;
6838   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6839                                    IncompatibleObjC);
6840 }
6841 
6842 /// AddConversionCandidate - Add a C++ conversion function as a
6843 /// candidate in the candidate set (C++ [over.match.conv],
6844 /// C++ [over.match.copy]). From is the expression we're converting from,
6845 /// and ToType is the type that we're eventually trying to convert to
6846 /// (which may or may not be the same type as the type that the
6847 /// conversion function produces).
6848 void
6849 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6850                              DeclAccessPair FoundDecl,
6851                              CXXRecordDecl *ActingContext,
6852                              Expr *From, QualType ToType,
6853                              OverloadCandidateSet& CandidateSet,
6854                              bool AllowObjCConversionOnExplicit,
6855                              bool AllowResultConversion) {
6856   assert(!Conversion->getDescribedFunctionTemplate() &&
6857          "Conversion function templates use AddTemplateConversionCandidate");
6858   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6859   if (!CandidateSet.isNewCandidate(Conversion))
6860     return;
6861 
6862   // If the conversion function has an undeduced return type, trigger its
6863   // deduction now.
6864   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6865     if (DeduceReturnType(Conversion, From->getExprLoc()))
6866       return;
6867     ConvType = Conversion->getConversionType().getNonReferenceType();
6868   }
6869 
6870   // If we don't allow any conversion of the result type, ignore conversion
6871   // functions that don't convert to exactly (possibly cv-qualified) T.
6872   if (!AllowResultConversion &&
6873       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6874     return;
6875 
6876   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6877   // operator is only a candidate if its return type is the target type or
6878   // can be converted to the target type with a qualification conversion.
6879   if (Conversion->isExplicit() &&
6880       !isAllowableExplicitConversion(*this, ConvType, ToType,
6881                                      AllowObjCConversionOnExplicit))
6882     return;
6883 
6884   // Overload resolution is always an unevaluated context.
6885   EnterExpressionEvaluationContext Unevaluated(
6886       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6887 
6888   // Add this candidate
6889   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6890   Candidate.FoundDecl = FoundDecl;
6891   Candidate.Function = Conversion;
6892   Candidate.IsSurrogate = false;
6893   Candidate.IgnoreObjectArgument = false;
6894   Candidate.FinalConversion.setAsIdentityConversion();
6895   Candidate.FinalConversion.setFromType(ConvType);
6896   Candidate.FinalConversion.setAllToTypes(ToType);
6897   Candidate.Viable = true;
6898   Candidate.ExplicitCallArguments = 1;
6899 
6900   // C++ [over.match.funcs]p4:
6901   //   For conversion functions, the function is considered to be a member of
6902   //   the class of the implicit implied object argument for the purpose of
6903   //   defining the type of the implicit object parameter.
6904   //
6905   // Determine the implicit conversion sequence for the implicit
6906   // object parameter.
6907   QualType ImplicitParamType = From->getType();
6908   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6909     ImplicitParamType = FromPtrType->getPointeeType();
6910   CXXRecordDecl *ConversionContext
6911     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6912 
6913   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6914       *this, CandidateSet.getLocation(), From->getType(),
6915       From->Classify(Context), Conversion, ConversionContext);
6916 
6917   if (Candidate.Conversions[0].isBad()) {
6918     Candidate.Viable = false;
6919     Candidate.FailureKind = ovl_fail_bad_conversion;
6920     return;
6921   }
6922 
6923   // We won't go through a user-defined type conversion function to convert a
6924   // derived to base as such conversions are given Conversion Rank. They only
6925   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6926   QualType FromCanon
6927     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6928   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6929   if (FromCanon == ToCanon ||
6930       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6931     Candidate.Viable = false;
6932     Candidate.FailureKind = ovl_fail_trivial_conversion;
6933     return;
6934   }
6935 
6936   // To determine what the conversion from the result of calling the
6937   // conversion function to the type we're eventually trying to
6938   // convert to (ToType), we need to synthesize a call to the
6939   // conversion function and attempt copy initialization from it. This
6940   // makes sure that we get the right semantics with respect to
6941   // lvalues/rvalues and the type. Fortunately, we can allocate this
6942   // call on the stack and we don't need its arguments to be
6943   // well-formed.
6944   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6945                             VK_LValue, From->getLocStart());
6946   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6947                                 Context.getPointerType(Conversion->getType()),
6948                                 CK_FunctionToPointerDecay,
6949                                 &ConversionRef, VK_RValue);
6950 
6951   QualType ConversionType = Conversion->getConversionType();
6952   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6953     Candidate.Viable = false;
6954     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6955     return;
6956   }
6957 
6958   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6959 
6960   // Note that it is safe to allocate CallExpr on the stack here because
6961   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6962   // allocator).
6963   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6964   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6965                 From->getLocStart());
6966   ImplicitConversionSequence ICS =
6967     TryCopyInitialization(*this, &Call, ToType,
6968                           /*SuppressUserConversions=*/true,
6969                           /*InOverloadResolution=*/false,
6970                           /*AllowObjCWritebackConversion=*/false);
6971 
6972   switch (ICS.getKind()) {
6973   case ImplicitConversionSequence::StandardConversion:
6974     Candidate.FinalConversion = ICS.Standard;
6975 
6976     // C++ [over.ics.user]p3:
6977     //   If the user-defined conversion is specified by a specialization of a
6978     //   conversion function template, the second standard conversion sequence
6979     //   shall have exact match rank.
6980     if (Conversion->getPrimaryTemplate() &&
6981         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6982       Candidate.Viable = false;
6983       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6984       return;
6985     }
6986 
6987     // C++0x [dcl.init.ref]p5:
6988     //    In the second case, if the reference is an rvalue reference and
6989     //    the second standard conversion sequence of the user-defined
6990     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6991     //    program is ill-formed.
6992     if (ToType->isRValueReferenceType() &&
6993         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6994       Candidate.Viable = false;
6995       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6996       return;
6997     }
6998     break;
6999 
7000   case ImplicitConversionSequence::BadConversion:
7001     Candidate.Viable = false;
7002     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7003     return;
7004 
7005   default:
7006     llvm_unreachable(
7007            "Can only end up with a standard conversion sequence or failure");
7008   }
7009 
7010   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7011     Candidate.Viable = false;
7012     Candidate.FailureKind = ovl_fail_enable_if;
7013     Candidate.DeductionFailure.Data = FailedAttr;
7014     return;
7015   }
7016 
7017   if (Conversion->isMultiVersion() &&
7018       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7019     Candidate.Viable = false;
7020     Candidate.FailureKind = ovl_non_default_multiversion_function;
7021   }
7022 }
7023 
7024 /// Adds a conversion function template specialization
7025 /// candidate to the overload set, using template argument deduction
7026 /// to deduce the template arguments of the conversion function
7027 /// template from the type that we are converting to (C++
7028 /// [temp.deduct.conv]).
7029 void
7030 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7031                                      DeclAccessPair FoundDecl,
7032                                      CXXRecordDecl *ActingDC,
7033                                      Expr *From, QualType ToType,
7034                                      OverloadCandidateSet &CandidateSet,
7035                                      bool AllowObjCConversionOnExplicit,
7036                                      bool AllowResultConversion) {
7037   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7038          "Only conversion function templates permitted here");
7039 
7040   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7041     return;
7042 
7043   TemplateDeductionInfo Info(CandidateSet.getLocation());
7044   CXXConversionDecl *Specialization = nullptr;
7045   if (TemplateDeductionResult Result
7046         = DeduceTemplateArguments(FunctionTemplate, ToType,
7047                                   Specialization, Info)) {
7048     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7049     Candidate.FoundDecl = FoundDecl;
7050     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7051     Candidate.Viable = false;
7052     Candidate.FailureKind = ovl_fail_bad_deduction;
7053     Candidate.IsSurrogate = false;
7054     Candidate.IgnoreObjectArgument = false;
7055     Candidate.ExplicitCallArguments = 1;
7056     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7057                                                           Info);
7058     return;
7059   }
7060 
7061   // Add the conversion function template specialization produced by
7062   // template argument deduction as a candidate.
7063   assert(Specialization && "Missing function template specialization?");
7064   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7065                          CandidateSet, AllowObjCConversionOnExplicit,
7066                          AllowResultConversion);
7067 }
7068 
7069 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7070 /// converts the given @c Object to a function pointer via the
7071 /// conversion function @c Conversion, and then attempts to call it
7072 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7073 /// the type of function that we'll eventually be calling.
7074 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7075                                  DeclAccessPair FoundDecl,
7076                                  CXXRecordDecl *ActingContext,
7077                                  const FunctionProtoType *Proto,
7078                                  Expr *Object,
7079                                  ArrayRef<Expr *> Args,
7080                                  OverloadCandidateSet& CandidateSet) {
7081   if (!CandidateSet.isNewCandidate(Conversion))
7082     return;
7083 
7084   // Overload resolution is always an unevaluated context.
7085   EnterExpressionEvaluationContext Unevaluated(
7086       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7087 
7088   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7089   Candidate.FoundDecl = FoundDecl;
7090   Candidate.Function = nullptr;
7091   Candidate.Surrogate = Conversion;
7092   Candidate.Viable = true;
7093   Candidate.IsSurrogate = true;
7094   Candidate.IgnoreObjectArgument = false;
7095   Candidate.ExplicitCallArguments = Args.size();
7096 
7097   // Determine the implicit conversion sequence for the implicit
7098   // object parameter.
7099   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7100       *this, CandidateSet.getLocation(), Object->getType(),
7101       Object->Classify(Context), Conversion, ActingContext);
7102   if (ObjectInit.isBad()) {
7103     Candidate.Viable = false;
7104     Candidate.FailureKind = ovl_fail_bad_conversion;
7105     Candidate.Conversions[0] = ObjectInit;
7106     return;
7107   }
7108 
7109   // The first conversion is actually a user-defined conversion whose
7110   // first conversion is ObjectInit's standard conversion (which is
7111   // effectively a reference binding). Record it as such.
7112   Candidate.Conversions[0].setUserDefined();
7113   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7114   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7115   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7116   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7117   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7118   Candidate.Conversions[0].UserDefined.After
7119     = Candidate.Conversions[0].UserDefined.Before;
7120   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7121 
7122   // Find the
7123   unsigned NumParams = Proto->getNumParams();
7124 
7125   // (C++ 13.3.2p2): A candidate function having fewer than m
7126   // parameters is viable only if it has an ellipsis in its parameter
7127   // list (8.3.5).
7128   if (Args.size() > NumParams && !Proto->isVariadic()) {
7129     Candidate.Viable = false;
7130     Candidate.FailureKind = ovl_fail_too_many_arguments;
7131     return;
7132   }
7133 
7134   // Function types don't have any default arguments, so just check if
7135   // we have enough arguments.
7136   if (Args.size() < NumParams) {
7137     // Not enough arguments.
7138     Candidate.Viable = false;
7139     Candidate.FailureKind = ovl_fail_too_few_arguments;
7140     return;
7141   }
7142 
7143   // Determine the implicit conversion sequences for each of the
7144   // arguments.
7145   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7146     if (ArgIdx < NumParams) {
7147       // (C++ 13.3.2p3): for F to be a viable function, there shall
7148       // exist for each argument an implicit conversion sequence
7149       // (13.3.3.1) that converts that argument to the corresponding
7150       // parameter of F.
7151       QualType ParamType = Proto->getParamType(ArgIdx);
7152       Candidate.Conversions[ArgIdx + 1]
7153         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7154                                 /*SuppressUserConversions=*/false,
7155                                 /*InOverloadResolution=*/false,
7156                                 /*AllowObjCWritebackConversion=*/
7157                                   getLangOpts().ObjCAutoRefCount);
7158       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7159         Candidate.Viable = false;
7160         Candidate.FailureKind = ovl_fail_bad_conversion;
7161         return;
7162       }
7163     } else {
7164       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7165       // argument for which there is no corresponding parameter is
7166       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7167       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7168     }
7169   }
7170 
7171   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7172     Candidate.Viable = false;
7173     Candidate.FailureKind = ovl_fail_enable_if;
7174     Candidate.DeductionFailure.Data = FailedAttr;
7175     return;
7176   }
7177 }
7178 
7179 /// Add overload candidates for overloaded operators that are
7180 /// member functions.
7181 ///
7182 /// Add the overloaded operator candidates that are member functions
7183 /// for the operator Op that was used in an operator expression such
7184 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7185 /// CandidateSet will store the added overload candidates. (C++
7186 /// [over.match.oper]).
7187 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7188                                        SourceLocation OpLoc,
7189                                        ArrayRef<Expr *> Args,
7190                                        OverloadCandidateSet& CandidateSet,
7191                                        SourceRange OpRange) {
7192   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7193 
7194   // C++ [over.match.oper]p3:
7195   //   For a unary operator @ with an operand of a type whose
7196   //   cv-unqualified version is T1, and for a binary operator @ with
7197   //   a left operand of a type whose cv-unqualified version is T1 and
7198   //   a right operand of a type whose cv-unqualified version is T2,
7199   //   three sets of candidate functions, designated member
7200   //   candidates, non-member candidates and built-in candidates, are
7201   //   constructed as follows:
7202   QualType T1 = Args[0]->getType();
7203 
7204   //     -- If T1 is a complete class type or a class currently being
7205   //        defined, the set of member candidates is the result of the
7206   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7207   //        the set of member candidates is empty.
7208   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7209     // Complete the type if it can be completed.
7210     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7211       return;
7212     // If the type is neither complete nor being defined, bail out now.
7213     if (!T1Rec->getDecl()->getDefinition())
7214       return;
7215 
7216     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7217     LookupQualifiedName(Operators, T1Rec->getDecl());
7218     Operators.suppressDiagnostics();
7219 
7220     for (LookupResult::iterator Oper = Operators.begin(),
7221                              OperEnd = Operators.end();
7222          Oper != OperEnd;
7223          ++Oper)
7224       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7225                          Args[0]->Classify(Context), Args.slice(1),
7226                          CandidateSet, /*SuppressUserConversions=*/false);
7227   }
7228 }
7229 
7230 /// AddBuiltinCandidate - Add a candidate for a built-in
7231 /// operator. ResultTy and ParamTys are the result and parameter types
7232 /// of the built-in candidate, respectively. Args and NumArgs are the
7233 /// arguments being passed to the candidate. IsAssignmentOperator
7234 /// should be true when this built-in candidate is an assignment
7235 /// operator. NumContextualBoolArguments is the number of arguments
7236 /// (at the beginning of the argument list) that will be contextually
7237 /// converted to bool.
7238 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7239                                OverloadCandidateSet& CandidateSet,
7240                                bool IsAssignmentOperator,
7241                                unsigned NumContextualBoolArguments) {
7242   // Overload resolution is always an unevaluated context.
7243   EnterExpressionEvaluationContext Unevaluated(
7244       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7245 
7246   // Add this candidate
7247   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7248   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7249   Candidate.Function = nullptr;
7250   Candidate.IsSurrogate = false;
7251   Candidate.IgnoreObjectArgument = false;
7252   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7253 
7254   // Determine the implicit conversion sequences for each of the
7255   // arguments.
7256   Candidate.Viable = true;
7257   Candidate.ExplicitCallArguments = Args.size();
7258   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7259     // C++ [over.match.oper]p4:
7260     //   For the built-in assignment operators, conversions of the
7261     //   left operand are restricted as follows:
7262     //     -- no temporaries are introduced to hold the left operand, and
7263     //     -- no user-defined conversions are applied to the left
7264     //        operand to achieve a type match with the left-most
7265     //        parameter of a built-in candidate.
7266     //
7267     // We block these conversions by turning off user-defined
7268     // conversions, since that is the only way that initialization of
7269     // a reference to a non-class type can occur from something that
7270     // is not of the same type.
7271     if (ArgIdx < NumContextualBoolArguments) {
7272       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7273              "Contextual conversion to bool requires bool type");
7274       Candidate.Conversions[ArgIdx]
7275         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7276     } else {
7277       Candidate.Conversions[ArgIdx]
7278         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7279                                 ArgIdx == 0 && IsAssignmentOperator,
7280                                 /*InOverloadResolution=*/false,
7281                                 /*AllowObjCWritebackConversion=*/
7282                                   getLangOpts().ObjCAutoRefCount);
7283     }
7284     if (Candidate.Conversions[ArgIdx].isBad()) {
7285       Candidate.Viable = false;
7286       Candidate.FailureKind = ovl_fail_bad_conversion;
7287       break;
7288     }
7289   }
7290 }
7291 
7292 namespace {
7293 
7294 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7295 /// candidate operator functions for built-in operators (C++
7296 /// [over.built]). The types are separated into pointer types and
7297 /// enumeration types.
7298 class BuiltinCandidateTypeSet  {
7299   /// TypeSet - A set of types.
7300   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7301                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7302 
7303   /// PointerTypes - The set of pointer types that will be used in the
7304   /// built-in candidates.
7305   TypeSet PointerTypes;
7306 
7307   /// MemberPointerTypes - The set of member pointer types that will be
7308   /// used in the built-in candidates.
7309   TypeSet MemberPointerTypes;
7310 
7311   /// EnumerationTypes - The set of enumeration types that will be
7312   /// used in the built-in candidates.
7313   TypeSet EnumerationTypes;
7314 
7315   /// The set of vector types that will be used in the built-in
7316   /// candidates.
7317   TypeSet VectorTypes;
7318 
7319   /// A flag indicating non-record types are viable candidates
7320   bool HasNonRecordTypes;
7321 
7322   /// A flag indicating whether either arithmetic or enumeration types
7323   /// were present in the candidate set.
7324   bool HasArithmeticOrEnumeralTypes;
7325 
7326   /// A flag indicating whether the nullptr type was present in the
7327   /// candidate set.
7328   bool HasNullPtrType;
7329 
7330   /// Sema - The semantic analysis instance where we are building the
7331   /// candidate type set.
7332   Sema &SemaRef;
7333 
7334   /// Context - The AST context in which we will build the type sets.
7335   ASTContext &Context;
7336 
7337   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7338                                                const Qualifiers &VisibleQuals);
7339   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7340 
7341 public:
7342   /// iterator - Iterates through the types that are part of the set.
7343   typedef TypeSet::iterator iterator;
7344 
7345   BuiltinCandidateTypeSet(Sema &SemaRef)
7346     : HasNonRecordTypes(false),
7347       HasArithmeticOrEnumeralTypes(false),
7348       HasNullPtrType(false),
7349       SemaRef(SemaRef),
7350       Context(SemaRef.Context) { }
7351 
7352   void AddTypesConvertedFrom(QualType Ty,
7353                              SourceLocation Loc,
7354                              bool AllowUserConversions,
7355                              bool AllowExplicitConversions,
7356                              const Qualifiers &VisibleTypeConversionsQuals);
7357 
7358   /// pointer_begin - First pointer type found;
7359   iterator pointer_begin() { return PointerTypes.begin(); }
7360 
7361   /// pointer_end - Past the last pointer type found;
7362   iterator pointer_end() { return PointerTypes.end(); }
7363 
7364   /// member_pointer_begin - First member pointer type found;
7365   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7366 
7367   /// member_pointer_end - Past the last member pointer type found;
7368   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7369 
7370   /// enumeration_begin - First enumeration type found;
7371   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7372 
7373   /// enumeration_end - Past the last enumeration type found;
7374   iterator enumeration_end() { return EnumerationTypes.end(); }
7375 
7376   iterator vector_begin() { return VectorTypes.begin(); }
7377   iterator vector_end() { return VectorTypes.end(); }
7378 
7379   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7380   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7381   bool hasNullPtrType() const { return HasNullPtrType; }
7382 };
7383 
7384 } // end anonymous namespace
7385 
7386 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7387 /// the set of pointer types along with any more-qualified variants of
7388 /// that type. For example, if @p Ty is "int const *", this routine
7389 /// will add "int const *", "int const volatile *", "int const
7390 /// restrict *", and "int const volatile restrict *" to the set of
7391 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7392 /// false otherwise.
7393 ///
7394 /// FIXME: what to do about extended qualifiers?
7395 bool
7396 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7397                                              const Qualifiers &VisibleQuals) {
7398 
7399   // Insert this type.
7400   if (!PointerTypes.insert(Ty))
7401     return false;
7402 
7403   QualType PointeeTy;
7404   const PointerType *PointerTy = Ty->getAs<PointerType>();
7405   bool buildObjCPtr = false;
7406   if (!PointerTy) {
7407     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7408     PointeeTy = PTy->getPointeeType();
7409     buildObjCPtr = true;
7410   } else {
7411     PointeeTy = PointerTy->getPointeeType();
7412   }
7413 
7414   // Don't add qualified variants of arrays. For one, they're not allowed
7415   // (the qualifier would sink to the element type), and for another, the
7416   // only overload situation where it matters is subscript or pointer +- int,
7417   // and those shouldn't have qualifier variants anyway.
7418   if (PointeeTy->isArrayType())
7419     return true;
7420 
7421   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7422   bool hasVolatile = VisibleQuals.hasVolatile();
7423   bool hasRestrict = VisibleQuals.hasRestrict();
7424 
7425   // Iterate through all strict supersets of BaseCVR.
7426   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7427     if ((CVR | BaseCVR) != CVR) continue;
7428     // Skip over volatile if no volatile found anywhere in the types.
7429     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7430 
7431     // Skip over restrict if no restrict found anywhere in the types, or if
7432     // the type cannot be restrict-qualified.
7433     if ((CVR & Qualifiers::Restrict) &&
7434         (!hasRestrict ||
7435          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7436       continue;
7437 
7438     // Build qualified pointee type.
7439     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7440 
7441     // Build qualified pointer type.
7442     QualType QPointerTy;
7443     if (!buildObjCPtr)
7444       QPointerTy = Context.getPointerType(QPointeeTy);
7445     else
7446       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7447 
7448     // Insert qualified pointer type.
7449     PointerTypes.insert(QPointerTy);
7450   }
7451 
7452   return true;
7453 }
7454 
7455 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7456 /// to the set of pointer types along with any more-qualified variants of
7457 /// that type. For example, if @p Ty is "int const *", this routine
7458 /// will add "int const *", "int const volatile *", "int const
7459 /// restrict *", and "int const volatile restrict *" to the set of
7460 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7461 /// false otherwise.
7462 ///
7463 /// FIXME: what to do about extended qualifiers?
7464 bool
7465 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7466     QualType Ty) {
7467   // Insert this type.
7468   if (!MemberPointerTypes.insert(Ty))
7469     return false;
7470 
7471   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7472   assert(PointerTy && "type was not a member pointer type!");
7473 
7474   QualType PointeeTy = PointerTy->getPointeeType();
7475   // Don't add qualified variants of arrays. For one, they're not allowed
7476   // (the qualifier would sink to the element type), and for another, the
7477   // only overload situation where it matters is subscript or pointer +- int,
7478   // and those shouldn't have qualifier variants anyway.
7479   if (PointeeTy->isArrayType())
7480     return true;
7481   const Type *ClassTy = PointerTy->getClass();
7482 
7483   // Iterate through all strict supersets of the pointee type's CVR
7484   // qualifiers.
7485   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7486   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7487     if ((CVR | BaseCVR) != CVR) continue;
7488 
7489     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7490     MemberPointerTypes.insert(
7491       Context.getMemberPointerType(QPointeeTy, ClassTy));
7492   }
7493 
7494   return true;
7495 }
7496 
7497 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7498 /// Ty can be implicit converted to the given set of @p Types. We're
7499 /// primarily interested in pointer types and enumeration types. We also
7500 /// take member pointer types, for the conditional operator.
7501 /// AllowUserConversions is true if we should look at the conversion
7502 /// functions of a class type, and AllowExplicitConversions if we
7503 /// should also include the explicit conversion functions of a class
7504 /// type.
7505 void
7506 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7507                                                SourceLocation Loc,
7508                                                bool AllowUserConversions,
7509                                                bool AllowExplicitConversions,
7510                                                const Qualifiers &VisibleQuals) {
7511   // Only deal with canonical types.
7512   Ty = Context.getCanonicalType(Ty);
7513 
7514   // Look through reference types; they aren't part of the type of an
7515   // expression for the purposes of conversions.
7516   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7517     Ty = RefTy->getPointeeType();
7518 
7519   // If we're dealing with an array type, decay to the pointer.
7520   if (Ty->isArrayType())
7521     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7522 
7523   // Otherwise, we don't care about qualifiers on the type.
7524   Ty = Ty.getLocalUnqualifiedType();
7525 
7526   // Flag if we ever add a non-record type.
7527   const RecordType *TyRec = Ty->getAs<RecordType>();
7528   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7529 
7530   // Flag if we encounter an arithmetic type.
7531   HasArithmeticOrEnumeralTypes =
7532     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7533 
7534   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7535     PointerTypes.insert(Ty);
7536   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7537     // Insert our type, and its more-qualified variants, into the set
7538     // of types.
7539     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7540       return;
7541   } else if (Ty->isMemberPointerType()) {
7542     // Member pointers are far easier, since the pointee can't be converted.
7543     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7544       return;
7545   } else if (Ty->isEnumeralType()) {
7546     HasArithmeticOrEnumeralTypes = true;
7547     EnumerationTypes.insert(Ty);
7548   } else if (Ty->isVectorType()) {
7549     // We treat vector types as arithmetic types in many contexts as an
7550     // extension.
7551     HasArithmeticOrEnumeralTypes = true;
7552     VectorTypes.insert(Ty);
7553   } else if (Ty->isNullPtrType()) {
7554     HasNullPtrType = true;
7555   } else if (AllowUserConversions && TyRec) {
7556     // No conversion functions in incomplete types.
7557     if (!SemaRef.isCompleteType(Loc, Ty))
7558       return;
7559 
7560     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7561     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7562       if (isa<UsingShadowDecl>(D))
7563         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7564 
7565       // Skip conversion function templates; they don't tell us anything
7566       // about which builtin types we can convert to.
7567       if (isa<FunctionTemplateDecl>(D))
7568         continue;
7569 
7570       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7571       if (AllowExplicitConversions || !Conv->isExplicit()) {
7572         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7573                               VisibleQuals);
7574       }
7575     }
7576   }
7577 }
7578 
7579 /// Helper function for AddBuiltinOperatorCandidates() that adds
7580 /// the volatile- and non-volatile-qualified assignment operators for the
7581 /// given type to the candidate set.
7582 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7583                                                    QualType T,
7584                                                    ArrayRef<Expr *> Args,
7585                                     OverloadCandidateSet &CandidateSet) {
7586   QualType ParamTypes[2];
7587 
7588   // T& operator=(T&, T)
7589   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7590   ParamTypes[1] = T;
7591   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7592                         /*IsAssignmentOperator=*/true);
7593 
7594   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7595     // volatile T& operator=(volatile T&, T)
7596     ParamTypes[0]
7597       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7598     ParamTypes[1] = T;
7599     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7600                           /*IsAssignmentOperator=*/true);
7601   }
7602 }
7603 
7604 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7605 /// if any, found in visible type conversion functions found in ArgExpr's type.
7606 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7607     Qualifiers VRQuals;
7608     const RecordType *TyRec;
7609     if (const MemberPointerType *RHSMPType =
7610         ArgExpr->getType()->getAs<MemberPointerType>())
7611       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7612     else
7613       TyRec = ArgExpr->getType()->getAs<RecordType>();
7614     if (!TyRec) {
7615       // Just to be safe, assume the worst case.
7616       VRQuals.addVolatile();
7617       VRQuals.addRestrict();
7618       return VRQuals;
7619     }
7620 
7621     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7622     if (!ClassDecl->hasDefinition())
7623       return VRQuals;
7624 
7625     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7626       if (isa<UsingShadowDecl>(D))
7627         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7628       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7629         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7630         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7631           CanTy = ResTypeRef->getPointeeType();
7632         // Need to go down the pointer/mempointer chain and add qualifiers
7633         // as see them.
7634         bool done = false;
7635         while (!done) {
7636           if (CanTy.isRestrictQualified())
7637             VRQuals.addRestrict();
7638           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7639             CanTy = ResTypePtr->getPointeeType();
7640           else if (const MemberPointerType *ResTypeMPtr =
7641                 CanTy->getAs<MemberPointerType>())
7642             CanTy = ResTypeMPtr->getPointeeType();
7643           else
7644             done = true;
7645           if (CanTy.isVolatileQualified())
7646             VRQuals.addVolatile();
7647           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7648             return VRQuals;
7649         }
7650       }
7651     }
7652     return VRQuals;
7653 }
7654 
7655 namespace {
7656 
7657 /// Helper class to manage the addition of builtin operator overload
7658 /// candidates. It provides shared state and utility methods used throughout
7659 /// the process, as well as a helper method to add each group of builtin
7660 /// operator overloads from the standard to a candidate set.
7661 class BuiltinOperatorOverloadBuilder {
7662   // Common instance state available to all overload candidate addition methods.
7663   Sema &S;
7664   ArrayRef<Expr *> Args;
7665   Qualifiers VisibleTypeConversionsQuals;
7666   bool HasArithmeticOrEnumeralCandidateType;
7667   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7668   OverloadCandidateSet &CandidateSet;
7669 
7670   static constexpr int ArithmeticTypesCap = 24;
7671   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7672 
7673   // Define some indices used to iterate over the arithemetic types in
7674   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7675   // types are that preserved by promotion (C++ [over.built]p2).
7676   unsigned FirstIntegralType,
7677            LastIntegralType;
7678   unsigned FirstPromotedIntegralType,
7679            LastPromotedIntegralType;
7680   unsigned FirstPromotedArithmeticType,
7681            LastPromotedArithmeticType;
7682   unsigned NumArithmeticTypes;
7683 
7684   void InitArithmeticTypes() {
7685     // Start of promoted types.
7686     FirstPromotedArithmeticType = 0;
7687     ArithmeticTypes.push_back(S.Context.FloatTy);
7688     ArithmeticTypes.push_back(S.Context.DoubleTy);
7689     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7690     if (S.Context.getTargetInfo().hasFloat128Type())
7691       ArithmeticTypes.push_back(S.Context.Float128Ty);
7692 
7693     // Start of integral types.
7694     FirstIntegralType = ArithmeticTypes.size();
7695     FirstPromotedIntegralType = ArithmeticTypes.size();
7696     ArithmeticTypes.push_back(S.Context.IntTy);
7697     ArithmeticTypes.push_back(S.Context.LongTy);
7698     ArithmeticTypes.push_back(S.Context.LongLongTy);
7699     if (S.Context.getTargetInfo().hasInt128Type())
7700       ArithmeticTypes.push_back(S.Context.Int128Ty);
7701     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7702     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7703     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7704     if (S.Context.getTargetInfo().hasInt128Type())
7705       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7706     LastPromotedIntegralType = ArithmeticTypes.size();
7707     LastPromotedArithmeticType = ArithmeticTypes.size();
7708     // End of promoted types.
7709 
7710     ArithmeticTypes.push_back(S.Context.BoolTy);
7711     ArithmeticTypes.push_back(S.Context.CharTy);
7712     ArithmeticTypes.push_back(S.Context.WCharTy);
7713     if (S.Context.getLangOpts().Char8)
7714       ArithmeticTypes.push_back(S.Context.Char8Ty);
7715     ArithmeticTypes.push_back(S.Context.Char16Ty);
7716     ArithmeticTypes.push_back(S.Context.Char32Ty);
7717     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7718     ArithmeticTypes.push_back(S.Context.ShortTy);
7719     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7720     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7721     LastIntegralType = ArithmeticTypes.size();
7722     NumArithmeticTypes = ArithmeticTypes.size();
7723     // End of integral types.
7724     // FIXME: What about complex? What about half?
7725 
7726     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7727            "Enough inline storage for all arithmetic types.");
7728   }
7729 
7730   /// Helper method to factor out the common pattern of adding overloads
7731   /// for '++' and '--' builtin operators.
7732   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7733                                            bool HasVolatile,
7734                                            bool HasRestrict) {
7735     QualType ParamTypes[2] = {
7736       S.Context.getLValueReferenceType(CandidateTy),
7737       S.Context.IntTy
7738     };
7739 
7740     // Non-volatile version.
7741     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7742 
7743     // Use a heuristic to reduce number of builtin candidates in the set:
7744     // add volatile version only if there are conversions to a volatile type.
7745     if (HasVolatile) {
7746       ParamTypes[0] =
7747         S.Context.getLValueReferenceType(
7748           S.Context.getVolatileType(CandidateTy));
7749       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7750     }
7751 
7752     // Add restrict version only if there are conversions to a restrict type
7753     // and our candidate type is a non-restrict-qualified pointer.
7754     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7755         !CandidateTy.isRestrictQualified()) {
7756       ParamTypes[0]
7757         = S.Context.getLValueReferenceType(
7758             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7759       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7760 
7761       if (HasVolatile) {
7762         ParamTypes[0]
7763           = S.Context.getLValueReferenceType(
7764               S.Context.getCVRQualifiedType(CandidateTy,
7765                                             (Qualifiers::Volatile |
7766                                              Qualifiers::Restrict)));
7767         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7768       }
7769     }
7770 
7771   }
7772 
7773 public:
7774   BuiltinOperatorOverloadBuilder(
7775     Sema &S, ArrayRef<Expr *> Args,
7776     Qualifiers VisibleTypeConversionsQuals,
7777     bool HasArithmeticOrEnumeralCandidateType,
7778     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7779     OverloadCandidateSet &CandidateSet)
7780     : S(S), Args(Args),
7781       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7782       HasArithmeticOrEnumeralCandidateType(
7783         HasArithmeticOrEnumeralCandidateType),
7784       CandidateTypes(CandidateTypes),
7785       CandidateSet(CandidateSet) {
7786 
7787     InitArithmeticTypes();
7788   }
7789 
7790   // Increment is deprecated for bool since C++17.
7791   //
7792   // C++ [over.built]p3:
7793   //
7794   //   For every pair (T, VQ), where T is an arithmetic type other
7795   //   than bool, and VQ is either volatile or empty, there exist
7796   //   candidate operator functions of the form
7797   //
7798   //       VQ T&      operator++(VQ T&);
7799   //       T          operator++(VQ T&, int);
7800   //
7801   // C++ [over.built]p4:
7802   //
7803   //   For every pair (T, VQ), where T is an arithmetic type other
7804   //   than bool, and VQ is either volatile or empty, there exist
7805   //   candidate operator functions of the form
7806   //
7807   //       VQ T&      operator--(VQ T&);
7808   //       T          operator--(VQ T&, int);
7809   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7810     if (!HasArithmeticOrEnumeralCandidateType)
7811       return;
7812 
7813     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7814       const auto TypeOfT = ArithmeticTypes[Arith];
7815       if (TypeOfT == S.Context.BoolTy) {
7816         if (Op == OO_MinusMinus)
7817           continue;
7818         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7819           continue;
7820       }
7821       addPlusPlusMinusMinusStyleOverloads(
7822         TypeOfT,
7823         VisibleTypeConversionsQuals.hasVolatile(),
7824         VisibleTypeConversionsQuals.hasRestrict());
7825     }
7826   }
7827 
7828   // C++ [over.built]p5:
7829   //
7830   //   For every pair (T, VQ), where T is a cv-qualified or
7831   //   cv-unqualified object type, and VQ is either volatile or
7832   //   empty, there exist candidate operator functions of the form
7833   //
7834   //       T*VQ&      operator++(T*VQ&);
7835   //       T*VQ&      operator--(T*VQ&);
7836   //       T*         operator++(T*VQ&, int);
7837   //       T*         operator--(T*VQ&, int);
7838   void addPlusPlusMinusMinusPointerOverloads() {
7839     for (BuiltinCandidateTypeSet::iterator
7840               Ptr = CandidateTypes[0].pointer_begin(),
7841            PtrEnd = CandidateTypes[0].pointer_end();
7842          Ptr != PtrEnd; ++Ptr) {
7843       // Skip pointer types that aren't pointers to object types.
7844       if (!(*Ptr)->getPointeeType()->isObjectType())
7845         continue;
7846 
7847       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7848         (!(*Ptr).isVolatileQualified() &&
7849          VisibleTypeConversionsQuals.hasVolatile()),
7850         (!(*Ptr).isRestrictQualified() &&
7851          VisibleTypeConversionsQuals.hasRestrict()));
7852     }
7853   }
7854 
7855   // C++ [over.built]p6:
7856   //   For every cv-qualified or cv-unqualified object type T, there
7857   //   exist candidate operator functions of the form
7858   //
7859   //       T&         operator*(T*);
7860   //
7861   // C++ [over.built]p7:
7862   //   For every function type T that does not have cv-qualifiers or a
7863   //   ref-qualifier, there exist candidate operator functions of the form
7864   //       T&         operator*(T*);
7865   void addUnaryStarPointerOverloads() {
7866     for (BuiltinCandidateTypeSet::iterator
7867               Ptr = CandidateTypes[0].pointer_begin(),
7868            PtrEnd = CandidateTypes[0].pointer_end();
7869          Ptr != PtrEnd; ++Ptr) {
7870       QualType ParamTy = *Ptr;
7871       QualType PointeeTy = ParamTy->getPointeeType();
7872       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7873         continue;
7874 
7875       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7876         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7877           continue;
7878 
7879       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7880     }
7881   }
7882 
7883   // C++ [over.built]p9:
7884   //  For every promoted arithmetic type T, there exist candidate
7885   //  operator functions of the form
7886   //
7887   //       T         operator+(T);
7888   //       T         operator-(T);
7889   void addUnaryPlusOrMinusArithmeticOverloads() {
7890     if (!HasArithmeticOrEnumeralCandidateType)
7891       return;
7892 
7893     for (unsigned Arith = FirstPromotedArithmeticType;
7894          Arith < LastPromotedArithmeticType; ++Arith) {
7895       QualType ArithTy = ArithmeticTypes[Arith];
7896       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7897     }
7898 
7899     // Extension: We also add these operators for vector types.
7900     for (BuiltinCandidateTypeSet::iterator
7901               Vec = CandidateTypes[0].vector_begin(),
7902            VecEnd = CandidateTypes[0].vector_end();
7903          Vec != VecEnd; ++Vec) {
7904       QualType VecTy = *Vec;
7905       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7906     }
7907   }
7908 
7909   // C++ [over.built]p8:
7910   //   For every type T, there exist candidate operator functions of
7911   //   the form
7912   //
7913   //       T*         operator+(T*);
7914   void addUnaryPlusPointerOverloads() {
7915     for (BuiltinCandidateTypeSet::iterator
7916               Ptr = CandidateTypes[0].pointer_begin(),
7917            PtrEnd = CandidateTypes[0].pointer_end();
7918          Ptr != PtrEnd; ++Ptr) {
7919       QualType ParamTy = *Ptr;
7920       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7921     }
7922   }
7923 
7924   // C++ [over.built]p10:
7925   //   For every promoted integral type T, there exist candidate
7926   //   operator functions of the form
7927   //
7928   //        T         operator~(T);
7929   void addUnaryTildePromotedIntegralOverloads() {
7930     if (!HasArithmeticOrEnumeralCandidateType)
7931       return;
7932 
7933     for (unsigned Int = FirstPromotedIntegralType;
7934          Int < LastPromotedIntegralType; ++Int) {
7935       QualType IntTy = ArithmeticTypes[Int];
7936       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7937     }
7938 
7939     // Extension: We also add this operator for vector types.
7940     for (BuiltinCandidateTypeSet::iterator
7941               Vec = CandidateTypes[0].vector_begin(),
7942            VecEnd = CandidateTypes[0].vector_end();
7943          Vec != VecEnd; ++Vec) {
7944       QualType VecTy = *Vec;
7945       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7946     }
7947   }
7948 
7949   // C++ [over.match.oper]p16:
7950   //   For every pointer to member type T or type std::nullptr_t, there
7951   //   exist candidate operator functions of the form
7952   //
7953   //        bool operator==(T,T);
7954   //        bool operator!=(T,T);
7955   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7956     /// Set of (canonical) types that we've already handled.
7957     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7958 
7959     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7960       for (BuiltinCandidateTypeSet::iterator
7961                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7962              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7963            MemPtr != MemPtrEnd;
7964            ++MemPtr) {
7965         // Don't add the same builtin candidate twice.
7966         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7967           continue;
7968 
7969         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7970         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7971       }
7972 
7973       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7974         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7975         if (AddedTypes.insert(NullPtrTy).second) {
7976           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7977           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7978         }
7979       }
7980     }
7981   }
7982 
7983   // C++ [over.built]p15:
7984   //
7985   //   For every T, where T is an enumeration type or a pointer type,
7986   //   there exist candidate operator functions of the form
7987   //
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   //        bool       operator!=(T, T);
7994   //           R       operator<=>(T, T)
7995   void addGenericBinaryPointerOrEnumeralOverloads() {
7996     // C++ [over.match.oper]p3:
7997     //   [...]the built-in candidates include all of the candidate operator
7998     //   functions defined in 13.6 that, compared to the given operator, [...]
7999     //   do not have the same parameter-type-list as any non-template non-member
8000     //   candidate.
8001     //
8002     // Note that in practice, this only affects enumeration types because there
8003     // aren't any built-in candidates of record type, and a user-defined operator
8004     // must have an operand of record or enumeration type. Also, the only other
8005     // overloaded operator with enumeration arguments, operator=,
8006     // cannot be overloaded for enumeration types, so this is the only place
8007     // where we must suppress candidates like this.
8008     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8009       UserDefinedBinaryOperators;
8010 
8011     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8012       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8013           CandidateTypes[ArgIdx].enumeration_end()) {
8014         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8015                                          CEnd = CandidateSet.end();
8016              C != CEnd; ++C) {
8017           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8018             continue;
8019 
8020           if (C->Function->isFunctionTemplateSpecialization())
8021             continue;
8022 
8023           QualType FirstParamType =
8024             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8025           QualType SecondParamType =
8026             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8027 
8028           // Skip if either parameter isn't of enumeral type.
8029           if (!FirstParamType->isEnumeralType() ||
8030               !SecondParamType->isEnumeralType())
8031             continue;
8032 
8033           // Add this operator to the set of known user-defined operators.
8034           UserDefinedBinaryOperators.insert(
8035             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8036                            S.Context.getCanonicalType(SecondParamType)));
8037         }
8038       }
8039     }
8040 
8041     /// Set of (canonical) types that we've already handled.
8042     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8043 
8044     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8045       for (BuiltinCandidateTypeSet::iterator
8046                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8047              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8048            Ptr != PtrEnd; ++Ptr) {
8049         // Don't add the same builtin candidate twice.
8050         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8051           continue;
8052 
8053         QualType ParamTypes[2] = { *Ptr, *Ptr };
8054         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8055       }
8056       for (BuiltinCandidateTypeSet::iterator
8057                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8058              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8059            Enum != EnumEnd; ++Enum) {
8060         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8061 
8062         // Don't add the same builtin candidate twice, or if a user defined
8063         // candidate exists.
8064         if (!AddedTypes.insert(CanonType).second ||
8065             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8066                                                             CanonType)))
8067           continue;
8068         QualType ParamTypes[2] = { *Enum, *Enum };
8069         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8070       }
8071     }
8072   }
8073 
8074   // C++ [over.built]p13:
8075   //
8076   //   For every cv-qualified or cv-unqualified object type T
8077   //   there exist candidate operator functions of the form
8078   //
8079   //      T*         operator+(T*, ptrdiff_t);
8080   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8081   //      T*         operator-(T*, ptrdiff_t);
8082   //      T*         operator+(ptrdiff_t, T*);
8083   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8084   //
8085   // C++ [over.built]p14:
8086   //
8087   //   For every T, where T is a pointer to object type, there
8088   //   exist candidate operator functions of the form
8089   //
8090   //      ptrdiff_t  operator-(T, T);
8091   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8092     /// Set of (canonical) types that we've already handled.
8093     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8094 
8095     for (int Arg = 0; Arg < 2; ++Arg) {
8096       QualType AsymmetricParamTypes[2] = {
8097         S.Context.getPointerDiffType(),
8098         S.Context.getPointerDiffType(),
8099       };
8100       for (BuiltinCandidateTypeSet::iterator
8101                 Ptr = CandidateTypes[Arg].pointer_begin(),
8102              PtrEnd = CandidateTypes[Arg].pointer_end();
8103            Ptr != PtrEnd; ++Ptr) {
8104         QualType PointeeTy = (*Ptr)->getPointeeType();
8105         if (!PointeeTy->isObjectType())
8106           continue;
8107 
8108         AsymmetricParamTypes[Arg] = *Ptr;
8109         if (Arg == 0 || Op == OO_Plus) {
8110           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8111           // T* operator+(ptrdiff_t, T*);
8112           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8113         }
8114         if (Op == OO_Minus) {
8115           // ptrdiff_t operator-(T, T);
8116           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8117             continue;
8118 
8119           QualType ParamTypes[2] = { *Ptr, *Ptr };
8120           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8121         }
8122       }
8123     }
8124   }
8125 
8126   // C++ [over.built]p12:
8127   //
8128   //   For every pair of promoted arithmetic types L and R, there
8129   //   exist candidate operator functions of the form
8130   //
8131   //        LR         operator*(L, R);
8132   //        LR         operator/(L, R);
8133   //        LR         operator+(L, R);
8134   //        LR         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   //        bool       operator!=(L, R);
8141   //
8142   //   where LR is the result of the usual arithmetic conversions
8143   //   between types L and R.
8144   //
8145   // C++ [over.built]p24:
8146   //
8147   //   For every pair of promoted arithmetic types L and R, there exist
8148   //   candidate operator functions of the form
8149   //
8150   //        LR       operator?(bool, L, R);
8151   //
8152   //   where LR is the result of the usual arithmetic conversions
8153   //   between types L and R.
8154   // Our candidates ignore the first parameter.
8155   void addGenericBinaryArithmeticOverloads() {
8156     if (!HasArithmeticOrEnumeralCandidateType)
8157       return;
8158 
8159     for (unsigned Left = FirstPromotedArithmeticType;
8160          Left < LastPromotedArithmeticType; ++Left) {
8161       for (unsigned Right = FirstPromotedArithmeticType;
8162            Right < LastPromotedArithmeticType; ++Right) {
8163         QualType LandR[2] = { ArithmeticTypes[Left],
8164                               ArithmeticTypes[Right] };
8165         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8166       }
8167     }
8168 
8169     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8170     // conditional operator for vector types.
8171     for (BuiltinCandidateTypeSet::iterator
8172               Vec1 = CandidateTypes[0].vector_begin(),
8173            Vec1End = CandidateTypes[0].vector_end();
8174          Vec1 != Vec1End; ++Vec1) {
8175       for (BuiltinCandidateTypeSet::iterator
8176                 Vec2 = CandidateTypes[1].vector_begin(),
8177              Vec2End = CandidateTypes[1].vector_end();
8178            Vec2 != Vec2End; ++Vec2) {
8179         QualType LandR[2] = { *Vec1, *Vec2 };
8180         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8181       }
8182     }
8183   }
8184 
8185   // C++2a [over.built]p14:
8186   //
8187   //   For every integral type T there exists a candidate operator function
8188   //   of the form
8189   //
8190   //        std::strong_ordering operator<=>(T, T)
8191   //
8192   // C++2a [over.built]p15:
8193   //
8194   //   For every pair of floating-point types L and R, there exists a candidate
8195   //   operator function of the form
8196   //
8197   //       std::partial_ordering operator<=>(L, R);
8198   //
8199   // FIXME: The current specification for integral types doesn't play nice with
8200   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8201   // comparisons. Under the current spec this can lead to ambiguity during
8202   // overload resolution. For example:
8203   //
8204   //   enum A : int {a};
8205   //   auto x = (a <=> (long)42);
8206   //
8207   //   error: call is ambiguous for arguments 'A' and 'long'.
8208   //   note: candidate operator<=>(int, int)
8209   //   note: candidate operator<=>(long, long)
8210   //
8211   // To avoid this error, this function deviates from the specification and adds
8212   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8213   // arithmetic types (the same as the generic relational overloads).
8214   //
8215   // For now this function acts as a placeholder.
8216   void addThreeWayArithmeticOverloads() {
8217     addGenericBinaryArithmeticOverloads();
8218   }
8219 
8220   // C++ [over.built]p17:
8221   //
8222   //   For every pair of promoted integral types L and R, there
8223   //   exist candidate operator functions of the form
8224   //
8225   //      LR         operator%(L, R);
8226   //      LR         operator&(L, R);
8227   //      LR         operator^(L, R);
8228   //      LR         operator|(L, R);
8229   //      L          operator<<(L, R);
8230   //      L          operator>>(L, R);
8231   //
8232   //   where LR is the result of the usual arithmetic conversions
8233   //   between types L and R.
8234   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8235     if (!HasArithmeticOrEnumeralCandidateType)
8236       return;
8237 
8238     for (unsigned Left = FirstPromotedIntegralType;
8239          Left < LastPromotedIntegralType; ++Left) {
8240       for (unsigned Right = FirstPromotedIntegralType;
8241            Right < LastPromotedIntegralType; ++Right) {
8242         QualType LandR[2] = { ArithmeticTypes[Left],
8243                               ArithmeticTypes[Right] };
8244         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8245       }
8246     }
8247   }
8248 
8249   // C++ [over.built]p20:
8250   //
8251   //   For every pair (T, VQ), where T is an enumeration or
8252   //   pointer to member type and VQ is either volatile or
8253   //   empty, there exist candidate operator functions of the form
8254   //
8255   //        VQ T&      operator=(VQ T&, T);
8256   void addAssignmentMemberPointerOrEnumeralOverloads() {
8257     /// Set of (canonical) types that we've already handled.
8258     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8259 
8260     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8261       for (BuiltinCandidateTypeSet::iterator
8262                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8263              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8264            Enum != EnumEnd; ++Enum) {
8265         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8266           continue;
8267 
8268         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8269       }
8270 
8271       for (BuiltinCandidateTypeSet::iterator
8272                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8273              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8274            MemPtr != MemPtrEnd; ++MemPtr) {
8275         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8276           continue;
8277 
8278         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8279       }
8280     }
8281   }
8282 
8283   // C++ [over.built]p19:
8284   //
8285   //   For every pair (T, VQ), where T is any type and VQ is either
8286   //   volatile or empty, there exist candidate operator functions
8287   //   of the form
8288   //
8289   //        T*VQ&      operator=(T*VQ&, T*);
8290   //
8291   // C++ [over.built]p21:
8292   //
8293   //   For every pair (T, VQ), where T is a cv-qualified or
8294   //   cv-unqualified object type and VQ is either volatile or
8295   //   empty, there exist candidate operator functions of the form
8296   //
8297   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8298   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8299   void addAssignmentPointerOverloads(bool isEqualOp) {
8300     /// Set of (canonical) types that we've already handled.
8301     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8302 
8303     for (BuiltinCandidateTypeSet::iterator
8304               Ptr = CandidateTypes[0].pointer_begin(),
8305            PtrEnd = CandidateTypes[0].pointer_end();
8306          Ptr != PtrEnd; ++Ptr) {
8307       // If this is operator=, keep track of the builtin candidates we added.
8308       if (isEqualOp)
8309         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8310       else if (!(*Ptr)->getPointeeType()->isObjectType())
8311         continue;
8312 
8313       // non-volatile version
8314       QualType ParamTypes[2] = {
8315         S.Context.getLValueReferenceType(*Ptr),
8316         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8317       };
8318       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8319                             /*IsAssigmentOperator=*/ isEqualOp);
8320 
8321       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8322                           VisibleTypeConversionsQuals.hasVolatile();
8323       if (NeedVolatile) {
8324         // volatile version
8325         ParamTypes[0] =
8326           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8327         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8328                               /*IsAssigmentOperator=*/isEqualOp);
8329       }
8330 
8331       if (!(*Ptr).isRestrictQualified() &&
8332           VisibleTypeConversionsQuals.hasRestrict()) {
8333         // restrict version
8334         ParamTypes[0]
8335           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8336         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8337                               /*IsAssigmentOperator=*/isEqualOp);
8338 
8339         if (NeedVolatile) {
8340           // volatile restrict version
8341           ParamTypes[0]
8342             = S.Context.getLValueReferenceType(
8343                 S.Context.getCVRQualifiedType(*Ptr,
8344                                               (Qualifiers::Volatile |
8345                                                Qualifiers::Restrict)));
8346           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8347                                 /*IsAssigmentOperator=*/isEqualOp);
8348         }
8349       }
8350     }
8351 
8352     if (isEqualOp) {
8353       for (BuiltinCandidateTypeSet::iterator
8354                 Ptr = CandidateTypes[1].pointer_begin(),
8355              PtrEnd = CandidateTypes[1].pointer_end();
8356            Ptr != PtrEnd; ++Ptr) {
8357         // Make sure we don't add the same candidate twice.
8358         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8359           continue;
8360 
8361         QualType ParamTypes[2] = {
8362           S.Context.getLValueReferenceType(*Ptr),
8363           *Ptr,
8364         };
8365 
8366         // non-volatile version
8367         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8368                               /*IsAssigmentOperator=*/true);
8369 
8370         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8371                            VisibleTypeConversionsQuals.hasVolatile();
8372         if (NeedVolatile) {
8373           // volatile version
8374           ParamTypes[0] =
8375             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8376           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8377                                 /*IsAssigmentOperator=*/true);
8378         }
8379 
8380         if (!(*Ptr).isRestrictQualified() &&
8381             VisibleTypeConversionsQuals.hasRestrict()) {
8382           // restrict version
8383           ParamTypes[0]
8384             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8385           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8386                                 /*IsAssigmentOperator=*/true);
8387 
8388           if (NeedVolatile) {
8389             // volatile restrict version
8390             ParamTypes[0]
8391               = S.Context.getLValueReferenceType(
8392                   S.Context.getCVRQualifiedType(*Ptr,
8393                                                 (Qualifiers::Volatile |
8394                                                  Qualifiers::Restrict)));
8395             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8396                                   /*IsAssigmentOperator=*/true);
8397           }
8398         }
8399       }
8400     }
8401   }
8402 
8403   // C++ [over.built]p18:
8404   //
8405   //   For every triple (L, VQ, R), where L is an arithmetic type,
8406   //   VQ is either volatile or empty, and R is a promoted
8407   //   arithmetic type, there exist candidate operator functions of
8408   //   the form
8409   //
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   //        VQ L&      operator-=(VQ L&, R);
8415   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8416     if (!HasArithmeticOrEnumeralCandidateType)
8417       return;
8418 
8419     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8420       for (unsigned Right = FirstPromotedArithmeticType;
8421            Right < LastPromotedArithmeticType; ++Right) {
8422         QualType ParamTypes[2];
8423         ParamTypes[1] = ArithmeticTypes[Right];
8424 
8425         // Add this built-in operator as a candidate (VQ is empty).
8426         ParamTypes[0] =
8427           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8428         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8429                               /*IsAssigmentOperator=*/isEqualOp);
8430 
8431         // Add this built-in operator as a candidate (VQ is 'volatile').
8432         if (VisibleTypeConversionsQuals.hasVolatile()) {
8433           ParamTypes[0] =
8434             S.Context.getVolatileType(ArithmeticTypes[Left]);
8435           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8436           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8437                                 /*IsAssigmentOperator=*/isEqualOp);
8438         }
8439       }
8440     }
8441 
8442     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8443     for (BuiltinCandidateTypeSet::iterator
8444               Vec1 = CandidateTypes[0].vector_begin(),
8445            Vec1End = CandidateTypes[0].vector_end();
8446          Vec1 != Vec1End; ++Vec1) {
8447       for (BuiltinCandidateTypeSet::iterator
8448                 Vec2 = CandidateTypes[1].vector_begin(),
8449              Vec2End = CandidateTypes[1].vector_end();
8450            Vec2 != Vec2End; ++Vec2) {
8451         QualType ParamTypes[2];
8452         ParamTypes[1] = *Vec2;
8453         // Add this built-in operator as a candidate (VQ is empty).
8454         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8455         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8456                               /*IsAssigmentOperator=*/isEqualOp);
8457 
8458         // Add this built-in operator as a candidate (VQ is 'volatile').
8459         if (VisibleTypeConversionsQuals.hasVolatile()) {
8460           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8461           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8462           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8463                                 /*IsAssigmentOperator=*/isEqualOp);
8464         }
8465       }
8466     }
8467   }
8468 
8469   // C++ [over.built]p22:
8470   //
8471   //   For every triple (L, VQ, R), where L is an integral type, VQ
8472   //   is either volatile or empty, and R is a promoted integral
8473   //   type, there exist candidate operator functions of the form
8474   //
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   //        VQ L&       operator|=(VQ L&, R);
8481   void addAssignmentIntegralOverloads() {
8482     if (!HasArithmeticOrEnumeralCandidateType)
8483       return;
8484 
8485     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8486       for (unsigned Right = FirstPromotedIntegralType;
8487            Right < LastPromotedIntegralType; ++Right) {
8488         QualType ParamTypes[2];
8489         ParamTypes[1] = ArithmeticTypes[Right];
8490 
8491         // Add this built-in operator as a candidate (VQ is empty).
8492         ParamTypes[0] =
8493           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8494         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8495         if (VisibleTypeConversionsQuals.hasVolatile()) {
8496           // Add this built-in operator as a candidate (VQ is 'volatile').
8497           ParamTypes[0] = ArithmeticTypes[Left];
8498           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8499           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8500           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8501         }
8502       }
8503     }
8504   }
8505 
8506   // C++ [over.operator]p23:
8507   //
8508   //   There also exist candidate operator functions of the form
8509   //
8510   //        bool        operator!(bool);
8511   //        bool        operator&&(bool, bool);
8512   //        bool        operator||(bool, bool);
8513   void addExclaimOverload() {
8514     QualType ParamTy = S.Context.BoolTy;
8515     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8516                           /*IsAssignmentOperator=*/false,
8517                           /*NumContextualBoolArguments=*/1);
8518   }
8519   void addAmpAmpOrPipePipeOverload() {
8520     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8521     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8522                           /*IsAssignmentOperator=*/false,
8523                           /*NumContextualBoolArguments=*/2);
8524   }
8525 
8526   // C++ [over.built]p13:
8527   //
8528   //   For every cv-qualified or cv-unqualified object type T there
8529   //   exist candidate operator functions of the form
8530   //
8531   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8532   //        T&         operator[](T*, ptrdiff_t);
8533   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8534   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8535   //        T&         operator[](ptrdiff_t, T*);
8536   void addSubscriptOverloads() {
8537     for (BuiltinCandidateTypeSet::iterator
8538               Ptr = CandidateTypes[0].pointer_begin(),
8539            PtrEnd = CandidateTypes[0].pointer_end();
8540          Ptr != PtrEnd; ++Ptr) {
8541       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8542       QualType PointeeType = (*Ptr)->getPointeeType();
8543       if (!PointeeType->isObjectType())
8544         continue;
8545 
8546       // T& operator[](T*, ptrdiff_t)
8547       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8548     }
8549 
8550     for (BuiltinCandidateTypeSet::iterator
8551               Ptr = CandidateTypes[1].pointer_begin(),
8552            PtrEnd = CandidateTypes[1].pointer_end();
8553          Ptr != PtrEnd; ++Ptr) {
8554       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8555       QualType PointeeType = (*Ptr)->getPointeeType();
8556       if (!PointeeType->isObjectType())
8557         continue;
8558 
8559       // T& operator[](ptrdiff_t, T*)
8560       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8561     }
8562   }
8563 
8564   // C++ [over.built]p11:
8565   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8566   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8567   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8568   //    there exist candidate operator functions of the form
8569   //
8570   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8571   //
8572   //    where CV12 is the union of CV1 and CV2.
8573   void addArrowStarOverloads() {
8574     for (BuiltinCandidateTypeSet::iterator
8575              Ptr = CandidateTypes[0].pointer_begin(),
8576            PtrEnd = CandidateTypes[0].pointer_end();
8577          Ptr != PtrEnd; ++Ptr) {
8578       QualType C1Ty = (*Ptr);
8579       QualType C1;
8580       QualifierCollector Q1;
8581       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8582       if (!isa<RecordType>(C1))
8583         continue;
8584       // heuristic to reduce number of builtin candidates in the set.
8585       // Add volatile/restrict version only if there are conversions to a
8586       // volatile/restrict type.
8587       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8588         continue;
8589       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8590         continue;
8591       for (BuiltinCandidateTypeSet::iterator
8592                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8593              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8594            MemPtr != MemPtrEnd; ++MemPtr) {
8595         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8596         QualType C2 = QualType(mptr->getClass(), 0);
8597         C2 = C2.getUnqualifiedType();
8598         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8599           break;
8600         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8601         // build CV12 T&
8602         QualType T = mptr->getPointeeType();
8603         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8604             T.isVolatileQualified())
8605           continue;
8606         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8607             T.isRestrictQualified())
8608           continue;
8609         T = Q1.apply(S.Context, T);
8610         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8611       }
8612     }
8613   }
8614 
8615   // Note that we don't consider the first argument, since it has been
8616   // contextually converted to bool long ago. The candidates below are
8617   // therefore added as binary.
8618   //
8619   // C++ [over.built]p25:
8620   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8621   //   enumeration type, there exist candidate operator functions of the form
8622   //
8623   //        T        operator?(bool, T, T);
8624   //
8625   void addConditionalOperatorOverloads() {
8626     /// Set of (canonical) types that we've already handled.
8627     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628 
8629     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8630       for (BuiltinCandidateTypeSet::iterator
8631                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8632              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8633            Ptr != PtrEnd; ++Ptr) {
8634         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8635           continue;
8636 
8637         QualType ParamTypes[2] = { *Ptr, *Ptr };
8638         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8639       }
8640 
8641       for (BuiltinCandidateTypeSet::iterator
8642                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8643              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8644            MemPtr != MemPtrEnd; ++MemPtr) {
8645         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8646           continue;
8647 
8648         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8649         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8650       }
8651 
8652       if (S.getLangOpts().CPlusPlus11) {
8653         for (BuiltinCandidateTypeSet::iterator
8654                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8655                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8656              Enum != EnumEnd; ++Enum) {
8657           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8658             continue;
8659 
8660           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8661             continue;
8662 
8663           QualType ParamTypes[2] = { *Enum, *Enum };
8664           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8665         }
8666       }
8667     }
8668   }
8669 };
8670 
8671 } // end anonymous namespace
8672 
8673 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8674 /// operator overloads to the candidate set (C++ [over.built]), based
8675 /// on the operator @p Op and the arguments given. For example, if the
8676 /// operator is a binary '+', this routine might add "int
8677 /// operator+(int, int)" to cover integer addition.
8678 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8679                                         SourceLocation OpLoc,
8680                                         ArrayRef<Expr *> Args,
8681                                         OverloadCandidateSet &CandidateSet) {
8682   // Find all of the types that the arguments can convert to, but only
8683   // if the operator we're looking at has built-in operator candidates
8684   // that make use of these types. Also record whether we encounter non-record
8685   // candidate types or either arithmetic or enumeral candidate types.
8686   Qualifiers VisibleTypeConversionsQuals;
8687   VisibleTypeConversionsQuals.addConst();
8688   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8689     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8690 
8691   bool HasNonRecordCandidateType = false;
8692   bool HasArithmeticOrEnumeralCandidateType = false;
8693   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8694   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8695     CandidateTypes.emplace_back(*this);
8696     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8697                                                  OpLoc,
8698                                                  true,
8699                                                  (Op == OO_Exclaim ||
8700                                                   Op == OO_AmpAmp ||
8701                                                   Op == OO_PipePipe),
8702                                                  VisibleTypeConversionsQuals);
8703     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8704         CandidateTypes[ArgIdx].hasNonRecordTypes();
8705     HasArithmeticOrEnumeralCandidateType =
8706         HasArithmeticOrEnumeralCandidateType ||
8707         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8708   }
8709 
8710   // Exit early when no non-record types have been added to the candidate set
8711   // for any of the arguments to the operator.
8712   //
8713   // We can't exit early for !, ||, or &&, since there we have always have
8714   // 'bool' overloads.
8715   if (!HasNonRecordCandidateType &&
8716       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8717     return;
8718 
8719   // Setup an object to manage the common state for building overloads.
8720   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8721                                            VisibleTypeConversionsQuals,
8722                                            HasArithmeticOrEnumeralCandidateType,
8723                                            CandidateTypes, CandidateSet);
8724 
8725   // Dispatch over the operation to add in only those overloads which apply.
8726   switch (Op) {
8727   case OO_None:
8728   case NUM_OVERLOADED_OPERATORS:
8729     llvm_unreachable("Expected an overloaded operator");
8730 
8731   case OO_New:
8732   case OO_Delete:
8733   case OO_Array_New:
8734   case OO_Array_Delete:
8735   case OO_Call:
8736     llvm_unreachable(
8737                     "Special operators don't use AddBuiltinOperatorCandidates");
8738 
8739   case OO_Comma:
8740   case OO_Arrow:
8741   case OO_Coawait:
8742     // C++ [over.match.oper]p3:
8743     //   -- For the operator ',', the unary operator '&', the
8744     //      operator '->', or the operator 'co_await', the
8745     //      built-in candidates set is empty.
8746     break;
8747 
8748   case OO_Plus: // '+' is either unary or binary
8749     if (Args.size() == 1)
8750       OpBuilder.addUnaryPlusPointerOverloads();
8751     LLVM_FALLTHROUGH;
8752 
8753   case OO_Minus: // '-' is either unary or binary
8754     if (Args.size() == 1) {
8755       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8756     } else {
8757       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8758       OpBuilder.addGenericBinaryArithmeticOverloads();
8759     }
8760     break;
8761 
8762   case OO_Star: // '*' is either unary or binary
8763     if (Args.size() == 1)
8764       OpBuilder.addUnaryStarPointerOverloads();
8765     else
8766       OpBuilder.addGenericBinaryArithmeticOverloads();
8767     break;
8768 
8769   case OO_Slash:
8770     OpBuilder.addGenericBinaryArithmeticOverloads();
8771     break;
8772 
8773   case OO_PlusPlus:
8774   case OO_MinusMinus:
8775     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8776     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8777     break;
8778 
8779   case OO_EqualEqual:
8780   case OO_ExclaimEqual:
8781     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8782     LLVM_FALLTHROUGH;
8783 
8784   case OO_Less:
8785   case OO_Greater:
8786   case OO_LessEqual:
8787   case OO_GreaterEqual:
8788     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8789     OpBuilder.addGenericBinaryArithmeticOverloads();
8790     break;
8791 
8792   case OO_Spaceship:
8793     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8794     OpBuilder.addThreeWayArithmeticOverloads();
8795     break;
8796 
8797   case OO_Percent:
8798   case OO_Caret:
8799   case OO_Pipe:
8800   case OO_LessLess:
8801   case OO_GreaterGreater:
8802     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8803     break;
8804 
8805   case OO_Amp: // '&' is either unary or binary
8806     if (Args.size() == 1)
8807       // C++ [over.match.oper]p3:
8808       //   -- For the operator ',', the unary operator '&', or the
8809       //      operator '->', the built-in candidates set is empty.
8810       break;
8811 
8812     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8813     break;
8814 
8815   case OO_Tilde:
8816     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8817     break;
8818 
8819   case OO_Equal:
8820     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8821     LLVM_FALLTHROUGH;
8822 
8823   case OO_PlusEqual:
8824   case OO_MinusEqual:
8825     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8826     LLVM_FALLTHROUGH;
8827 
8828   case OO_StarEqual:
8829   case OO_SlashEqual:
8830     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8831     break;
8832 
8833   case OO_PercentEqual:
8834   case OO_LessLessEqual:
8835   case OO_GreaterGreaterEqual:
8836   case OO_AmpEqual:
8837   case OO_CaretEqual:
8838   case OO_PipeEqual:
8839     OpBuilder.addAssignmentIntegralOverloads();
8840     break;
8841 
8842   case OO_Exclaim:
8843     OpBuilder.addExclaimOverload();
8844     break;
8845 
8846   case OO_AmpAmp:
8847   case OO_PipePipe:
8848     OpBuilder.addAmpAmpOrPipePipeOverload();
8849     break;
8850 
8851   case OO_Subscript:
8852     OpBuilder.addSubscriptOverloads();
8853     break;
8854 
8855   case OO_ArrowStar:
8856     OpBuilder.addArrowStarOverloads();
8857     break;
8858 
8859   case OO_Conditional:
8860     OpBuilder.addConditionalOperatorOverloads();
8861     OpBuilder.addGenericBinaryArithmeticOverloads();
8862     break;
8863   }
8864 }
8865 
8866 /// Add function candidates found via argument-dependent lookup
8867 /// to the set of overloading candidates.
8868 ///
8869 /// This routine performs argument-dependent name lookup based on the
8870 /// given function name (which may also be an operator name) and adds
8871 /// all of the overload candidates found by ADL to the overload
8872 /// candidate set (C++ [basic.lookup.argdep]).
8873 void
8874 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8875                                            SourceLocation Loc,
8876                                            ArrayRef<Expr *> Args,
8877                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8878                                            OverloadCandidateSet& CandidateSet,
8879                                            bool PartialOverloading) {
8880   ADLResult Fns;
8881 
8882   // FIXME: This approach for uniquing ADL results (and removing
8883   // redundant candidates from the set) relies on pointer-equality,
8884   // which means we need to key off the canonical decl.  However,
8885   // always going back to the canonical decl might not get us the
8886   // right set of default arguments.  What default arguments are
8887   // we supposed to consider on ADL candidates, anyway?
8888 
8889   // FIXME: Pass in the explicit template arguments?
8890   ArgumentDependentLookup(Name, Loc, Args, Fns);
8891 
8892   // Erase all of the candidates we already knew about.
8893   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8894                                    CandEnd = CandidateSet.end();
8895        Cand != CandEnd; ++Cand)
8896     if (Cand->Function) {
8897       Fns.erase(Cand->Function);
8898       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8899         Fns.erase(FunTmpl);
8900     }
8901 
8902   // For each of the ADL candidates we found, add it to the overload
8903   // set.
8904   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8905     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8906     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8907       if (ExplicitTemplateArgs)
8908         continue;
8909 
8910       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8911                            PartialOverloading);
8912     } else
8913       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8914                                    FoundDecl, ExplicitTemplateArgs,
8915                                    Args, CandidateSet, PartialOverloading);
8916   }
8917 }
8918 
8919 namespace {
8920 enum class Comparison { Equal, Better, Worse };
8921 }
8922 
8923 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8924 /// overload resolution.
8925 ///
8926 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8927 /// Cand1's first N enable_if attributes have precisely the same conditions as
8928 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8929 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8930 ///
8931 /// Note that you can have a pair of candidates such that Cand1's enable_if
8932 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8933 /// worse than Cand1's.
8934 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8935                                        const FunctionDecl *Cand2) {
8936   // Common case: One (or both) decls don't have enable_if attrs.
8937   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8938   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8939   if (!Cand1Attr || !Cand2Attr) {
8940     if (Cand1Attr == Cand2Attr)
8941       return Comparison::Equal;
8942     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8943   }
8944 
8945   // FIXME: The next several lines are just
8946   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8947   // instead of reverse order which is how they're stored in the AST.
8948   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8949   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8950 
8951   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8952   // has fewer enable_if attributes than Cand2.
8953   if (Cand1Attrs.size() < Cand2Attrs.size())
8954     return Comparison::Worse;
8955 
8956   auto Cand1I = Cand1Attrs.begin();
8957   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8958   for (auto &Cand2A : Cand2Attrs) {
8959     Cand1ID.clear();
8960     Cand2ID.clear();
8961 
8962     auto &Cand1A = *Cand1I++;
8963     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8964     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8965     if (Cand1ID != Cand2ID)
8966       return Comparison::Worse;
8967   }
8968 
8969   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8970 }
8971 
8972 /// isBetterOverloadCandidate - Determines whether the first overload
8973 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8974 bool clang::isBetterOverloadCandidate(
8975     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8976     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8977   // Define viable functions to be better candidates than non-viable
8978   // functions.
8979   if (!Cand2.Viable)
8980     return Cand1.Viable;
8981   else if (!Cand1.Viable)
8982     return false;
8983 
8984   // C++ [over.match.best]p1:
8985   //
8986   //   -- if F is a static member function, ICS1(F) is defined such
8987   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8988   //      any function G, and, symmetrically, ICS1(G) is neither
8989   //      better nor worse than ICS1(F).
8990   unsigned StartArg = 0;
8991   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8992     StartArg = 1;
8993 
8994   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8995     // We don't allow incompatible pointer conversions in C++.
8996     if (!S.getLangOpts().CPlusPlus)
8997       return ICS.isStandard() &&
8998              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8999 
9000     // The only ill-formed conversion we allow in C++ is the string literal to
9001     // char* conversion, which is only considered ill-formed after C++11.
9002     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9003            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9004   };
9005 
9006   // Define functions that don't require ill-formed conversions for a given
9007   // argument to be better candidates than functions that do.
9008   unsigned NumArgs = Cand1.Conversions.size();
9009   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9010   bool HasBetterConversion = false;
9011   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9012     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9013     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9014     if (Cand1Bad != Cand2Bad) {
9015       if (Cand1Bad)
9016         return false;
9017       HasBetterConversion = true;
9018     }
9019   }
9020 
9021   if (HasBetterConversion)
9022     return true;
9023 
9024   // C++ [over.match.best]p1:
9025   //   A viable function F1 is defined to be a better function than another
9026   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9027   //   conversion sequence than ICSi(F2), and then...
9028   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9029     switch (CompareImplicitConversionSequences(S, Loc,
9030                                                Cand1.Conversions[ArgIdx],
9031                                                Cand2.Conversions[ArgIdx])) {
9032     case ImplicitConversionSequence::Better:
9033       // Cand1 has a better conversion sequence.
9034       HasBetterConversion = true;
9035       break;
9036 
9037     case ImplicitConversionSequence::Worse:
9038       // Cand1 can't be better than Cand2.
9039       return false;
9040 
9041     case ImplicitConversionSequence::Indistinguishable:
9042       // Do nothing.
9043       break;
9044     }
9045   }
9046 
9047   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9048   //       ICSj(F2), or, if not that,
9049   if (HasBetterConversion)
9050     return true;
9051 
9052   //   -- the context is an initialization by user-defined conversion
9053   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9054   //      from the return type of F1 to the destination type (i.e.,
9055   //      the type of the entity being initialized) is a better
9056   //      conversion sequence than the standard conversion sequence
9057   //      from the return type of F2 to the destination type.
9058   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9059       Cand1.Function && Cand2.Function &&
9060       isa<CXXConversionDecl>(Cand1.Function) &&
9061       isa<CXXConversionDecl>(Cand2.Function)) {
9062     // First check whether we prefer one of the conversion functions over the
9063     // other. This only distinguishes the results in non-standard, extension
9064     // cases such as the conversion from a lambda closure type to a function
9065     // pointer or block.
9066     ImplicitConversionSequence::CompareKind Result =
9067         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9068     if (Result == ImplicitConversionSequence::Indistinguishable)
9069       Result = CompareStandardConversionSequences(S, Loc,
9070                                                   Cand1.FinalConversion,
9071                                                   Cand2.FinalConversion);
9072 
9073     if (Result != ImplicitConversionSequence::Indistinguishable)
9074       return Result == ImplicitConversionSequence::Better;
9075 
9076     // FIXME: Compare kind of reference binding if conversion functions
9077     // convert to a reference type used in direct reference binding, per
9078     // C++14 [over.match.best]p1 section 2 bullet 3.
9079   }
9080 
9081   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9082   // as combined with the resolution to CWG issue 243.
9083   //
9084   // When the context is initialization by constructor ([over.match.ctor] or
9085   // either phase of [over.match.list]), a constructor is preferred over
9086   // a conversion function.
9087   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9088       Cand1.Function && Cand2.Function &&
9089       isa<CXXConstructorDecl>(Cand1.Function) !=
9090           isa<CXXConstructorDecl>(Cand2.Function))
9091     return isa<CXXConstructorDecl>(Cand1.Function);
9092 
9093   //    -- F1 is a non-template function and F2 is a function template
9094   //       specialization, or, if not that,
9095   bool Cand1IsSpecialization = Cand1.Function &&
9096                                Cand1.Function->getPrimaryTemplate();
9097   bool Cand2IsSpecialization = Cand2.Function &&
9098                                Cand2.Function->getPrimaryTemplate();
9099   if (Cand1IsSpecialization != Cand2IsSpecialization)
9100     return Cand2IsSpecialization;
9101 
9102   //   -- F1 and F2 are function template specializations, and the function
9103   //      template for F1 is more specialized than the template for F2
9104   //      according to the partial ordering rules described in 14.5.5.2, or,
9105   //      if not that,
9106   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9107     if (FunctionTemplateDecl *BetterTemplate
9108           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9109                                          Cand2.Function->getPrimaryTemplate(),
9110                                          Loc,
9111                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9112                                                              : TPOC_Call,
9113                                          Cand1.ExplicitCallArguments,
9114                                          Cand2.ExplicitCallArguments))
9115       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9116   }
9117 
9118   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9119   // A derived-class constructor beats an (inherited) base class constructor.
9120   bool Cand1IsInherited =
9121       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9122   bool Cand2IsInherited =
9123       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9124   if (Cand1IsInherited != Cand2IsInherited)
9125     return Cand2IsInherited;
9126   else if (Cand1IsInherited) {
9127     assert(Cand2IsInherited);
9128     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9129     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9130     if (Cand1Class->isDerivedFrom(Cand2Class))
9131       return true;
9132     if (Cand2Class->isDerivedFrom(Cand1Class))
9133       return false;
9134     // Inherited from sibling base classes: still ambiguous.
9135   }
9136 
9137   // Check C++17 tie-breakers for deduction guides.
9138   {
9139     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9140     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9141     if (Guide1 && Guide2) {
9142       //  -- F1 is generated from a deduction-guide and F2 is not
9143       if (Guide1->isImplicit() != Guide2->isImplicit())
9144         return Guide2->isImplicit();
9145 
9146       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9147       if (Guide1->isCopyDeductionCandidate())
9148         return true;
9149     }
9150   }
9151 
9152   // Check for enable_if value-based overload resolution.
9153   if (Cand1.Function && Cand2.Function) {
9154     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9155     if (Cmp != Comparison::Equal)
9156       return Cmp == Comparison::Better;
9157   }
9158 
9159   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9160     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9161     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9162            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9163   }
9164 
9165   bool HasPS1 = Cand1.Function != nullptr &&
9166                 functionHasPassObjectSizeParams(Cand1.Function);
9167   bool HasPS2 = Cand2.Function != nullptr &&
9168                 functionHasPassObjectSizeParams(Cand2.Function);
9169   return HasPS1 != HasPS2 && HasPS1;
9170 }
9171 
9172 /// Determine whether two declarations are "equivalent" for the purposes of
9173 /// name lookup and overload resolution. This applies when the same internal/no
9174 /// linkage entity is defined by two modules (probably by textually including
9175 /// the same header). In such a case, we don't consider the declarations to
9176 /// declare the same entity, but we also don't want lookups with both
9177 /// declarations visible to be ambiguous in some cases (this happens when using
9178 /// a modularized libstdc++).
9179 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9180                                                   const NamedDecl *B) {
9181   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9182   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9183   if (!VA || !VB)
9184     return false;
9185 
9186   // The declarations must be declaring the same name as an internal linkage
9187   // entity in different modules.
9188   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9189           VB->getDeclContext()->getRedeclContext()) ||
9190       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9191           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9192       VA->isExternallyVisible() || VB->isExternallyVisible())
9193     return false;
9194 
9195   // Check that the declarations appear to be equivalent.
9196   //
9197   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9198   // For constants and functions, we should check the initializer or body is
9199   // the same. For non-constant variables, we shouldn't allow it at all.
9200   if (Context.hasSameType(VA->getType(), VB->getType()))
9201     return true;
9202 
9203   // Enum constants within unnamed enumerations will have different types, but
9204   // may still be similar enough to be interchangeable for our purposes.
9205   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9206     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9207       // Only handle anonymous enums. If the enumerations were named and
9208       // equivalent, they would have been merged to the same type.
9209       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9210       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9211       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9212           !Context.hasSameType(EnumA->getIntegerType(),
9213                                EnumB->getIntegerType()))
9214         return false;
9215       // Allow this only if the value is the same for both enumerators.
9216       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9217     }
9218   }
9219 
9220   // Nothing else is sufficiently similar.
9221   return false;
9222 }
9223 
9224 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9225     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9226   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9227 
9228   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9229   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9230       << !M << (M ? M->getFullModuleName() : "");
9231 
9232   for (auto *E : Equiv) {
9233     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9234     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9235         << !M << (M ? M->getFullModuleName() : "");
9236   }
9237 }
9238 
9239 /// Computes the best viable function (C++ 13.3.3)
9240 /// within an overload candidate set.
9241 ///
9242 /// \param Loc The location of the function name (or operator symbol) for
9243 /// which overload resolution occurs.
9244 ///
9245 /// \param Best If overload resolution was successful or found a deleted
9246 /// function, \p Best points to the candidate function found.
9247 ///
9248 /// \returns The result of overload resolution.
9249 OverloadingResult
9250 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9251                                          iterator &Best) {
9252   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9253   std::transform(begin(), end(), std::back_inserter(Candidates),
9254                  [](OverloadCandidate &Cand) { return &Cand; });
9255 
9256   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9257   // are accepted by both clang and NVCC. However, during a particular
9258   // compilation mode only one call variant is viable. We need to
9259   // exclude non-viable overload candidates from consideration based
9260   // only on their host/device attributes. Specifically, if one
9261   // candidate call is WrongSide and the other is SameSide, we ignore
9262   // the WrongSide candidate.
9263   if (S.getLangOpts().CUDA) {
9264     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9265     bool ContainsSameSideCandidate =
9266         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9267           return Cand->Function &&
9268                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9269                      Sema::CFP_SameSide;
9270         });
9271     if (ContainsSameSideCandidate) {
9272       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9273         return Cand->Function &&
9274                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9275                    Sema::CFP_WrongSide;
9276       };
9277       llvm::erase_if(Candidates, IsWrongSideCandidate);
9278     }
9279   }
9280 
9281   // Find the best viable function.
9282   Best = end();
9283   for (auto *Cand : Candidates)
9284     if (Cand->Viable)
9285       if (Best == end() ||
9286           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9287         Best = Cand;
9288 
9289   // If we didn't find any viable functions, abort.
9290   if (Best == end())
9291     return OR_No_Viable_Function;
9292 
9293   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9294 
9295   // Make sure that this function is better than every other viable
9296   // function. If not, we have an ambiguity.
9297   for (auto *Cand : Candidates) {
9298     if (Cand->Viable && Cand != Best &&
9299         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9300       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9301                                                    Cand->Function)) {
9302         EquivalentCands.push_back(Cand->Function);
9303         continue;
9304       }
9305 
9306       Best = end();
9307       return OR_Ambiguous;
9308     }
9309   }
9310 
9311   // Best is the best viable function.
9312   if (Best->Function &&
9313       (Best->Function->isDeleted() ||
9314        S.isFunctionConsideredUnavailable(Best->Function)))
9315     return OR_Deleted;
9316 
9317   if (!EquivalentCands.empty())
9318     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9319                                                     EquivalentCands);
9320 
9321   return OR_Success;
9322 }
9323 
9324 namespace {
9325 
9326 enum OverloadCandidateKind {
9327   oc_function,
9328   oc_method,
9329   oc_constructor,
9330   oc_implicit_default_constructor,
9331   oc_implicit_copy_constructor,
9332   oc_implicit_move_constructor,
9333   oc_implicit_copy_assignment,
9334   oc_implicit_move_assignment,
9335   oc_inherited_constructor
9336 };
9337 
9338 enum OverloadCandidateSelect {
9339   ocs_non_template,
9340   ocs_template,
9341   ocs_described_template,
9342 };
9343 
9344 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9345 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9346                           std::string &Description) {
9347 
9348   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9349   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9350     isTemplate = true;
9351     Description = S.getTemplateArgumentBindingsText(
9352         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9353   }
9354 
9355   OverloadCandidateSelect Select = [&]() {
9356     if (!Description.empty())
9357       return ocs_described_template;
9358     return isTemplate ? ocs_template : ocs_non_template;
9359   }();
9360 
9361   OverloadCandidateKind Kind = [&]() {
9362     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9363       if (!Ctor->isImplicit()) {
9364         if (isa<ConstructorUsingShadowDecl>(Found))
9365           return oc_inherited_constructor;
9366         else
9367           return oc_constructor;
9368       }
9369 
9370       if (Ctor->isDefaultConstructor())
9371         return oc_implicit_default_constructor;
9372 
9373       if (Ctor->isMoveConstructor())
9374         return oc_implicit_move_constructor;
9375 
9376       assert(Ctor->isCopyConstructor() &&
9377              "unexpected sort of implicit constructor");
9378       return oc_implicit_copy_constructor;
9379     }
9380 
9381     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9382       // This actually gets spelled 'candidate function' for now, but
9383       // it doesn't hurt to split it out.
9384       if (!Meth->isImplicit())
9385         return oc_method;
9386 
9387       if (Meth->isMoveAssignmentOperator())
9388         return oc_implicit_move_assignment;
9389 
9390       if (Meth->isCopyAssignmentOperator())
9391         return oc_implicit_copy_assignment;
9392 
9393       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9394       return oc_method;
9395     }
9396 
9397     return oc_function;
9398   }();
9399 
9400   return std::make_pair(Kind, Select);
9401 }
9402 
9403 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9404   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9405   // set.
9406   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9407     S.Diag(FoundDecl->getLocation(),
9408            diag::note_ovl_candidate_inherited_constructor)
9409       << Shadow->getNominatedBaseClass();
9410 }
9411 
9412 } // end anonymous namespace
9413 
9414 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9415                                     const FunctionDecl *FD) {
9416   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9417     bool AlwaysTrue;
9418     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9419       return false;
9420     if (!AlwaysTrue)
9421       return false;
9422   }
9423   return true;
9424 }
9425 
9426 /// Returns true if we can take the address of the function.
9427 ///
9428 /// \param Complain - If true, we'll emit a diagnostic
9429 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9430 ///   we in overload resolution?
9431 /// \param Loc - The location of the statement we're complaining about. Ignored
9432 ///   if we're not complaining, or if we're in overload resolution.
9433 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9434                                               bool Complain,
9435                                               bool InOverloadResolution,
9436                                               SourceLocation Loc) {
9437   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9438     if (Complain) {
9439       if (InOverloadResolution)
9440         S.Diag(FD->getLocStart(),
9441                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9442       else
9443         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9444     }
9445     return false;
9446   }
9447 
9448   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9449     return P->hasAttr<PassObjectSizeAttr>();
9450   });
9451   if (I == FD->param_end())
9452     return true;
9453 
9454   if (Complain) {
9455     // Add one to ParamNo because it's user-facing
9456     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9457     if (InOverloadResolution)
9458       S.Diag(FD->getLocation(),
9459              diag::note_ovl_candidate_has_pass_object_size_params)
9460           << ParamNo;
9461     else
9462       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9463           << FD << ParamNo;
9464   }
9465   return false;
9466 }
9467 
9468 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9469                                                const FunctionDecl *FD) {
9470   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9471                                            /*InOverloadResolution=*/true,
9472                                            /*Loc=*/SourceLocation());
9473 }
9474 
9475 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9476                                              bool Complain,
9477                                              SourceLocation Loc) {
9478   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9479                                              /*InOverloadResolution=*/false,
9480                                              Loc);
9481 }
9482 
9483 // Notes the location of an overload candidate.
9484 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9485                                  QualType DestType, bool TakingAddress) {
9486   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9487     return;
9488   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9489     return;
9490 
9491   std::string FnDesc;
9492   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9493       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9494   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9495                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9496                          << Fn << FnDesc;
9497 
9498   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9499   Diag(Fn->getLocation(), PD);
9500   MaybeEmitInheritedConstructorNote(*this, Found);
9501 }
9502 
9503 // Notes the location of all overload candidates designated through
9504 // OverloadedExpr
9505 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9506                                      bool TakingAddress) {
9507   assert(OverloadedExpr->getType() == Context.OverloadTy);
9508 
9509   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9510   OverloadExpr *OvlExpr = Ovl.Expression;
9511 
9512   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9513                             IEnd = OvlExpr->decls_end();
9514        I != IEnd; ++I) {
9515     if (FunctionTemplateDecl *FunTmpl =
9516                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9517       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9518                             TakingAddress);
9519     } else if (FunctionDecl *Fun
9520                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9521       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9522     }
9523   }
9524 }
9525 
9526 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9527 /// "lead" diagnostic; it will be given two arguments, the source and
9528 /// target types of the conversion.
9529 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9530                                  Sema &S,
9531                                  SourceLocation CaretLoc,
9532                                  const PartialDiagnostic &PDiag) const {
9533   S.Diag(CaretLoc, PDiag)
9534     << Ambiguous.getFromType() << Ambiguous.getToType();
9535   // FIXME: The note limiting machinery is borrowed from
9536   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9537   // refactoring here.
9538   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9539   unsigned CandsShown = 0;
9540   AmbiguousConversionSequence::const_iterator I, E;
9541   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9542     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9543       break;
9544     ++CandsShown;
9545     S.NoteOverloadCandidate(I->first, I->second);
9546   }
9547   if (I != E)
9548     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9549 }
9550 
9551 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9552                                   unsigned I, bool TakingCandidateAddress) {
9553   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9554   assert(Conv.isBad());
9555   assert(Cand->Function && "for now, candidate must be a function");
9556   FunctionDecl *Fn = Cand->Function;
9557 
9558   // There's a conversion slot for the object argument if this is a
9559   // non-constructor method.  Note that 'I' corresponds the
9560   // conversion-slot index.
9561   bool isObjectArgument = false;
9562   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9563     if (I == 0)
9564       isObjectArgument = true;
9565     else
9566       I--;
9567   }
9568 
9569   std::string FnDesc;
9570   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9571       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9572 
9573   Expr *FromExpr = Conv.Bad.FromExpr;
9574   QualType FromTy = Conv.Bad.getFromType();
9575   QualType ToTy = Conv.Bad.getToType();
9576 
9577   if (FromTy == S.Context.OverloadTy) {
9578     assert(FromExpr && "overload set argument came from implicit argument?");
9579     Expr *E = FromExpr->IgnoreParens();
9580     if (isa<UnaryOperator>(E))
9581       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9582     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9583 
9584     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9585         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9586         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9587         << Name << I + 1;
9588     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9589     return;
9590   }
9591 
9592   // Do some hand-waving analysis to see if the non-viability is due
9593   // to a qualifier mismatch.
9594   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9595   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9596   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9597     CToTy = RT->getPointeeType();
9598   else {
9599     // TODO: detect and diagnose the full richness of const mismatches.
9600     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9601       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9602         CFromTy = FromPT->getPointeeType();
9603         CToTy = ToPT->getPointeeType();
9604       }
9605   }
9606 
9607   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9608       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9609     Qualifiers FromQs = CFromTy.getQualifiers();
9610     Qualifiers ToQs = CToTy.getQualifiers();
9611 
9612     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9613       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9614           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9615           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9616           << FromQs.getAddressSpaceAttributePrintValue()
9617           << ToQs.getAddressSpaceAttributePrintValue()
9618           << (unsigned)isObjectArgument << I + 1;
9619       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9620       return;
9621     }
9622 
9623     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9624       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9625           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9626           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9627           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9628           << (unsigned)isObjectArgument << I + 1;
9629       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9630       return;
9631     }
9632 
9633     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9634       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9635           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9636           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9637           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9638           << (unsigned)isObjectArgument << I + 1;
9639       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9640       return;
9641     }
9642 
9643     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9644       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9645           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9646           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9647           << FromQs.hasUnaligned() << I + 1;
9648       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9649       return;
9650     }
9651 
9652     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9653     assert(CVR && "unexpected qualifiers mismatch");
9654 
9655     if (isObjectArgument) {
9656       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9657           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9658           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9659           << (CVR - 1);
9660     } else {
9661       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9662           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9663           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9664           << (CVR - 1) << I + 1;
9665     }
9666     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9667     return;
9668   }
9669 
9670   // Special diagnostic for failure to convert an initializer list, since
9671   // telling the user that it has type void is not useful.
9672   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9673     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9674         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9675         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9676         << ToTy << (unsigned)isObjectArgument << I + 1;
9677     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9678     return;
9679   }
9680 
9681   // Diagnose references or pointers to incomplete types differently,
9682   // since it's far from impossible that the incompleteness triggered
9683   // the failure.
9684   QualType TempFromTy = FromTy.getNonReferenceType();
9685   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9686     TempFromTy = PTy->getPointeeType();
9687   if (TempFromTy->isIncompleteType()) {
9688     // Emit the generic diagnostic and, optionally, add the hints to it.
9689     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9690         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9691         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9692         << ToTy << (unsigned)isObjectArgument << I + 1
9693         << (unsigned)(Cand->Fix.Kind);
9694 
9695     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9696     return;
9697   }
9698 
9699   // Diagnose base -> derived pointer conversions.
9700   unsigned BaseToDerivedConversion = 0;
9701   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9702     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9703       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9704                                                FromPtrTy->getPointeeType()) &&
9705           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9706           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9707           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9708                           FromPtrTy->getPointeeType()))
9709         BaseToDerivedConversion = 1;
9710     }
9711   } else if (const ObjCObjectPointerType *FromPtrTy
9712                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9713     if (const ObjCObjectPointerType *ToPtrTy
9714                                         = ToTy->getAs<ObjCObjectPointerType>())
9715       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9716         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9717           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9718                                                 FromPtrTy->getPointeeType()) &&
9719               FromIface->isSuperClassOf(ToIface))
9720             BaseToDerivedConversion = 2;
9721   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9722     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9723         !FromTy->isIncompleteType() &&
9724         !ToRefTy->getPointeeType()->isIncompleteType() &&
9725         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9726       BaseToDerivedConversion = 3;
9727     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9728                ToTy.getNonReferenceType().getCanonicalType() ==
9729                FromTy.getNonReferenceType().getCanonicalType()) {
9730       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9731           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9732           << (unsigned)isObjectArgument << I + 1
9733           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9734       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9735       return;
9736     }
9737   }
9738 
9739   if (BaseToDerivedConversion) {
9740     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9741         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9742         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9743         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9744     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9745     return;
9746   }
9747 
9748   if (isa<ObjCObjectPointerType>(CFromTy) &&
9749       isa<PointerType>(CToTy)) {
9750       Qualifiers FromQs = CFromTy.getQualifiers();
9751       Qualifiers ToQs = CToTy.getQualifiers();
9752       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9753         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9754             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9755             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9756             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9757         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9758         return;
9759       }
9760   }
9761 
9762   if (TakingCandidateAddress &&
9763       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9764     return;
9765 
9766   // Emit the generic diagnostic and, optionally, add the hints to it.
9767   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9768   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9769         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9770         << ToTy << (unsigned)isObjectArgument << I + 1
9771         << (unsigned)(Cand->Fix.Kind);
9772 
9773   // If we can fix the conversion, suggest the FixIts.
9774   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9775        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9776     FDiag << *HI;
9777   S.Diag(Fn->getLocation(), FDiag);
9778 
9779   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9780 }
9781 
9782 /// Additional arity mismatch diagnosis specific to a function overload
9783 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9784 /// over a candidate in any candidate set.
9785 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9786                                unsigned NumArgs) {
9787   FunctionDecl *Fn = Cand->Function;
9788   unsigned MinParams = Fn->getMinRequiredArguments();
9789 
9790   // With invalid overloaded operators, it's possible that we think we
9791   // have an arity mismatch when in fact it looks like we have the
9792   // right number of arguments, because only overloaded operators have
9793   // the weird behavior of overloading member and non-member functions.
9794   // Just don't report anything.
9795   if (Fn->isInvalidDecl() &&
9796       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9797     return true;
9798 
9799   if (NumArgs < MinParams) {
9800     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9801            (Cand->FailureKind == ovl_fail_bad_deduction &&
9802             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9803   } else {
9804     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9805            (Cand->FailureKind == ovl_fail_bad_deduction &&
9806             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9807   }
9808 
9809   return false;
9810 }
9811 
9812 /// General arity mismatch diagnosis over a candidate in a candidate set.
9813 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9814                                   unsigned NumFormalArgs) {
9815   assert(isa<FunctionDecl>(D) &&
9816       "The templated declaration should at least be a function"
9817       " when diagnosing bad template argument deduction due to too many"
9818       " or too few arguments");
9819 
9820   FunctionDecl *Fn = cast<FunctionDecl>(D);
9821 
9822   // TODO: treat calls to a missing default constructor as a special case
9823   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9824   unsigned MinParams = Fn->getMinRequiredArguments();
9825 
9826   // at least / at most / exactly
9827   unsigned mode, modeCount;
9828   if (NumFormalArgs < MinParams) {
9829     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9830         FnTy->isTemplateVariadic())
9831       mode = 0; // "at least"
9832     else
9833       mode = 2; // "exactly"
9834     modeCount = MinParams;
9835   } else {
9836     if (MinParams != FnTy->getNumParams())
9837       mode = 1; // "at most"
9838     else
9839       mode = 2; // "exactly"
9840     modeCount = FnTy->getNumParams();
9841   }
9842 
9843   std::string Description;
9844   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9845       ClassifyOverloadCandidate(S, Found, Fn, Description);
9846 
9847   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9848     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9849         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9850         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9851   else
9852     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9853         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9854         << Description << mode << modeCount << NumFormalArgs;
9855 
9856   MaybeEmitInheritedConstructorNote(S, Found);
9857 }
9858 
9859 /// Arity mismatch diagnosis specific to a function overload candidate.
9860 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9861                                   unsigned NumFormalArgs) {
9862   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9863     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9864 }
9865 
9866 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9867   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9868     return TD;
9869   llvm_unreachable("Unsupported: Getting the described template declaration"
9870                    " for bad deduction diagnosis");
9871 }
9872 
9873 /// Diagnose a failed template-argument deduction.
9874 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9875                                  DeductionFailureInfo &DeductionFailure,
9876                                  unsigned NumArgs,
9877                                  bool TakingCandidateAddress) {
9878   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9879   NamedDecl *ParamD;
9880   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9881   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9882   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9883   switch (DeductionFailure.Result) {
9884   case Sema::TDK_Success:
9885     llvm_unreachable("TDK_success while diagnosing bad deduction");
9886 
9887   case Sema::TDK_Incomplete: {
9888     assert(ParamD && "no parameter found for incomplete deduction result");
9889     S.Diag(Templated->getLocation(),
9890            diag::note_ovl_candidate_incomplete_deduction)
9891         << ParamD->getDeclName();
9892     MaybeEmitInheritedConstructorNote(S, Found);
9893     return;
9894   }
9895 
9896   case Sema::TDK_Underqualified: {
9897     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9898     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9899 
9900     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9901 
9902     // Param will have been canonicalized, but it should just be a
9903     // qualified version of ParamD, so move the qualifiers to that.
9904     QualifierCollector Qs;
9905     Qs.strip(Param);
9906     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9907     assert(S.Context.hasSameType(Param, NonCanonParam));
9908 
9909     // Arg has also been canonicalized, but there's nothing we can do
9910     // about that.  It also doesn't matter as much, because it won't
9911     // have any template parameters in it (because deduction isn't
9912     // done on dependent types).
9913     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9914 
9915     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9916         << ParamD->getDeclName() << Arg << NonCanonParam;
9917     MaybeEmitInheritedConstructorNote(S, Found);
9918     return;
9919   }
9920 
9921   case Sema::TDK_Inconsistent: {
9922     assert(ParamD && "no parameter found for inconsistent deduction result");
9923     int which = 0;
9924     if (isa<TemplateTypeParmDecl>(ParamD))
9925       which = 0;
9926     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9927       // Deduction might have failed because we deduced arguments of two
9928       // different types for a non-type template parameter.
9929       // FIXME: Use a different TDK value for this.
9930       QualType T1 =
9931           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9932       QualType T2 =
9933           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9934       if (!S.Context.hasSameType(T1, T2)) {
9935         S.Diag(Templated->getLocation(),
9936                diag::note_ovl_candidate_inconsistent_deduction_types)
9937           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9938           << *DeductionFailure.getSecondArg() << T2;
9939         MaybeEmitInheritedConstructorNote(S, Found);
9940         return;
9941       }
9942 
9943       which = 1;
9944     } else {
9945       which = 2;
9946     }
9947 
9948     S.Diag(Templated->getLocation(),
9949            diag::note_ovl_candidate_inconsistent_deduction)
9950         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9951         << *DeductionFailure.getSecondArg();
9952     MaybeEmitInheritedConstructorNote(S, Found);
9953     return;
9954   }
9955 
9956   case Sema::TDK_InvalidExplicitArguments:
9957     assert(ParamD && "no parameter found for invalid explicit arguments");
9958     if (ParamD->getDeclName())
9959       S.Diag(Templated->getLocation(),
9960              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9961           << ParamD->getDeclName();
9962     else {
9963       int index = 0;
9964       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9965         index = TTP->getIndex();
9966       else if (NonTypeTemplateParmDecl *NTTP
9967                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9968         index = NTTP->getIndex();
9969       else
9970         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9971       S.Diag(Templated->getLocation(),
9972              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9973           << (index + 1);
9974     }
9975     MaybeEmitInheritedConstructorNote(S, Found);
9976     return;
9977 
9978   case Sema::TDK_TooManyArguments:
9979   case Sema::TDK_TooFewArguments:
9980     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9981     return;
9982 
9983   case Sema::TDK_InstantiationDepth:
9984     S.Diag(Templated->getLocation(),
9985            diag::note_ovl_candidate_instantiation_depth);
9986     MaybeEmitInheritedConstructorNote(S, Found);
9987     return;
9988 
9989   case Sema::TDK_SubstitutionFailure: {
9990     // Format the template argument list into the argument string.
9991     SmallString<128> TemplateArgString;
9992     if (TemplateArgumentList *Args =
9993             DeductionFailure.getTemplateArgumentList()) {
9994       TemplateArgString = " ";
9995       TemplateArgString += S.getTemplateArgumentBindingsText(
9996           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9997     }
9998 
9999     // If this candidate was disabled by enable_if, say so.
10000     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10001     if (PDiag && PDiag->second.getDiagID() ==
10002           diag::err_typename_nested_not_found_enable_if) {
10003       // FIXME: Use the source range of the condition, and the fully-qualified
10004       //        name of the enable_if template. These are both present in PDiag.
10005       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10006         << "'enable_if'" << TemplateArgString;
10007       return;
10008     }
10009 
10010     // We found a specific requirement that disabled the enable_if.
10011     if (PDiag && PDiag->second.getDiagID() ==
10012         diag::err_typename_nested_not_found_requirement) {
10013       S.Diag(Templated->getLocation(),
10014              diag::note_ovl_candidate_disabled_by_requirement)
10015         << PDiag->second.getStringArg(0) << TemplateArgString;
10016       return;
10017     }
10018 
10019     // Format the SFINAE diagnostic into the argument string.
10020     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10021     //        formatted message in another diagnostic.
10022     SmallString<128> SFINAEArgString;
10023     SourceRange R;
10024     if (PDiag) {
10025       SFINAEArgString = ": ";
10026       R = SourceRange(PDiag->first, PDiag->first);
10027       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10028     }
10029 
10030     S.Diag(Templated->getLocation(),
10031            diag::note_ovl_candidate_substitution_failure)
10032         << TemplateArgString << SFINAEArgString << R;
10033     MaybeEmitInheritedConstructorNote(S, Found);
10034     return;
10035   }
10036 
10037   case Sema::TDK_DeducedMismatch:
10038   case Sema::TDK_DeducedMismatchNested: {
10039     // Format the template argument list into the argument string.
10040     SmallString<128> TemplateArgString;
10041     if (TemplateArgumentList *Args =
10042             DeductionFailure.getTemplateArgumentList()) {
10043       TemplateArgString = " ";
10044       TemplateArgString += S.getTemplateArgumentBindingsText(
10045           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10046     }
10047 
10048     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10049         << (*DeductionFailure.getCallArgIndex() + 1)
10050         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10051         << TemplateArgString
10052         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10053     break;
10054   }
10055 
10056   case Sema::TDK_NonDeducedMismatch: {
10057     // FIXME: Provide a source location to indicate what we couldn't match.
10058     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10059     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10060     if (FirstTA.getKind() == TemplateArgument::Template &&
10061         SecondTA.getKind() == TemplateArgument::Template) {
10062       TemplateName FirstTN = FirstTA.getAsTemplate();
10063       TemplateName SecondTN = SecondTA.getAsTemplate();
10064       if (FirstTN.getKind() == TemplateName::Template &&
10065           SecondTN.getKind() == TemplateName::Template) {
10066         if (FirstTN.getAsTemplateDecl()->getName() ==
10067             SecondTN.getAsTemplateDecl()->getName()) {
10068           // FIXME: This fixes a bad diagnostic where both templates are named
10069           // the same.  This particular case is a bit difficult since:
10070           // 1) It is passed as a string to the diagnostic printer.
10071           // 2) The diagnostic printer only attempts to find a better
10072           //    name for types, not decls.
10073           // Ideally, this should folded into the diagnostic printer.
10074           S.Diag(Templated->getLocation(),
10075                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10076               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10077           return;
10078         }
10079       }
10080     }
10081 
10082     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10083         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10084       return;
10085 
10086     // FIXME: For generic lambda parameters, check if the function is a lambda
10087     // call operator, and if so, emit a prettier and more informative
10088     // diagnostic that mentions 'auto' and lambda in addition to
10089     // (or instead of?) the canonical template type parameters.
10090     S.Diag(Templated->getLocation(),
10091            diag::note_ovl_candidate_non_deduced_mismatch)
10092         << FirstTA << SecondTA;
10093     return;
10094   }
10095   // TODO: diagnose these individually, then kill off
10096   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10097   case Sema::TDK_MiscellaneousDeductionFailure:
10098     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10099     MaybeEmitInheritedConstructorNote(S, Found);
10100     return;
10101   case Sema::TDK_CUDATargetMismatch:
10102     S.Diag(Templated->getLocation(),
10103            diag::note_cuda_ovl_candidate_target_mismatch);
10104     return;
10105   }
10106 }
10107 
10108 /// Diagnose a failed template-argument deduction, for function calls.
10109 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10110                                  unsigned NumArgs,
10111                                  bool TakingCandidateAddress) {
10112   unsigned TDK = Cand->DeductionFailure.Result;
10113   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10114     if (CheckArityMismatch(S, Cand, NumArgs))
10115       return;
10116   }
10117   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10118                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10119 }
10120 
10121 /// CUDA: diagnose an invalid call across targets.
10122 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10123   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10124   FunctionDecl *Callee = Cand->Function;
10125 
10126   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10127                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10128 
10129   std::string FnDesc;
10130   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10131       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10132 
10133   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10134       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10135       << FnDesc /* Ignored */
10136       << CalleeTarget << CallerTarget;
10137 
10138   // This could be an implicit constructor for which we could not infer the
10139   // target due to a collsion. Diagnose that case.
10140   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10141   if (Meth != nullptr && Meth->isImplicit()) {
10142     CXXRecordDecl *ParentClass = Meth->getParent();
10143     Sema::CXXSpecialMember CSM;
10144 
10145     switch (FnKindPair.first) {
10146     default:
10147       return;
10148     case oc_implicit_default_constructor:
10149       CSM = Sema::CXXDefaultConstructor;
10150       break;
10151     case oc_implicit_copy_constructor:
10152       CSM = Sema::CXXCopyConstructor;
10153       break;
10154     case oc_implicit_move_constructor:
10155       CSM = Sema::CXXMoveConstructor;
10156       break;
10157     case oc_implicit_copy_assignment:
10158       CSM = Sema::CXXCopyAssignment;
10159       break;
10160     case oc_implicit_move_assignment:
10161       CSM = Sema::CXXMoveAssignment;
10162       break;
10163     };
10164 
10165     bool ConstRHS = false;
10166     if (Meth->getNumParams()) {
10167       if (const ReferenceType *RT =
10168               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10169         ConstRHS = RT->getPointeeType().isConstQualified();
10170       }
10171     }
10172 
10173     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10174                                               /* ConstRHS */ ConstRHS,
10175                                               /* Diagnose */ true);
10176   }
10177 }
10178 
10179 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10180   FunctionDecl *Callee = Cand->Function;
10181   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10182 
10183   S.Diag(Callee->getLocation(),
10184          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10185       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10186 }
10187 
10188 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10189   FunctionDecl *Callee = Cand->Function;
10190 
10191   S.Diag(Callee->getLocation(),
10192          diag::note_ovl_candidate_disabled_by_extension);
10193 }
10194 
10195 /// Generates a 'note' diagnostic for an overload candidate.  We've
10196 /// already generated a primary error at the call site.
10197 ///
10198 /// It really does need to be a single diagnostic with its caret
10199 /// pointed at the candidate declaration.  Yes, this creates some
10200 /// major challenges of technical writing.  Yes, this makes pointing
10201 /// out problems with specific arguments quite awkward.  It's still
10202 /// better than generating twenty screens of text for every failed
10203 /// overload.
10204 ///
10205 /// It would be great to be able to express per-candidate problems
10206 /// more richly for those diagnostic clients that cared, but we'd
10207 /// still have to be just as careful with the default diagnostics.
10208 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10209                                   unsigned NumArgs,
10210                                   bool TakingCandidateAddress) {
10211   FunctionDecl *Fn = Cand->Function;
10212 
10213   // Note deleted candidates, but only if they're viable.
10214   if (Cand->Viable) {
10215     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10216       std::string FnDesc;
10217       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10218           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10219 
10220       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10221           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10222           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10223       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10224       return;
10225     }
10226 
10227     // We don't really have anything else to say about viable candidates.
10228     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10229     return;
10230   }
10231 
10232   switch (Cand->FailureKind) {
10233   case ovl_fail_too_many_arguments:
10234   case ovl_fail_too_few_arguments:
10235     return DiagnoseArityMismatch(S, Cand, NumArgs);
10236 
10237   case ovl_fail_bad_deduction:
10238     return DiagnoseBadDeduction(S, Cand, NumArgs,
10239                                 TakingCandidateAddress);
10240 
10241   case ovl_fail_illegal_constructor: {
10242     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10243       << (Fn->getPrimaryTemplate() ? 1 : 0);
10244     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10245     return;
10246   }
10247 
10248   case ovl_fail_trivial_conversion:
10249   case ovl_fail_bad_final_conversion:
10250   case ovl_fail_final_conversion_not_exact:
10251     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10252 
10253   case ovl_fail_bad_conversion: {
10254     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10255     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10256       if (Cand->Conversions[I].isBad())
10257         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10258 
10259     // FIXME: this currently happens when we're called from SemaInit
10260     // when user-conversion overload fails.  Figure out how to handle
10261     // those conditions and diagnose them well.
10262     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10263   }
10264 
10265   case ovl_fail_bad_target:
10266     return DiagnoseBadTarget(S, Cand);
10267 
10268   case ovl_fail_enable_if:
10269     return DiagnoseFailedEnableIfAttr(S, Cand);
10270 
10271   case ovl_fail_ext_disabled:
10272     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10273 
10274   case ovl_fail_inhctor_slice:
10275     // It's generally not interesting to note copy/move constructors here.
10276     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10277       return;
10278     S.Diag(Fn->getLocation(),
10279            diag::note_ovl_candidate_inherited_constructor_slice)
10280       << (Fn->getPrimaryTemplate() ? 1 : 0)
10281       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10282     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10283     return;
10284 
10285   case ovl_fail_addr_not_available: {
10286     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10287     (void)Available;
10288     assert(!Available);
10289     break;
10290   }
10291   case ovl_non_default_multiversion_function:
10292     // Do nothing, these should simply be ignored.
10293     break;
10294   }
10295 }
10296 
10297 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10298   // Desugar the type of the surrogate down to a function type,
10299   // retaining as many typedefs as possible while still showing
10300   // the function type (and, therefore, its parameter types).
10301   QualType FnType = Cand->Surrogate->getConversionType();
10302   bool isLValueReference = false;
10303   bool isRValueReference = false;
10304   bool isPointer = false;
10305   if (const LValueReferenceType *FnTypeRef =
10306         FnType->getAs<LValueReferenceType>()) {
10307     FnType = FnTypeRef->getPointeeType();
10308     isLValueReference = true;
10309   } else if (const RValueReferenceType *FnTypeRef =
10310                FnType->getAs<RValueReferenceType>()) {
10311     FnType = FnTypeRef->getPointeeType();
10312     isRValueReference = true;
10313   }
10314   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10315     FnType = FnTypePtr->getPointeeType();
10316     isPointer = true;
10317   }
10318   // Desugar down to a function type.
10319   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10320   // Reconstruct the pointer/reference as appropriate.
10321   if (isPointer) FnType = S.Context.getPointerType(FnType);
10322   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10323   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10324 
10325   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10326     << FnType;
10327 }
10328 
10329 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10330                                          SourceLocation OpLoc,
10331                                          OverloadCandidate *Cand) {
10332   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10333   std::string TypeStr("operator");
10334   TypeStr += Opc;
10335   TypeStr += "(";
10336   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10337   if (Cand->Conversions.size() == 1) {
10338     TypeStr += ")";
10339     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10340   } else {
10341     TypeStr += ", ";
10342     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10343     TypeStr += ")";
10344     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10345   }
10346 }
10347 
10348 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10349                                          OverloadCandidate *Cand) {
10350   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10351     if (ICS.isBad()) break; // all meaningless after first invalid
10352     if (!ICS.isAmbiguous()) continue;
10353 
10354     ICS.DiagnoseAmbiguousConversion(
10355         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10356   }
10357 }
10358 
10359 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10360   if (Cand->Function)
10361     return Cand->Function->getLocation();
10362   if (Cand->IsSurrogate)
10363     return Cand->Surrogate->getLocation();
10364   return SourceLocation();
10365 }
10366 
10367 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10368   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10369   case Sema::TDK_Success:
10370   case Sema::TDK_NonDependentConversionFailure:
10371     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10372 
10373   case Sema::TDK_Invalid:
10374   case Sema::TDK_Incomplete:
10375     return 1;
10376 
10377   case Sema::TDK_Underqualified:
10378   case Sema::TDK_Inconsistent:
10379     return 2;
10380 
10381   case Sema::TDK_SubstitutionFailure:
10382   case Sema::TDK_DeducedMismatch:
10383   case Sema::TDK_DeducedMismatchNested:
10384   case Sema::TDK_NonDeducedMismatch:
10385   case Sema::TDK_MiscellaneousDeductionFailure:
10386   case Sema::TDK_CUDATargetMismatch:
10387     return 3;
10388 
10389   case Sema::TDK_InstantiationDepth:
10390     return 4;
10391 
10392   case Sema::TDK_InvalidExplicitArguments:
10393     return 5;
10394 
10395   case Sema::TDK_TooManyArguments:
10396   case Sema::TDK_TooFewArguments:
10397     return 6;
10398   }
10399   llvm_unreachable("Unhandled deduction result");
10400 }
10401 
10402 namespace {
10403 struct CompareOverloadCandidatesForDisplay {
10404   Sema &S;
10405   SourceLocation Loc;
10406   size_t NumArgs;
10407   OverloadCandidateSet::CandidateSetKind CSK;
10408 
10409   CompareOverloadCandidatesForDisplay(
10410       Sema &S, SourceLocation Loc, size_t NArgs,
10411       OverloadCandidateSet::CandidateSetKind CSK)
10412       : S(S), NumArgs(NArgs), CSK(CSK) {}
10413 
10414   bool operator()(const OverloadCandidate *L,
10415                   const OverloadCandidate *R) {
10416     // Fast-path this check.
10417     if (L == R) return false;
10418 
10419     // Order first by viability.
10420     if (L->Viable) {
10421       if (!R->Viable) return true;
10422 
10423       // TODO: introduce a tri-valued comparison for overload
10424       // candidates.  Would be more worthwhile if we had a sort
10425       // that could exploit it.
10426       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10427         return true;
10428       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10429         return false;
10430     } else if (R->Viable)
10431       return false;
10432 
10433     assert(L->Viable == R->Viable);
10434 
10435     // Criteria by which we can sort non-viable candidates:
10436     if (!L->Viable) {
10437       // 1. Arity mismatches come after other candidates.
10438       if (L->FailureKind == ovl_fail_too_many_arguments ||
10439           L->FailureKind == ovl_fail_too_few_arguments) {
10440         if (R->FailureKind == ovl_fail_too_many_arguments ||
10441             R->FailureKind == ovl_fail_too_few_arguments) {
10442           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10443           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10444           if (LDist == RDist) {
10445             if (L->FailureKind == R->FailureKind)
10446               // Sort non-surrogates before surrogates.
10447               return !L->IsSurrogate && R->IsSurrogate;
10448             // Sort candidates requiring fewer parameters than there were
10449             // arguments given after candidates requiring more parameters
10450             // than there were arguments given.
10451             return L->FailureKind == ovl_fail_too_many_arguments;
10452           }
10453           return LDist < RDist;
10454         }
10455         return false;
10456       }
10457       if (R->FailureKind == ovl_fail_too_many_arguments ||
10458           R->FailureKind == ovl_fail_too_few_arguments)
10459         return true;
10460 
10461       // 2. Bad conversions come first and are ordered by the number
10462       // of bad conversions and quality of good conversions.
10463       if (L->FailureKind == ovl_fail_bad_conversion) {
10464         if (R->FailureKind != ovl_fail_bad_conversion)
10465           return true;
10466 
10467         // The conversion that can be fixed with a smaller number of changes,
10468         // comes first.
10469         unsigned numLFixes = L->Fix.NumConversionsFixed;
10470         unsigned numRFixes = R->Fix.NumConversionsFixed;
10471         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10472         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10473         if (numLFixes != numRFixes) {
10474           return numLFixes < numRFixes;
10475         }
10476 
10477         // If there's any ordering between the defined conversions...
10478         // FIXME: this might not be transitive.
10479         assert(L->Conversions.size() == R->Conversions.size());
10480 
10481         int leftBetter = 0;
10482         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10483         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10484           switch (CompareImplicitConversionSequences(S, Loc,
10485                                                      L->Conversions[I],
10486                                                      R->Conversions[I])) {
10487           case ImplicitConversionSequence::Better:
10488             leftBetter++;
10489             break;
10490 
10491           case ImplicitConversionSequence::Worse:
10492             leftBetter--;
10493             break;
10494 
10495           case ImplicitConversionSequence::Indistinguishable:
10496             break;
10497           }
10498         }
10499         if (leftBetter > 0) return true;
10500         if (leftBetter < 0) return false;
10501 
10502       } else if (R->FailureKind == ovl_fail_bad_conversion)
10503         return false;
10504 
10505       if (L->FailureKind == ovl_fail_bad_deduction) {
10506         if (R->FailureKind != ovl_fail_bad_deduction)
10507           return true;
10508 
10509         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10510           return RankDeductionFailure(L->DeductionFailure)
10511                < RankDeductionFailure(R->DeductionFailure);
10512       } else if (R->FailureKind == ovl_fail_bad_deduction)
10513         return false;
10514 
10515       // TODO: others?
10516     }
10517 
10518     // Sort everything else by location.
10519     SourceLocation LLoc = GetLocationForCandidate(L);
10520     SourceLocation RLoc = GetLocationForCandidate(R);
10521 
10522     // Put candidates without locations (e.g. builtins) at the end.
10523     if (LLoc.isInvalid()) return false;
10524     if (RLoc.isInvalid()) return true;
10525 
10526     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10527   }
10528 };
10529 }
10530 
10531 /// CompleteNonViableCandidate - Normally, overload resolution only
10532 /// computes up to the first bad conversion. Produces the FixIt set if
10533 /// possible.
10534 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10535                                        ArrayRef<Expr *> Args) {
10536   assert(!Cand->Viable);
10537 
10538   // Don't do anything on failures other than bad conversion.
10539   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10540 
10541   // We only want the FixIts if all the arguments can be corrected.
10542   bool Unfixable = false;
10543   // Use a implicit copy initialization to check conversion fixes.
10544   Cand->Fix.setConversionChecker(TryCopyInitialization);
10545 
10546   // Attempt to fix the bad conversion.
10547   unsigned ConvCount = Cand->Conversions.size();
10548   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10549        ++ConvIdx) {
10550     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10551     if (Cand->Conversions[ConvIdx].isInitialized() &&
10552         Cand->Conversions[ConvIdx].isBad()) {
10553       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10554       break;
10555     }
10556   }
10557 
10558   // FIXME: this should probably be preserved from the overload
10559   // operation somehow.
10560   bool SuppressUserConversions = false;
10561 
10562   unsigned ConvIdx = 0;
10563   ArrayRef<QualType> ParamTypes;
10564 
10565   if (Cand->IsSurrogate) {
10566     QualType ConvType
10567       = Cand->Surrogate->getConversionType().getNonReferenceType();
10568     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10569       ConvType = ConvPtrType->getPointeeType();
10570     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10571     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10572     ConvIdx = 1;
10573   } else if (Cand->Function) {
10574     ParamTypes =
10575         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10576     if (isa<CXXMethodDecl>(Cand->Function) &&
10577         !isa<CXXConstructorDecl>(Cand->Function)) {
10578       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10579       ConvIdx = 1;
10580     }
10581   } else {
10582     // Builtin operator.
10583     assert(ConvCount <= 3);
10584     ParamTypes = Cand->BuiltinParamTypes;
10585   }
10586 
10587   // Fill in the rest of the conversions.
10588   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10589     if (Cand->Conversions[ConvIdx].isInitialized()) {
10590       // We've already checked this conversion.
10591     } else if (ArgIdx < ParamTypes.size()) {
10592       if (ParamTypes[ArgIdx]->isDependentType())
10593         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10594             Args[ArgIdx]->getType());
10595       else {
10596         Cand->Conversions[ConvIdx] =
10597             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10598                                   SuppressUserConversions,
10599                                   /*InOverloadResolution=*/true,
10600                                   /*AllowObjCWritebackConversion=*/
10601                                   S.getLangOpts().ObjCAutoRefCount);
10602         // Store the FixIt in the candidate if it exists.
10603         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10604           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10605       }
10606     } else
10607       Cand->Conversions[ConvIdx].setEllipsis();
10608   }
10609 }
10610 
10611 /// When overload resolution fails, prints diagnostic messages containing the
10612 /// candidates in the candidate set.
10613 void OverloadCandidateSet::NoteCandidates(
10614     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10615     StringRef Opc, SourceLocation OpLoc,
10616     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10617   // Sort the candidates by viability and position.  Sorting directly would
10618   // be prohibitive, so we make a set of pointers and sort those.
10619   SmallVector<OverloadCandidate*, 32> Cands;
10620   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10621   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10622     if (!Filter(*Cand))
10623       continue;
10624     if (Cand->Viable)
10625       Cands.push_back(Cand);
10626     else if (OCD == OCD_AllCandidates) {
10627       CompleteNonViableCandidate(S, Cand, Args);
10628       if (Cand->Function || Cand->IsSurrogate)
10629         Cands.push_back(Cand);
10630       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10631       // want to list every possible builtin candidate.
10632     }
10633   }
10634 
10635   std::stable_sort(Cands.begin(), Cands.end(),
10636             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10637 
10638   bool ReportedAmbiguousConversions = false;
10639 
10640   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10641   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10642   unsigned CandsShown = 0;
10643   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10644     OverloadCandidate *Cand = *I;
10645 
10646     // Set an arbitrary limit on the number of candidate functions we'll spam
10647     // the user with.  FIXME: This limit should depend on details of the
10648     // candidate list.
10649     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10650       break;
10651     }
10652     ++CandsShown;
10653 
10654     if (Cand->Function)
10655       NoteFunctionCandidate(S, Cand, Args.size(),
10656                             /*TakingCandidateAddress=*/false);
10657     else if (Cand->IsSurrogate)
10658       NoteSurrogateCandidate(S, Cand);
10659     else {
10660       assert(Cand->Viable &&
10661              "Non-viable built-in candidates are not added to Cands.");
10662       // Generally we only see ambiguities including viable builtin
10663       // operators if overload resolution got screwed up by an
10664       // ambiguous user-defined conversion.
10665       //
10666       // FIXME: It's quite possible for different conversions to see
10667       // different ambiguities, though.
10668       if (!ReportedAmbiguousConversions) {
10669         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10670         ReportedAmbiguousConversions = true;
10671       }
10672 
10673       // If this is a viable builtin, print it.
10674       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10675     }
10676   }
10677 
10678   if (I != E)
10679     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10680 }
10681 
10682 static SourceLocation
10683 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10684   return Cand->Specialization ? Cand->Specialization->getLocation()
10685                               : SourceLocation();
10686 }
10687 
10688 namespace {
10689 struct CompareTemplateSpecCandidatesForDisplay {
10690   Sema &S;
10691   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10692 
10693   bool operator()(const TemplateSpecCandidate *L,
10694                   const TemplateSpecCandidate *R) {
10695     // Fast-path this check.
10696     if (L == R)
10697       return false;
10698 
10699     // Assuming that both candidates are not matches...
10700 
10701     // Sort by the ranking of deduction failures.
10702     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10703       return RankDeductionFailure(L->DeductionFailure) <
10704              RankDeductionFailure(R->DeductionFailure);
10705 
10706     // Sort everything else by location.
10707     SourceLocation LLoc = GetLocationForCandidate(L);
10708     SourceLocation RLoc = GetLocationForCandidate(R);
10709 
10710     // Put candidates without locations (e.g. builtins) at the end.
10711     if (LLoc.isInvalid())
10712       return false;
10713     if (RLoc.isInvalid())
10714       return true;
10715 
10716     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10717   }
10718 };
10719 }
10720 
10721 /// Diagnose a template argument deduction failure.
10722 /// We are treating these failures as overload failures due to bad
10723 /// deductions.
10724 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10725                                                  bool ForTakingAddress) {
10726   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10727                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10728 }
10729 
10730 void TemplateSpecCandidateSet::destroyCandidates() {
10731   for (iterator i = begin(), e = end(); i != e; ++i) {
10732     i->DeductionFailure.Destroy();
10733   }
10734 }
10735 
10736 void TemplateSpecCandidateSet::clear() {
10737   destroyCandidates();
10738   Candidates.clear();
10739 }
10740 
10741 /// NoteCandidates - When no template specialization match is found, prints
10742 /// diagnostic messages containing the non-matching specializations that form
10743 /// the candidate set.
10744 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10745 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10746 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10747   // Sort the candidates by position (assuming no candidate is a match).
10748   // Sorting directly would be prohibitive, so we make a set of pointers
10749   // and sort those.
10750   SmallVector<TemplateSpecCandidate *, 32> Cands;
10751   Cands.reserve(size());
10752   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10753     if (Cand->Specialization)
10754       Cands.push_back(Cand);
10755     // Otherwise, this is a non-matching builtin candidate.  We do not,
10756     // in general, want to list every possible builtin candidate.
10757   }
10758 
10759   llvm::sort(Cands.begin(), Cands.end(),
10760              CompareTemplateSpecCandidatesForDisplay(S));
10761 
10762   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10763   // for generalization purposes (?).
10764   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10765 
10766   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10767   unsigned CandsShown = 0;
10768   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10769     TemplateSpecCandidate *Cand = *I;
10770 
10771     // Set an arbitrary limit on the number of candidates we'll spam
10772     // the user with.  FIXME: This limit should depend on details of the
10773     // candidate list.
10774     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10775       break;
10776     ++CandsShown;
10777 
10778     assert(Cand->Specialization &&
10779            "Non-matching built-in candidates are not added to Cands.");
10780     Cand->NoteDeductionFailure(S, ForTakingAddress);
10781   }
10782 
10783   if (I != E)
10784     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10785 }
10786 
10787 // [PossiblyAFunctionType]  -->   [Return]
10788 // NonFunctionType --> NonFunctionType
10789 // R (A) --> R(A)
10790 // R (*)(A) --> R (A)
10791 // R (&)(A) --> R (A)
10792 // R (S::*)(A) --> R (A)
10793 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10794   QualType Ret = PossiblyAFunctionType;
10795   if (const PointerType *ToTypePtr =
10796     PossiblyAFunctionType->getAs<PointerType>())
10797     Ret = ToTypePtr->getPointeeType();
10798   else if (const ReferenceType *ToTypeRef =
10799     PossiblyAFunctionType->getAs<ReferenceType>())
10800     Ret = ToTypeRef->getPointeeType();
10801   else if (const MemberPointerType *MemTypePtr =
10802     PossiblyAFunctionType->getAs<MemberPointerType>())
10803     Ret = MemTypePtr->getPointeeType();
10804   Ret =
10805     Context.getCanonicalType(Ret).getUnqualifiedType();
10806   return Ret;
10807 }
10808 
10809 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10810                                  bool Complain = true) {
10811   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10812       S.DeduceReturnType(FD, Loc, Complain))
10813     return true;
10814 
10815   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10816   if (S.getLangOpts().CPlusPlus17 &&
10817       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10818       !S.ResolveExceptionSpec(Loc, FPT))
10819     return true;
10820 
10821   return false;
10822 }
10823 
10824 namespace {
10825 // A helper class to help with address of function resolution
10826 // - allows us to avoid passing around all those ugly parameters
10827 class AddressOfFunctionResolver {
10828   Sema& S;
10829   Expr* SourceExpr;
10830   const QualType& TargetType;
10831   QualType TargetFunctionType; // Extracted function type from target type
10832 
10833   bool Complain;
10834   //DeclAccessPair& ResultFunctionAccessPair;
10835   ASTContext& Context;
10836 
10837   bool TargetTypeIsNonStaticMemberFunction;
10838   bool FoundNonTemplateFunction;
10839   bool StaticMemberFunctionFromBoundPointer;
10840   bool HasComplained;
10841 
10842   OverloadExpr::FindResult OvlExprInfo;
10843   OverloadExpr *OvlExpr;
10844   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10845   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10846   TemplateSpecCandidateSet FailedCandidates;
10847 
10848 public:
10849   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10850                             const QualType &TargetType, bool Complain)
10851       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10852         Complain(Complain), Context(S.getASTContext()),
10853         TargetTypeIsNonStaticMemberFunction(
10854             !!TargetType->getAs<MemberPointerType>()),
10855         FoundNonTemplateFunction(false),
10856         StaticMemberFunctionFromBoundPointer(false),
10857         HasComplained(false),
10858         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10859         OvlExpr(OvlExprInfo.Expression),
10860         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10861     ExtractUnqualifiedFunctionTypeFromTargetType();
10862 
10863     if (TargetFunctionType->isFunctionType()) {
10864       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10865         if (!UME->isImplicitAccess() &&
10866             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10867           StaticMemberFunctionFromBoundPointer = true;
10868     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10869       DeclAccessPair dap;
10870       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10871               OvlExpr, false, &dap)) {
10872         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10873           if (!Method->isStatic()) {
10874             // If the target type is a non-function type and the function found
10875             // is a non-static member function, pretend as if that was the
10876             // target, it's the only possible type to end up with.
10877             TargetTypeIsNonStaticMemberFunction = true;
10878 
10879             // And skip adding the function if its not in the proper form.
10880             // We'll diagnose this due to an empty set of functions.
10881             if (!OvlExprInfo.HasFormOfMemberPointer)
10882               return;
10883           }
10884 
10885         Matches.push_back(std::make_pair(dap, Fn));
10886       }
10887       return;
10888     }
10889 
10890     if (OvlExpr->hasExplicitTemplateArgs())
10891       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10892 
10893     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10894       // C++ [over.over]p4:
10895       //   If more than one function is selected, [...]
10896       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10897         if (FoundNonTemplateFunction)
10898           EliminateAllTemplateMatches();
10899         else
10900           EliminateAllExceptMostSpecializedTemplate();
10901       }
10902     }
10903 
10904     if (S.getLangOpts().CUDA && Matches.size() > 1)
10905       EliminateSuboptimalCudaMatches();
10906   }
10907 
10908   bool hasComplained() const { return HasComplained; }
10909 
10910 private:
10911   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10912     QualType Discard;
10913     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10914            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10915   }
10916 
10917   /// \return true if A is considered a better overload candidate for the
10918   /// desired type than B.
10919   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10920     // If A doesn't have exactly the correct type, we don't want to classify it
10921     // as "better" than anything else. This way, the user is required to
10922     // disambiguate for us if there are multiple candidates and no exact match.
10923     return candidateHasExactlyCorrectType(A) &&
10924            (!candidateHasExactlyCorrectType(B) ||
10925             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10926   }
10927 
10928   /// \return true if we were able to eliminate all but one overload candidate,
10929   /// false otherwise.
10930   bool eliminiateSuboptimalOverloadCandidates() {
10931     // Same algorithm as overload resolution -- one pass to pick the "best",
10932     // another pass to be sure that nothing is better than the best.
10933     auto Best = Matches.begin();
10934     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10935       if (isBetterCandidate(I->second, Best->second))
10936         Best = I;
10937 
10938     const FunctionDecl *BestFn = Best->second;
10939     auto IsBestOrInferiorToBest = [this, BestFn](
10940         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10941       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10942     };
10943 
10944     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10945     // option, so we can potentially give the user a better error
10946     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10947       return false;
10948     Matches[0] = *Best;
10949     Matches.resize(1);
10950     return true;
10951   }
10952 
10953   bool isTargetTypeAFunction() const {
10954     return TargetFunctionType->isFunctionType();
10955   }
10956 
10957   // [ToType]     [Return]
10958 
10959   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10960   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10961   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10962   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10963     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10964   }
10965 
10966   // return true if any matching specializations were found
10967   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10968                                    const DeclAccessPair& CurAccessFunPair) {
10969     if (CXXMethodDecl *Method
10970               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10971       // Skip non-static function templates when converting to pointer, and
10972       // static when converting to member pointer.
10973       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10974         return false;
10975     }
10976     else if (TargetTypeIsNonStaticMemberFunction)
10977       return false;
10978 
10979     // C++ [over.over]p2:
10980     //   If the name is a function template, template argument deduction is
10981     //   done (14.8.2.2), and if the argument deduction succeeds, the
10982     //   resulting template argument list is used to generate a single
10983     //   function template specialization, which is added to the set of
10984     //   overloaded functions considered.
10985     FunctionDecl *Specialization = nullptr;
10986     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10987     if (Sema::TemplateDeductionResult Result
10988           = S.DeduceTemplateArguments(FunctionTemplate,
10989                                       &OvlExplicitTemplateArgs,
10990                                       TargetFunctionType, Specialization,
10991                                       Info, /*IsAddressOfFunction*/true)) {
10992       // Make a note of the failed deduction for diagnostics.
10993       FailedCandidates.addCandidate()
10994           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10995                MakeDeductionFailureInfo(Context, Result, Info));
10996       return false;
10997     }
10998 
10999     // Template argument deduction ensures that we have an exact match or
11000     // compatible pointer-to-function arguments that would be adjusted by ICS.
11001     // This function template specicalization works.
11002     assert(S.isSameOrCompatibleFunctionType(
11003               Context.getCanonicalType(Specialization->getType()),
11004               Context.getCanonicalType(TargetFunctionType)));
11005 
11006     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11007       return false;
11008 
11009     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11010     return true;
11011   }
11012 
11013   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11014                                       const DeclAccessPair& CurAccessFunPair) {
11015     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11016       // Skip non-static functions when converting to pointer, and static
11017       // when converting to member pointer.
11018       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11019         return false;
11020     }
11021     else if (TargetTypeIsNonStaticMemberFunction)
11022       return false;
11023 
11024     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11025       if (S.getLangOpts().CUDA)
11026         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11027           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11028             return false;
11029       if (FunDecl->isMultiVersion()) {
11030         const auto *TA = FunDecl->getAttr<TargetAttr>();
11031         assert(TA && "Multiversioned functions require a target attribute");
11032         if (!TA->isDefaultVersion())
11033           return false;
11034       }
11035 
11036       // If any candidate has a placeholder return type, trigger its deduction
11037       // now.
11038       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11039                                Complain)) {
11040         HasComplained |= Complain;
11041         return false;
11042       }
11043 
11044       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11045         return false;
11046 
11047       // If we're in C, we need to support types that aren't exactly identical.
11048       if (!S.getLangOpts().CPlusPlus ||
11049           candidateHasExactlyCorrectType(FunDecl)) {
11050         Matches.push_back(std::make_pair(
11051             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11052         FoundNonTemplateFunction = true;
11053         return true;
11054       }
11055     }
11056 
11057     return false;
11058   }
11059 
11060   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11061     bool Ret = false;
11062 
11063     // If the overload expression doesn't have the form of a pointer to
11064     // member, don't try to convert it to a pointer-to-member type.
11065     if (IsInvalidFormOfPointerToMemberFunction())
11066       return false;
11067 
11068     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11069                                E = OvlExpr->decls_end();
11070          I != E; ++I) {
11071       // Look through any using declarations to find the underlying function.
11072       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11073 
11074       // C++ [over.over]p3:
11075       //   Non-member functions and static member functions match
11076       //   targets of type "pointer-to-function" or "reference-to-function."
11077       //   Nonstatic member functions match targets of
11078       //   type "pointer-to-member-function."
11079       // Note that according to DR 247, the containing class does not matter.
11080       if (FunctionTemplateDecl *FunctionTemplate
11081                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11082         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11083           Ret = true;
11084       }
11085       // If we have explicit template arguments supplied, skip non-templates.
11086       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11087                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11088         Ret = true;
11089     }
11090     assert(Ret || Matches.empty());
11091     return Ret;
11092   }
11093 
11094   void EliminateAllExceptMostSpecializedTemplate() {
11095     //   [...] and any given function template specialization F1 is
11096     //   eliminated if the set contains a second function template
11097     //   specialization whose function template is more specialized
11098     //   than the function template of F1 according to the partial
11099     //   ordering rules of 14.5.5.2.
11100 
11101     // The algorithm specified above is quadratic. We instead use a
11102     // two-pass algorithm (similar to the one used to identify the
11103     // best viable function in an overload set) that identifies the
11104     // best function template (if it exists).
11105 
11106     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11107     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11108       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11109 
11110     // TODO: It looks like FailedCandidates does not serve much purpose
11111     // here, since the no_viable diagnostic has index 0.
11112     UnresolvedSetIterator Result = S.getMostSpecialized(
11113         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11114         SourceExpr->getLocStart(), S.PDiag(),
11115         S.PDiag(diag::err_addr_ovl_ambiguous)
11116             << Matches[0].second->getDeclName(),
11117         S.PDiag(diag::note_ovl_candidate)
11118             << (unsigned)oc_function << (unsigned)ocs_described_template,
11119         Complain, TargetFunctionType);
11120 
11121     if (Result != MatchesCopy.end()) {
11122       // Make it the first and only element
11123       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11124       Matches[0].second = cast<FunctionDecl>(*Result);
11125       Matches.resize(1);
11126     } else
11127       HasComplained |= Complain;
11128   }
11129 
11130   void EliminateAllTemplateMatches() {
11131     //   [...] any function template specializations in the set are
11132     //   eliminated if the set also contains a non-template function, [...]
11133     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11134       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11135         ++I;
11136       else {
11137         Matches[I] = Matches[--N];
11138         Matches.resize(N);
11139       }
11140     }
11141   }
11142 
11143   void EliminateSuboptimalCudaMatches() {
11144     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11145   }
11146 
11147 public:
11148   void ComplainNoMatchesFound() const {
11149     assert(Matches.empty());
11150     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11151         << OvlExpr->getName() << TargetFunctionType
11152         << OvlExpr->getSourceRange();
11153     if (FailedCandidates.empty())
11154       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11155                                   /*TakingAddress=*/true);
11156     else {
11157       // We have some deduction failure messages. Use them to diagnose
11158       // the function templates, and diagnose the non-template candidates
11159       // normally.
11160       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11161                                  IEnd = OvlExpr->decls_end();
11162            I != IEnd; ++I)
11163         if (FunctionDecl *Fun =
11164                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11165           if (!functionHasPassObjectSizeParams(Fun))
11166             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11167                                     /*TakingAddress=*/true);
11168       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11169     }
11170   }
11171 
11172   bool IsInvalidFormOfPointerToMemberFunction() const {
11173     return TargetTypeIsNonStaticMemberFunction &&
11174       !OvlExprInfo.HasFormOfMemberPointer;
11175   }
11176 
11177   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11178       // TODO: Should we condition this on whether any functions might
11179       // have matched, or is it more appropriate to do that in callers?
11180       // TODO: a fixit wouldn't hurt.
11181       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11182         << TargetType << OvlExpr->getSourceRange();
11183   }
11184 
11185   bool IsStaticMemberFunctionFromBoundPointer() const {
11186     return StaticMemberFunctionFromBoundPointer;
11187   }
11188 
11189   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11190     S.Diag(OvlExpr->getLocStart(),
11191            diag::err_invalid_form_pointer_member_function)
11192       << OvlExpr->getSourceRange();
11193   }
11194 
11195   void ComplainOfInvalidConversion() const {
11196     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11197       << OvlExpr->getName() << TargetType;
11198   }
11199 
11200   void ComplainMultipleMatchesFound() const {
11201     assert(Matches.size() > 1);
11202     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11203       << OvlExpr->getName()
11204       << OvlExpr->getSourceRange();
11205     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11206                                 /*TakingAddress=*/true);
11207   }
11208 
11209   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11210 
11211   int getNumMatches() const { return Matches.size(); }
11212 
11213   FunctionDecl* getMatchingFunctionDecl() const {
11214     if (Matches.size() != 1) return nullptr;
11215     return Matches[0].second;
11216   }
11217 
11218   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11219     if (Matches.size() != 1) return nullptr;
11220     return &Matches[0].first;
11221   }
11222 };
11223 }
11224 
11225 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11226 /// an overloaded function (C++ [over.over]), where @p From is an
11227 /// expression with overloaded function type and @p ToType is the type
11228 /// we're trying to resolve to. For example:
11229 ///
11230 /// @code
11231 /// int f(double);
11232 /// int f(int);
11233 ///
11234 /// int (*pfd)(double) = f; // selects f(double)
11235 /// @endcode
11236 ///
11237 /// This routine returns the resulting FunctionDecl if it could be
11238 /// resolved, and NULL otherwise. When @p Complain is true, this
11239 /// routine will emit diagnostics if there is an error.
11240 FunctionDecl *
11241 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11242                                          QualType TargetType,
11243                                          bool Complain,
11244                                          DeclAccessPair &FoundResult,
11245                                          bool *pHadMultipleCandidates) {
11246   assert(AddressOfExpr->getType() == Context.OverloadTy);
11247 
11248   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11249                                      Complain);
11250   int NumMatches = Resolver.getNumMatches();
11251   FunctionDecl *Fn = nullptr;
11252   bool ShouldComplain = Complain && !Resolver.hasComplained();
11253   if (NumMatches == 0 && ShouldComplain) {
11254     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11255       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11256     else
11257       Resolver.ComplainNoMatchesFound();
11258   }
11259   else if (NumMatches > 1 && ShouldComplain)
11260     Resolver.ComplainMultipleMatchesFound();
11261   else if (NumMatches == 1) {
11262     Fn = Resolver.getMatchingFunctionDecl();
11263     assert(Fn);
11264     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11265       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11266     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11267     if (Complain) {
11268       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11269         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11270       else
11271         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11272     }
11273   }
11274 
11275   if (pHadMultipleCandidates)
11276     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11277   return Fn;
11278 }
11279 
11280 /// Given an expression that refers to an overloaded function, try to
11281 /// resolve that function to a single function that can have its address taken.
11282 /// This will modify `Pair` iff it returns non-null.
11283 ///
11284 /// This routine can only realistically succeed if all but one candidates in the
11285 /// overload set for SrcExpr cannot have their addresses taken.
11286 FunctionDecl *
11287 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11288                                                   DeclAccessPair &Pair) {
11289   OverloadExpr::FindResult R = OverloadExpr::find(E);
11290   OverloadExpr *Ovl = R.Expression;
11291   FunctionDecl *Result = nullptr;
11292   DeclAccessPair DAP;
11293   // Don't use the AddressOfResolver because we're specifically looking for
11294   // cases where we have one overload candidate that lacks
11295   // enable_if/pass_object_size/...
11296   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11297     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11298     if (!FD)
11299       return nullptr;
11300 
11301     if (!checkAddressOfFunctionIsAvailable(FD))
11302       continue;
11303 
11304     // We have more than one result; quit.
11305     if (Result)
11306       return nullptr;
11307     DAP = I.getPair();
11308     Result = FD;
11309   }
11310 
11311   if (Result)
11312     Pair = DAP;
11313   return Result;
11314 }
11315 
11316 /// Given an overloaded function, tries to turn it into a non-overloaded
11317 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11318 /// will perform access checks, diagnose the use of the resultant decl, and, if
11319 /// requested, potentially perform a function-to-pointer decay.
11320 ///
11321 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11322 /// Otherwise, returns true. This may emit diagnostics and return true.
11323 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11324     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11325   Expr *E = SrcExpr.get();
11326   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11327 
11328   DeclAccessPair DAP;
11329   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11330   if (!Found)
11331     return false;
11332 
11333   // Emitting multiple diagnostics for a function that is both inaccessible and
11334   // unavailable is consistent with our behavior elsewhere. So, always check
11335   // for both.
11336   DiagnoseUseOfDecl(Found, E->getExprLoc());
11337   CheckAddressOfMemberAccess(E, DAP);
11338   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11339   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11340     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11341   else
11342     SrcExpr = Fixed;
11343   return true;
11344 }
11345 
11346 /// Given an expression that refers to an overloaded function, try to
11347 /// resolve that overloaded function expression down to a single function.
11348 ///
11349 /// This routine can only resolve template-ids that refer to a single function
11350 /// template, where that template-id refers to a single template whose template
11351 /// arguments are either provided by the template-id or have defaults,
11352 /// as described in C++0x [temp.arg.explicit]p3.
11353 ///
11354 /// If no template-ids are found, no diagnostics are emitted and NULL is
11355 /// returned.
11356 FunctionDecl *
11357 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11358                                                   bool Complain,
11359                                                   DeclAccessPair *FoundResult) {
11360   // C++ [over.over]p1:
11361   //   [...] [Note: any redundant set of parentheses surrounding the
11362   //   overloaded function name is ignored (5.1). ]
11363   // C++ [over.over]p1:
11364   //   [...] The overloaded function name can be preceded by the &
11365   //   operator.
11366 
11367   // If we didn't actually find any template-ids, we're done.
11368   if (!ovl->hasExplicitTemplateArgs())
11369     return nullptr;
11370 
11371   TemplateArgumentListInfo ExplicitTemplateArgs;
11372   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11373   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11374 
11375   // Look through all of the overloaded functions, searching for one
11376   // whose type matches exactly.
11377   FunctionDecl *Matched = nullptr;
11378   for (UnresolvedSetIterator I = ovl->decls_begin(),
11379          E = ovl->decls_end(); I != E; ++I) {
11380     // C++0x [temp.arg.explicit]p3:
11381     //   [...] In contexts where deduction is done and fails, or in contexts
11382     //   where deduction is not done, if a template argument list is
11383     //   specified and it, along with any default template arguments,
11384     //   identifies a single function template specialization, then the
11385     //   template-id is an lvalue for the function template specialization.
11386     FunctionTemplateDecl *FunctionTemplate
11387       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11388 
11389     // C++ [over.over]p2:
11390     //   If the name is a function template, template argument deduction is
11391     //   done (14.8.2.2), and if the argument deduction succeeds, the
11392     //   resulting template argument list is used to generate a single
11393     //   function template specialization, which is added to the set of
11394     //   overloaded functions considered.
11395     FunctionDecl *Specialization = nullptr;
11396     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11397     if (TemplateDeductionResult Result
11398           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11399                                     Specialization, Info,
11400                                     /*IsAddressOfFunction*/true)) {
11401       // Make a note of the failed deduction for diagnostics.
11402       // TODO: Actually use the failed-deduction info?
11403       FailedCandidates.addCandidate()
11404           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11405                MakeDeductionFailureInfo(Context, Result, Info));
11406       continue;
11407     }
11408 
11409     assert(Specialization && "no specialization and no error?");
11410 
11411     // Multiple matches; we can't resolve to a single declaration.
11412     if (Matched) {
11413       if (Complain) {
11414         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11415           << ovl->getName();
11416         NoteAllOverloadCandidates(ovl);
11417       }
11418       return nullptr;
11419     }
11420 
11421     Matched = Specialization;
11422     if (FoundResult) *FoundResult = I.getPair();
11423   }
11424 
11425   if (Matched &&
11426       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11427     return nullptr;
11428 
11429   return Matched;
11430 }
11431 
11432 // Resolve and fix an overloaded expression that can be resolved
11433 // because it identifies a single function template specialization.
11434 //
11435 // Last three arguments should only be supplied if Complain = true
11436 //
11437 // Return true if it was logically possible to so resolve the
11438 // expression, regardless of whether or not it succeeded.  Always
11439 // returns true if 'complain' is set.
11440 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11441                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11442                       bool complain, SourceRange OpRangeForComplaining,
11443                                            QualType DestTypeForComplaining,
11444                                             unsigned DiagIDForComplaining) {
11445   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11446 
11447   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11448 
11449   DeclAccessPair found;
11450   ExprResult SingleFunctionExpression;
11451   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11452                            ovl.Expression, /*complain*/ false, &found)) {
11453     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11454       SrcExpr = ExprError();
11455       return true;
11456     }
11457 
11458     // It is only correct to resolve to an instance method if we're
11459     // resolving a form that's permitted to be a pointer to member.
11460     // Otherwise we'll end up making a bound member expression, which
11461     // is illegal in all the contexts we resolve like this.
11462     if (!ovl.HasFormOfMemberPointer &&
11463         isa<CXXMethodDecl>(fn) &&
11464         cast<CXXMethodDecl>(fn)->isInstance()) {
11465       if (!complain) return false;
11466 
11467       Diag(ovl.Expression->getExprLoc(),
11468            diag::err_bound_member_function)
11469         << 0 << ovl.Expression->getSourceRange();
11470 
11471       // TODO: I believe we only end up here if there's a mix of
11472       // static and non-static candidates (otherwise the expression
11473       // would have 'bound member' type, not 'overload' type).
11474       // Ideally we would note which candidate was chosen and why
11475       // the static candidates were rejected.
11476       SrcExpr = ExprError();
11477       return true;
11478     }
11479 
11480     // Fix the expression to refer to 'fn'.
11481     SingleFunctionExpression =
11482         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11483 
11484     // If desired, do function-to-pointer decay.
11485     if (doFunctionPointerConverion) {
11486       SingleFunctionExpression =
11487         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11488       if (SingleFunctionExpression.isInvalid()) {
11489         SrcExpr = ExprError();
11490         return true;
11491       }
11492     }
11493   }
11494 
11495   if (!SingleFunctionExpression.isUsable()) {
11496     if (complain) {
11497       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11498         << ovl.Expression->getName()
11499         << DestTypeForComplaining
11500         << OpRangeForComplaining
11501         << ovl.Expression->getQualifierLoc().getSourceRange();
11502       NoteAllOverloadCandidates(SrcExpr.get());
11503 
11504       SrcExpr = ExprError();
11505       return true;
11506     }
11507 
11508     return false;
11509   }
11510 
11511   SrcExpr = SingleFunctionExpression;
11512   return true;
11513 }
11514 
11515 /// Add a single candidate to the overload set.
11516 static void AddOverloadedCallCandidate(Sema &S,
11517                                        DeclAccessPair FoundDecl,
11518                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11519                                        ArrayRef<Expr *> Args,
11520                                        OverloadCandidateSet &CandidateSet,
11521                                        bool PartialOverloading,
11522                                        bool KnownValid) {
11523   NamedDecl *Callee = FoundDecl.getDecl();
11524   if (isa<UsingShadowDecl>(Callee))
11525     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11526 
11527   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11528     if (ExplicitTemplateArgs) {
11529       assert(!KnownValid && "Explicit template arguments?");
11530       return;
11531     }
11532     // Prevent ill-formed function decls to be added as overload candidates.
11533     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11534       return;
11535 
11536     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11537                            /*SuppressUsedConversions=*/false,
11538                            PartialOverloading);
11539     return;
11540   }
11541 
11542   if (FunctionTemplateDecl *FuncTemplate
11543       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11544     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11545                                    ExplicitTemplateArgs, Args, CandidateSet,
11546                                    /*SuppressUsedConversions=*/false,
11547                                    PartialOverloading);
11548     return;
11549   }
11550 
11551   assert(!KnownValid && "unhandled case in overloaded call candidate");
11552 }
11553 
11554 /// Add the overload candidates named by callee and/or found by argument
11555 /// dependent lookup to the given overload set.
11556 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11557                                        ArrayRef<Expr *> Args,
11558                                        OverloadCandidateSet &CandidateSet,
11559                                        bool PartialOverloading) {
11560 
11561 #ifndef NDEBUG
11562   // Verify that ArgumentDependentLookup is consistent with the rules
11563   // in C++0x [basic.lookup.argdep]p3:
11564   //
11565   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11566   //   and let Y be the lookup set produced by argument dependent
11567   //   lookup (defined as follows). If X contains
11568   //
11569   //     -- a declaration of a class member, or
11570   //
11571   //     -- a block-scope function declaration that is not a
11572   //        using-declaration, or
11573   //
11574   //     -- a declaration that is neither a function or a function
11575   //        template
11576   //
11577   //   then Y is empty.
11578 
11579   if (ULE->requiresADL()) {
11580     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11581            E = ULE->decls_end(); I != E; ++I) {
11582       assert(!(*I)->getDeclContext()->isRecord());
11583       assert(isa<UsingShadowDecl>(*I) ||
11584              !(*I)->getDeclContext()->isFunctionOrMethod());
11585       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11586     }
11587   }
11588 #endif
11589 
11590   // It would be nice to avoid this copy.
11591   TemplateArgumentListInfo TABuffer;
11592   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11593   if (ULE->hasExplicitTemplateArgs()) {
11594     ULE->copyTemplateArgumentsInto(TABuffer);
11595     ExplicitTemplateArgs = &TABuffer;
11596   }
11597 
11598   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11599          E = ULE->decls_end(); I != E; ++I)
11600     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11601                                CandidateSet, PartialOverloading,
11602                                /*KnownValid*/ true);
11603 
11604   if (ULE->requiresADL())
11605     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11606                                          Args, ExplicitTemplateArgs,
11607                                          CandidateSet, PartialOverloading);
11608 }
11609 
11610 /// Determine whether a declaration with the specified name could be moved into
11611 /// a different namespace.
11612 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11613   switch (Name.getCXXOverloadedOperator()) {
11614   case OO_New: case OO_Array_New:
11615   case OO_Delete: case OO_Array_Delete:
11616     return false;
11617 
11618   default:
11619     return true;
11620   }
11621 }
11622 
11623 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11624 /// template, where the non-dependent name was declared after the template
11625 /// was defined. This is common in code written for a compilers which do not
11626 /// correctly implement two-stage name lookup.
11627 ///
11628 /// Returns true if a viable candidate was found and a diagnostic was issued.
11629 static bool
11630 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11631                        const CXXScopeSpec &SS, LookupResult &R,
11632                        OverloadCandidateSet::CandidateSetKind CSK,
11633                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11634                        ArrayRef<Expr *> Args,
11635                        bool *DoDiagnoseEmptyLookup = nullptr) {
11636   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11637     return false;
11638 
11639   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11640     if (DC->isTransparentContext())
11641       continue;
11642 
11643     SemaRef.LookupQualifiedName(R, DC);
11644 
11645     if (!R.empty()) {
11646       R.suppressDiagnostics();
11647 
11648       if (isa<CXXRecordDecl>(DC)) {
11649         // Don't diagnose names we find in classes; we get much better
11650         // diagnostics for these from DiagnoseEmptyLookup.
11651         R.clear();
11652         if (DoDiagnoseEmptyLookup)
11653           *DoDiagnoseEmptyLookup = true;
11654         return false;
11655       }
11656 
11657       OverloadCandidateSet Candidates(FnLoc, CSK);
11658       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11659         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11660                                    ExplicitTemplateArgs, Args,
11661                                    Candidates, false, /*KnownValid*/ false);
11662 
11663       OverloadCandidateSet::iterator Best;
11664       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11665         // No viable functions. Don't bother the user with notes for functions
11666         // which don't work and shouldn't be found anyway.
11667         R.clear();
11668         return false;
11669       }
11670 
11671       // Find the namespaces where ADL would have looked, and suggest
11672       // declaring the function there instead.
11673       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11674       Sema::AssociatedClassSet AssociatedClasses;
11675       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11676                                                  AssociatedNamespaces,
11677                                                  AssociatedClasses);
11678       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11679       if (canBeDeclaredInNamespace(R.getLookupName())) {
11680         DeclContext *Std = SemaRef.getStdNamespace();
11681         for (Sema::AssociatedNamespaceSet::iterator
11682                it = AssociatedNamespaces.begin(),
11683                end = AssociatedNamespaces.end(); it != end; ++it) {
11684           // Never suggest declaring a function within namespace 'std'.
11685           if (Std && Std->Encloses(*it))
11686             continue;
11687 
11688           // Never suggest declaring a function within a namespace with a
11689           // reserved name, like __gnu_cxx.
11690           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11691           if (NS &&
11692               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11693             continue;
11694 
11695           SuggestedNamespaces.insert(*it);
11696         }
11697       }
11698 
11699       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11700         << R.getLookupName();
11701       if (SuggestedNamespaces.empty()) {
11702         SemaRef.Diag(Best->Function->getLocation(),
11703                      diag::note_not_found_by_two_phase_lookup)
11704           << R.getLookupName() << 0;
11705       } else if (SuggestedNamespaces.size() == 1) {
11706         SemaRef.Diag(Best->Function->getLocation(),
11707                      diag::note_not_found_by_two_phase_lookup)
11708           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11709       } else {
11710         // FIXME: It would be useful to list the associated namespaces here,
11711         // but the diagnostics infrastructure doesn't provide a way to produce
11712         // a localized representation of a list of items.
11713         SemaRef.Diag(Best->Function->getLocation(),
11714                      diag::note_not_found_by_two_phase_lookup)
11715           << R.getLookupName() << 2;
11716       }
11717 
11718       // Try to recover by calling this function.
11719       return true;
11720     }
11721 
11722     R.clear();
11723   }
11724 
11725   return false;
11726 }
11727 
11728 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11729 /// template, where the non-dependent operator was declared after the template
11730 /// was defined.
11731 ///
11732 /// Returns true if a viable candidate was found and a diagnostic was issued.
11733 static bool
11734 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11735                                SourceLocation OpLoc,
11736                                ArrayRef<Expr *> Args) {
11737   DeclarationName OpName =
11738     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11739   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11740   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11741                                 OverloadCandidateSet::CSK_Operator,
11742                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11743 }
11744 
11745 namespace {
11746 class BuildRecoveryCallExprRAII {
11747   Sema &SemaRef;
11748 public:
11749   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11750     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11751     SemaRef.IsBuildingRecoveryCallExpr = true;
11752   }
11753 
11754   ~BuildRecoveryCallExprRAII() {
11755     SemaRef.IsBuildingRecoveryCallExpr = false;
11756   }
11757 };
11758 
11759 }
11760 
11761 static std::unique_ptr<CorrectionCandidateCallback>
11762 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11763               bool HasTemplateArgs, bool AllowTypoCorrection) {
11764   if (!AllowTypoCorrection)
11765     return llvm::make_unique<NoTypoCorrectionCCC>();
11766   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11767                                                   HasTemplateArgs, ME);
11768 }
11769 
11770 /// Attempts to recover from a call where no functions were found.
11771 ///
11772 /// Returns true if new candidates were found.
11773 static ExprResult
11774 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11775                       UnresolvedLookupExpr *ULE,
11776                       SourceLocation LParenLoc,
11777                       MutableArrayRef<Expr *> Args,
11778                       SourceLocation RParenLoc,
11779                       bool EmptyLookup, bool AllowTypoCorrection) {
11780   // Do not try to recover if it is already building a recovery call.
11781   // This stops infinite loops for template instantiations like
11782   //
11783   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11784   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11785   //
11786   if (SemaRef.IsBuildingRecoveryCallExpr)
11787     return ExprError();
11788   BuildRecoveryCallExprRAII RCE(SemaRef);
11789 
11790   CXXScopeSpec SS;
11791   SS.Adopt(ULE->getQualifierLoc());
11792   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11793 
11794   TemplateArgumentListInfo TABuffer;
11795   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11796   if (ULE->hasExplicitTemplateArgs()) {
11797     ULE->copyTemplateArgumentsInto(TABuffer);
11798     ExplicitTemplateArgs = &TABuffer;
11799   }
11800 
11801   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11802                  Sema::LookupOrdinaryName);
11803   bool DoDiagnoseEmptyLookup = EmptyLookup;
11804   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11805                               OverloadCandidateSet::CSK_Normal,
11806                               ExplicitTemplateArgs, Args,
11807                               &DoDiagnoseEmptyLookup) &&
11808     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11809         S, SS, R,
11810         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11811                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11812         ExplicitTemplateArgs, Args)))
11813     return ExprError();
11814 
11815   assert(!R.empty() && "lookup results empty despite recovery");
11816 
11817   // If recovery created an ambiguity, just bail out.
11818   if (R.isAmbiguous()) {
11819     R.suppressDiagnostics();
11820     return ExprError();
11821   }
11822 
11823   // Build an implicit member call if appropriate.  Just drop the
11824   // casts and such from the call, we don't really care.
11825   ExprResult NewFn = ExprError();
11826   if ((*R.begin())->isCXXClassMember())
11827     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11828                                                     ExplicitTemplateArgs, S);
11829   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11830     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11831                                         ExplicitTemplateArgs);
11832   else
11833     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11834 
11835   if (NewFn.isInvalid())
11836     return ExprError();
11837 
11838   // This shouldn't cause an infinite loop because we're giving it
11839   // an expression with viable lookup results, which should never
11840   // end up here.
11841   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11842                                MultiExprArg(Args.data(), Args.size()),
11843                                RParenLoc);
11844 }
11845 
11846 /// Constructs and populates an OverloadedCandidateSet from
11847 /// the given function.
11848 /// \returns true when an the ExprResult output parameter has been set.
11849 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11850                                   UnresolvedLookupExpr *ULE,
11851                                   MultiExprArg Args,
11852                                   SourceLocation RParenLoc,
11853                                   OverloadCandidateSet *CandidateSet,
11854                                   ExprResult *Result) {
11855 #ifndef NDEBUG
11856   if (ULE->requiresADL()) {
11857     // To do ADL, we must have found an unqualified name.
11858     assert(!ULE->getQualifier() && "qualified name with ADL");
11859 
11860     // We don't perform ADL for implicit declarations of builtins.
11861     // Verify that this was correctly set up.
11862     FunctionDecl *F;
11863     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11864         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11865         F->getBuiltinID() && F->isImplicit())
11866       llvm_unreachable("performing ADL for builtin");
11867 
11868     // We don't perform ADL in C.
11869     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11870   }
11871 #endif
11872 
11873   UnbridgedCastsSet UnbridgedCasts;
11874   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11875     *Result = ExprError();
11876     return true;
11877   }
11878 
11879   // Add the functions denoted by the callee to the set of candidate
11880   // functions, including those from argument-dependent lookup.
11881   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11882 
11883   if (getLangOpts().MSVCCompat &&
11884       CurContext->isDependentContext() && !isSFINAEContext() &&
11885       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11886 
11887     OverloadCandidateSet::iterator Best;
11888     if (CandidateSet->empty() ||
11889         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11890             OR_No_Viable_Function) {
11891       // In Microsoft mode, if we are inside a template class member function then
11892       // create a type dependent CallExpr. The goal is to postpone name lookup
11893       // to instantiation time to be able to search into type dependent base
11894       // classes.
11895       CallExpr *CE = new (Context) CallExpr(
11896           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11897       CE->setTypeDependent(true);
11898       CE->setValueDependent(true);
11899       CE->setInstantiationDependent(true);
11900       *Result = CE;
11901       return true;
11902     }
11903   }
11904 
11905   if (CandidateSet->empty())
11906     return false;
11907 
11908   UnbridgedCasts.restore();
11909   return false;
11910 }
11911 
11912 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11913 /// the completed call expression. If overload resolution fails, emits
11914 /// diagnostics and returns ExprError()
11915 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11916                                            UnresolvedLookupExpr *ULE,
11917                                            SourceLocation LParenLoc,
11918                                            MultiExprArg Args,
11919                                            SourceLocation RParenLoc,
11920                                            Expr *ExecConfig,
11921                                            OverloadCandidateSet *CandidateSet,
11922                                            OverloadCandidateSet::iterator *Best,
11923                                            OverloadingResult OverloadResult,
11924                                            bool AllowTypoCorrection) {
11925   if (CandidateSet->empty())
11926     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11927                                  RParenLoc, /*EmptyLookup=*/true,
11928                                  AllowTypoCorrection);
11929 
11930   switch (OverloadResult) {
11931   case OR_Success: {
11932     FunctionDecl *FDecl = (*Best)->Function;
11933     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11934     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11935       return ExprError();
11936     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11937     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11938                                          ExecConfig);
11939   }
11940 
11941   case OR_No_Viable_Function: {
11942     // Try to recover by looking for viable functions which the user might
11943     // have meant to call.
11944     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11945                                                 Args, RParenLoc,
11946                                                 /*EmptyLookup=*/false,
11947                                                 AllowTypoCorrection);
11948     if (!Recovery.isInvalid())
11949       return Recovery;
11950 
11951     // If the user passes in a function that we can't take the address of, we
11952     // generally end up emitting really bad error messages. Here, we attempt to
11953     // emit better ones.
11954     for (const Expr *Arg : Args) {
11955       if (!Arg->getType()->isFunctionType())
11956         continue;
11957       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11958         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11959         if (FD &&
11960             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11961                                                        Arg->getExprLoc()))
11962           return ExprError();
11963       }
11964     }
11965 
11966     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11967         << ULE->getName() << Fn->getSourceRange();
11968     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11969     break;
11970   }
11971 
11972   case OR_Ambiguous:
11973     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11974       << ULE->getName() << Fn->getSourceRange();
11975     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11976     break;
11977 
11978   case OR_Deleted: {
11979     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11980       << (*Best)->Function->isDeleted()
11981       << ULE->getName()
11982       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11983       << Fn->getSourceRange();
11984     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11985 
11986     // We emitted an error for the unavailable/deleted function call but keep
11987     // the call in the AST.
11988     FunctionDecl *FDecl = (*Best)->Function;
11989     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11990     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11991                                          ExecConfig);
11992   }
11993   }
11994 
11995   // Overload resolution failed.
11996   return ExprError();
11997 }
11998 
11999 static void markUnaddressableCandidatesUnviable(Sema &S,
12000                                                 OverloadCandidateSet &CS) {
12001   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12002     if (I->Viable &&
12003         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12004       I->Viable = false;
12005       I->FailureKind = ovl_fail_addr_not_available;
12006     }
12007   }
12008 }
12009 
12010 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12011 /// (which eventually refers to the declaration Func) and the call
12012 /// arguments Args/NumArgs, attempt to resolve the function call down
12013 /// to a specific function. If overload resolution succeeds, returns
12014 /// the call expression produced by overload resolution.
12015 /// Otherwise, emits diagnostics and returns ExprError.
12016 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12017                                          UnresolvedLookupExpr *ULE,
12018                                          SourceLocation LParenLoc,
12019                                          MultiExprArg Args,
12020                                          SourceLocation RParenLoc,
12021                                          Expr *ExecConfig,
12022                                          bool AllowTypoCorrection,
12023                                          bool CalleesAddressIsTaken) {
12024   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12025                                     OverloadCandidateSet::CSK_Normal);
12026   ExprResult result;
12027 
12028   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12029                              &result))
12030     return result;
12031 
12032   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12033   // functions that aren't addressible are considered unviable.
12034   if (CalleesAddressIsTaken)
12035     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12036 
12037   OverloadCandidateSet::iterator Best;
12038   OverloadingResult OverloadResult =
12039       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12040 
12041   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12042                                   RParenLoc, ExecConfig, &CandidateSet,
12043                                   &Best, OverloadResult,
12044                                   AllowTypoCorrection);
12045 }
12046 
12047 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12048   return Functions.size() > 1 ||
12049     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12050 }
12051 
12052 /// Create a unary operation that may resolve to an overloaded
12053 /// operator.
12054 ///
12055 /// \param OpLoc The location of the operator itself (e.g., '*').
12056 ///
12057 /// \param Opc The UnaryOperatorKind that describes this operator.
12058 ///
12059 /// \param Fns The set of non-member functions that will be
12060 /// considered by overload resolution. The caller needs to build this
12061 /// set based on the context using, e.g.,
12062 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12063 /// set should not contain any member functions; those will be added
12064 /// by CreateOverloadedUnaryOp().
12065 ///
12066 /// \param Input The input argument.
12067 ExprResult
12068 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12069                               const UnresolvedSetImpl &Fns,
12070                               Expr *Input, bool PerformADL) {
12071   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12072   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12073   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12074   // TODO: provide better source location info.
12075   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12076 
12077   if (checkPlaceholderForOverload(*this, Input))
12078     return ExprError();
12079 
12080   Expr *Args[2] = { Input, nullptr };
12081   unsigned NumArgs = 1;
12082 
12083   // For post-increment and post-decrement, add the implicit '0' as
12084   // the second argument, so that we know this is a post-increment or
12085   // post-decrement.
12086   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12087     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12088     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12089                                      SourceLocation());
12090     NumArgs = 2;
12091   }
12092 
12093   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12094 
12095   if (Input->isTypeDependent()) {
12096     if (Fns.empty())
12097       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12098                                          VK_RValue, OK_Ordinary, OpLoc, false);
12099 
12100     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12101     UnresolvedLookupExpr *Fn
12102       = UnresolvedLookupExpr::Create(Context, NamingClass,
12103                                      NestedNameSpecifierLoc(), OpNameInfo,
12104                                      /*ADL*/ true, IsOverloaded(Fns),
12105                                      Fns.begin(), Fns.end());
12106     return new (Context)
12107         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12108                             VK_RValue, OpLoc, FPOptions());
12109   }
12110 
12111   // Build an empty overload set.
12112   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12113 
12114   // Add the candidates from the given function set.
12115   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12116 
12117   // Add operator candidates that are member functions.
12118   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12119 
12120   // Add candidates from ADL.
12121   if (PerformADL) {
12122     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12123                                          /*ExplicitTemplateArgs*/nullptr,
12124                                          CandidateSet);
12125   }
12126 
12127   // Add builtin operator candidates.
12128   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12129 
12130   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12131 
12132   // Perform overload resolution.
12133   OverloadCandidateSet::iterator Best;
12134   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12135   case OR_Success: {
12136     // We found a built-in operator or an overloaded operator.
12137     FunctionDecl *FnDecl = Best->Function;
12138 
12139     if (FnDecl) {
12140       Expr *Base = nullptr;
12141       // We matched an overloaded operator. Build a call to that
12142       // operator.
12143 
12144       // Convert the arguments.
12145       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12146         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12147 
12148         ExprResult InputRes =
12149           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12150                                               Best->FoundDecl, Method);
12151         if (InputRes.isInvalid())
12152           return ExprError();
12153         Base = Input = InputRes.get();
12154       } else {
12155         // Convert the arguments.
12156         ExprResult InputInit
12157           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12158                                                       Context,
12159                                                       FnDecl->getParamDecl(0)),
12160                                       SourceLocation(),
12161                                       Input);
12162         if (InputInit.isInvalid())
12163           return ExprError();
12164         Input = InputInit.get();
12165       }
12166 
12167       // Build the actual expression node.
12168       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12169                                                 Base, HadMultipleCandidates,
12170                                                 OpLoc);
12171       if (FnExpr.isInvalid())
12172         return ExprError();
12173 
12174       // Determine the result type.
12175       QualType ResultTy = FnDecl->getReturnType();
12176       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12177       ResultTy = ResultTy.getNonLValueExprType(Context);
12178 
12179       Args[0] = Input;
12180       CallExpr *TheCall =
12181         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12182                                           ResultTy, VK, OpLoc, FPOptions());
12183 
12184       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12185         return ExprError();
12186 
12187       if (CheckFunctionCall(FnDecl, TheCall,
12188                             FnDecl->getType()->castAs<FunctionProtoType>()))
12189         return ExprError();
12190 
12191       return MaybeBindToTemporary(TheCall);
12192     } else {
12193       // We matched a built-in operator. Convert the arguments, then
12194       // break out so that we will build the appropriate built-in
12195       // operator node.
12196       ExprResult InputRes = PerformImplicitConversion(
12197           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12198       if (InputRes.isInvalid())
12199         return ExprError();
12200       Input = InputRes.get();
12201       break;
12202     }
12203   }
12204 
12205   case OR_No_Viable_Function:
12206     // This is an erroneous use of an operator which can be overloaded by
12207     // a non-member function. Check for non-member operators which were
12208     // defined too late to be candidates.
12209     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12210       // FIXME: Recover by calling the found function.
12211       return ExprError();
12212 
12213     // No viable function; fall through to handling this as a
12214     // built-in operator, which will produce an error message for us.
12215     break;
12216 
12217   case OR_Ambiguous:
12218     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12219         << UnaryOperator::getOpcodeStr(Opc)
12220         << Input->getType()
12221         << Input->getSourceRange();
12222     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12223                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12224     return ExprError();
12225 
12226   case OR_Deleted:
12227     Diag(OpLoc, diag::err_ovl_deleted_oper)
12228       << Best->Function->isDeleted()
12229       << UnaryOperator::getOpcodeStr(Opc)
12230       << getDeletedOrUnavailableSuffix(Best->Function)
12231       << Input->getSourceRange();
12232     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12233                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12234     return ExprError();
12235   }
12236 
12237   // Either we found no viable overloaded operator or we matched a
12238   // built-in operator. In either case, fall through to trying to
12239   // build a built-in operation.
12240   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12241 }
12242 
12243 /// Create a binary operation that may resolve to an overloaded
12244 /// operator.
12245 ///
12246 /// \param OpLoc The location of the operator itself (e.g., '+').
12247 ///
12248 /// \param Opc The BinaryOperatorKind that describes this operator.
12249 ///
12250 /// \param Fns The set of non-member functions that will be
12251 /// considered by overload resolution. The caller needs to build this
12252 /// set based on the context using, e.g.,
12253 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12254 /// set should not contain any member functions; those will be added
12255 /// by CreateOverloadedBinOp().
12256 ///
12257 /// \param LHS Left-hand argument.
12258 /// \param RHS Right-hand argument.
12259 ExprResult
12260 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12261                             BinaryOperatorKind Opc,
12262                             const UnresolvedSetImpl &Fns,
12263                             Expr *LHS, Expr *RHS, bool PerformADL) {
12264   Expr *Args[2] = { LHS, RHS };
12265   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12266 
12267   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12268   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12269 
12270   // If either side is type-dependent, create an appropriate dependent
12271   // expression.
12272   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12273     if (Fns.empty()) {
12274       // If there are no functions to store, just build a dependent
12275       // BinaryOperator or CompoundAssignment.
12276       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12277         return new (Context) BinaryOperator(
12278             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12279             OpLoc, FPFeatures);
12280 
12281       return new (Context) CompoundAssignOperator(
12282           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12283           Context.DependentTy, Context.DependentTy, OpLoc,
12284           FPFeatures);
12285     }
12286 
12287     // FIXME: save results of ADL from here?
12288     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12289     // TODO: provide better source location info in DNLoc component.
12290     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12291     UnresolvedLookupExpr *Fn
12292       = UnresolvedLookupExpr::Create(Context, NamingClass,
12293                                      NestedNameSpecifierLoc(), OpNameInfo,
12294                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12295                                      Fns.begin(), Fns.end());
12296     return new (Context)
12297         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12298                             VK_RValue, OpLoc, FPFeatures);
12299   }
12300 
12301   // Always do placeholder-like conversions on the RHS.
12302   if (checkPlaceholderForOverload(*this, Args[1]))
12303     return ExprError();
12304 
12305   // Do placeholder-like conversion on the LHS; note that we should
12306   // not get here with a PseudoObject LHS.
12307   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12308   if (checkPlaceholderForOverload(*this, Args[0]))
12309     return ExprError();
12310 
12311   // If this is the assignment operator, we only perform overload resolution
12312   // if the left-hand side is a class or enumeration type. This is actually
12313   // a hack. The standard requires that we do overload resolution between the
12314   // various built-in candidates, but as DR507 points out, this can lead to
12315   // problems. So we do it this way, which pretty much follows what GCC does.
12316   // Note that we go the traditional code path for compound assignment forms.
12317   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12318     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12319 
12320   // If this is the .* operator, which is not overloadable, just
12321   // create a built-in binary operator.
12322   if (Opc == BO_PtrMemD)
12323     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12324 
12325   // Build an empty overload set.
12326   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12327 
12328   // Add the candidates from the given function set.
12329   AddFunctionCandidates(Fns, Args, CandidateSet);
12330 
12331   // Add operator candidates that are member functions.
12332   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12333 
12334   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12335   // performed for an assignment operator (nor for operator[] nor operator->,
12336   // which don't get here).
12337   if (Opc != BO_Assign && PerformADL)
12338     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12339                                          /*ExplicitTemplateArgs*/ nullptr,
12340                                          CandidateSet);
12341 
12342   // Add builtin operator candidates.
12343   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12344 
12345   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12346 
12347   // Perform overload resolution.
12348   OverloadCandidateSet::iterator Best;
12349   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12350     case OR_Success: {
12351       // We found a built-in operator or an overloaded operator.
12352       FunctionDecl *FnDecl = Best->Function;
12353 
12354       if (FnDecl) {
12355         Expr *Base = nullptr;
12356         // We matched an overloaded operator. Build a call to that
12357         // operator.
12358 
12359         // Convert the arguments.
12360         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12361           // Best->Access is only meaningful for class members.
12362           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12363 
12364           ExprResult Arg1 =
12365             PerformCopyInitialization(
12366               InitializedEntity::InitializeParameter(Context,
12367                                                      FnDecl->getParamDecl(0)),
12368               SourceLocation(), Args[1]);
12369           if (Arg1.isInvalid())
12370             return ExprError();
12371 
12372           ExprResult Arg0 =
12373             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12374                                                 Best->FoundDecl, Method);
12375           if (Arg0.isInvalid())
12376             return ExprError();
12377           Base = Args[0] = Arg0.getAs<Expr>();
12378           Args[1] = RHS = Arg1.getAs<Expr>();
12379         } else {
12380           // Convert the arguments.
12381           ExprResult Arg0 = PerformCopyInitialization(
12382             InitializedEntity::InitializeParameter(Context,
12383                                                    FnDecl->getParamDecl(0)),
12384             SourceLocation(), Args[0]);
12385           if (Arg0.isInvalid())
12386             return ExprError();
12387 
12388           ExprResult Arg1 =
12389             PerformCopyInitialization(
12390               InitializedEntity::InitializeParameter(Context,
12391                                                      FnDecl->getParamDecl(1)),
12392               SourceLocation(), Args[1]);
12393           if (Arg1.isInvalid())
12394             return ExprError();
12395           Args[0] = LHS = Arg0.getAs<Expr>();
12396           Args[1] = RHS = Arg1.getAs<Expr>();
12397         }
12398 
12399         // Build the actual expression node.
12400         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12401                                                   Best->FoundDecl, Base,
12402                                                   HadMultipleCandidates, OpLoc);
12403         if (FnExpr.isInvalid())
12404           return ExprError();
12405 
12406         // Determine the result type.
12407         QualType ResultTy = FnDecl->getReturnType();
12408         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12409         ResultTy = ResultTy.getNonLValueExprType(Context);
12410 
12411         CXXOperatorCallExpr *TheCall =
12412           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12413                                             Args, ResultTy, VK, OpLoc,
12414                                             FPFeatures);
12415 
12416         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12417                                 FnDecl))
12418           return ExprError();
12419 
12420         ArrayRef<const Expr *> ArgsArray(Args, 2);
12421         const Expr *ImplicitThis = nullptr;
12422         // Cut off the implicit 'this'.
12423         if (isa<CXXMethodDecl>(FnDecl)) {
12424           ImplicitThis = ArgsArray[0];
12425           ArgsArray = ArgsArray.slice(1);
12426         }
12427 
12428         // Check for a self move.
12429         if (Op == OO_Equal)
12430           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12431 
12432         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12433                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12434                   VariadicDoesNotApply);
12435 
12436         return MaybeBindToTemporary(TheCall);
12437       } else {
12438         // We matched a built-in operator. Convert the arguments, then
12439         // break out so that we will build the appropriate built-in
12440         // operator node.
12441         ExprResult ArgsRes0 =
12442             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12443                                       Best->Conversions[0], AA_Passing);
12444         if (ArgsRes0.isInvalid())
12445           return ExprError();
12446         Args[0] = ArgsRes0.get();
12447 
12448         ExprResult ArgsRes1 =
12449             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12450                                       Best->Conversions[1], AA_Passing);
12451         if (ArgsRes1.isInvalid())
12452           return ExprError();
12453         Args[1] = ArgsRes1.get();
12454         break;
12455       }
12456     }
12457 
12458     case OR_No_Viable_Function: {
12459       // C++ [over.match.oper]p9:
12460       //   If the operator is the operator , [...] and there are no
12461       //   viable functions, then the operator is assumed to be the
12462       //   built-in operator and interpreted according to clause 5.
12463       if (Opc == BO_Comma)
12464         break;
12465 
12466       // For class as left operand for assignment or compound assignment
12467       // operator do not fall through to handling in built-in, but report that
12468       // no overloaded assignment operator found
12469       ExprResult Result = ExprError();
12470       if (Args[0]->getType()->isRecordType() &&
12471           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12472         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12473              << BinaryOperator::getOpcodeStr(Opc)
12474              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12475         if (Args[0]->getType()->isIncompleteType()) {
12476           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12477             << Args[0]->getType()
12478             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12479         }
12480       } else {
12481         // This is an erroneous use of an operator which can be overloaded by
12482         // a non-member function. Check for non-member operators which were
12483         // defined too late to be candidates.
12484         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12485           // FIXME: Recover by calling the found function.
12486           return ExprError();
12487 
12488         // No viable function; try to create a built-in operation, which will
12489         // produce an error. Then, show the non-viable candidates.
12490         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12491       }
12492       assert(Result.isInvalid() &&
12493              "C++ binary operator overloading is missing candidates!");
12494       if (Result.isInvalid())
12495         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12496                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12497       return Result;
12498     }
12499 
12500     case OR_Ambiguous:
12501       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12502           << BinaryOperator::getOpcodeStr(Opc)
12503           << Args[0]->getType() << Args[1]->getType()
12504           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12505       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12506                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12507       return ExprError();
12508 
12509     case OR_Deleted:
12510       if (isImplicitlyDeleted(Best->Function)) {
12511         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12512         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12513           << Context.getRecordType(Method->getParent())
12514           << getSpecialMember(Method);
12515 
12516         // The user probably meant to call this special member. Just
12517         // explain why it's deleted.
12518         NoteDeletedFunction(Method);
12519         return ExprError();
12520       } else {
12521         Diag(OpLoc, diag::err_ovl_deleted_oper)
12522           << Best->Function->isDeleted()
12523           << BinaryOperator::getOpcodeStr(Opc)
12524           << getDeletedOrUnavailableSuffix(Best->Function)
12525           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12526       }
12527       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12528                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12529       return ExprError();
12530   }
12531 
12532   // We matched a built-in operator; build it.
12533   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12534 }
12535 
12536 ExprResult
12537 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12538                                          SourceLocation RLoc,
12539                                          Expr *Base, Expr *Idx) {
12540   Expr *Args[2] = { Base, Idx };
12541   DeclarationName OpName =
12542       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12543 
12544   // If either side is type-dependent, create an appropriate dependent
12545   // expression.
12546   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12547 
12548     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12549     // CHECKME: no 'operator' keyword?
12550     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12551     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12552     UnresolvedLookupExpr *Fn
12553       = UnresolvedLookupExpr::Create(Context, NamingClass,
12554                                      NestedNameSpecifierLoc(), OpNameInfo,
12555                                      /*ADL*/ true, /*Overloaded*/ false,
12556                                      UnresolvedSetIterator(),
12557                                      UnresolvedSetIterator());
12558     // Can't add any actual overloads yet
12559 
12560     return new (Context)
12561         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12562                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12563   }
12564 
12565   // Handle placeholders on both operands.
12566   if (checkPlaceholderForOverload(*this, Args[0]))
12567     return ExprError();
12568   if (checkPlaceholderForOverload(*this, Args[1]))
12569     return ExprError();
12570 
12571   // Build an empty overload set.
12572   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12573 
12574   // Subscript can only be overloaded as a member function.
12575 
12576   // Add operator candidates that are member functions.
12577   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12578 
12579   // Add builtin operator candidates.
12580   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12581 
12582   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12583 
12584   // Perform overload resolution.
12585   OverloadCandidateSet::iterator Best;
12586   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12587     case OR_Success: {
12588       // We found a built-in operator or an overloaded operator.
12589       FunctionDecl *FnDecl = Best->Function;
12590 
12591       if (FnDecl) {
12592         // We matched an overloaded operator. Build a call to that
12593         // operator.
12594 
12595         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12596 
12597         // Convert the arguments.
12598         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12599         ExprResult Arg0 =
12600           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12601                                               Best->FoundDecl, Method);
12602         if (Arg0.isInvalid())
12603           return ExprError();
12604         Args[0] = Arg0.get();
12605 
12606         // Convert the arguments.
12607         ExprResult InputInit
12608           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12609                                                       Context,
12610                                                       FnDecl->getParamDecl(0)),
12611                                       SourceLocation(),
12612                                       Args[1]);
12613         if (InputInit.isInvalid())
12614           return ExprError();
12615 
12616         Args[1] = InputInit.getAs<Expr>();
12617 
12618         // Build the actual expression node.
12619         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12620         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12621         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12622                                                   Best->FoundDecl,
12623                                                   Base,
12624                                                   HadMultipleCandidates,
12625                                                   OpLocInfo.getLoc(),
12626                                                   OpLocInfo.getInfo());
12627         if (FnExpr.isInvalid())
12628           return ExprError();
12629 
12630         // Determine the result type
12631         QualType ResultTy = FnDecl->getReturnType();
12632         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12633         ResultTy = ResultTy.getNonLValueExprType(Context);
12634 
12635         CXXOperatorCallExpr *TheCall =
12636           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12637                                             FnExpr.get(), Args,
12638                                             ResultTy, VK, RLoc,
12639                                             FPOptions());
12640 
12641         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12642           return ExprError();
12643 
12644         if (CheckFunctionCall(Method, TheCall,
12645                               Method->getType()->castAs<FunctionProtoType>()))
12646           return ExprError();
12647 
12648         return MaybeBindToTemporary(TheCall);
12649       } else {
12650         // We matched a built-in operator. Convert the arguments, then
12651         // break out so that we will build the appropriate built-in
12652         // operator node.
12653         ExprResult ArgsRes0 =
12654             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12655                                       Best->Conversions[0], AA_Passing);
12656         if (ArgsRes0.isInvalid())
12657           return ExprError();
12658         Args[0] = ArgsRes0.get();
12659 
12660         ExprResult ArgsRes1 =
12661             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12662                                       Best->Conversions[1], AA_Passing);
12663         if (ArgsRes1.isInvalid())
12664           return ExprError();
12665         Args[1] = ArgsRes1.get();
12666 
12667         break;
12668       }
12669     }
12670 
12671     case OR_No_Viable_Function: {
12672       if (CandidateSet.empty())
12673         Diag(LLoc, diag::err_ovl_no_oper)
12674           << Args[0]->getType() << /*subscript*/ 0
12675           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12676       else
12677         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12678           << Args[0]->getType()
12679           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12680       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12681                                   "[]", LLoc);
12682       return ExprError();
12683     }
12684 
12685     case OR_Ambiguous:
12686       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12687           << "[]"
12688           << Args[0]->getType() << Args[1]->getType()
12689           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12690       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12691                                   "[]", LLoc);
12692       return ExprError();
12693 
12694     case OR_Deleted:
12695       Diag(LLoc, diag::err_ovl_deleted_oper)
12696         << Best->Function->isDeleted() << "[]"
12697         << getDeletedOrUnavailableSuffix(Best->Function)
12698         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12699       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12700                                   "[]", LLoc);
12701       return ExprError();
12702     }
12703 
12704   // We matched a built-in operator; build it.
12705   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12706 }
12707 
12708 /// BuildCallToMemberFunction - Build a call to a member
12709 /// function. MemExpr is the expression that refers to the member
12710 /// function (and includes the object parameter), Args/NumArgs are the
12711 /// arguments to the function call (not including the object
12712 /// parameter). The caller needs to validate that the member
12713 /// expression refers to a non-static member function or an overloaded
12714 /// member function.
12715 ExprResult
12716 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12717                                 SourceLocation LParenLoc,
12718                                 MultiExprArg Args,
12719                                 SourceLocation RParenLoc) {
12720   assert(MemExprE->getType() == Context.BoundMemberTy ||
12721          MemExprE->getType() == Context.OverloadTy);
12722 
12723   // Dig out the member expression. This holds both the object
12724   // argument and the member function we're referring to.
12725   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12726 
12727   // Determine whether this is a call to a pointer-to-member function.
12728   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12729     assert(op->getType() == Context.BoundMemberTy);
12730     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12731 
12732     QualType fnType =
12733       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12734 
12735     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12736     QualType resultType = proto->getCallResultType(Context);
12737     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12738 
12739     // Check that the object type isn't more qualified than the
12740     // member function we're calling.
12741     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12742 
12743     QualType objectType = op->getLHS()->getType();
12744     if (op->getOpcode() == BO_PtrMemI)
12745       objectType = objectType->castAs<PointerType>()->getPointeeType();
12746     Qualifiers objectQuals = objectType.getQualifiers();
12747 
12748     Qualifiers difference = objectQuals - funcQuals;
12749     difference.removeObjCGCAttr();
12750     difference.removeAddressSpace();
12751     if (difference) {
12752       std::string qualsString = difference.getAsString();
12753       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12754         << fnType.getUnqualifiedType()
12755         << qualsString
12756         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12757     }
12758 
12759     CXXMemberCallExpr *call
12760       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12761                                         resultType, valueKind, RParenLoc);
12762 
12763     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12764                             call, nullptr))
12765       return ExprError();
12766 
12767     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12768       return ExprError();
12769 
12770     if (CheckOtherCall(call, proto))
12771       return ExprError();
12772 
12773     return MaybeBindToTemporary(call);
12774   }
12775 
12776   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12777     return new (Context)
12778         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12779 
12780   UnbridgedCastsSet UnbridgedCasts;
12781   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12782     return ExprError();
12783 
12784   MemberExpr *MemExpr;
12785   CXXMethodDecl *Method = nullptr;
12786   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12787   NestedNameSpecifier *Qualifier = nullptr;
12788   if (isa<MemberExpr>(NakedMemExpr)) {
12789     MemExpr = cast<MemberExpr>(NakedMemExpr);
12790     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12791     FoundDecl = MemExpr->getFoundDecl();
12792     Qualifier = MemExpr->getQualifier();
12793     UnbridgedCasts.restore();
12794   } else {
12795     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12796     Qualifier = UnresExpr->getQualifier();
12797 
12798     QualType ObjectType = UnresExpr->getBaseType();
12799     Expr::Classification ObjectClassification
12800       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12801                             : UnresExpr->getBase()->Classify(Context);
12802 
12803     // Add overload candidates
12804     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12805                                       OverloadCandidateSet::CSK_Normal);
12806 
12807     // FIXME: avoid copy.
12808     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12809     if (UnresExpr->hasExplicitTemplateArgs()) {
12810       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12811       TemplateArgs = &TemplateArgsBuffer;
12812     }
12813 
12814     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12815            E = UnresExpr->decls_end(); I != E; ++I) {
12816 
12817       NamedDecl *Func = *I;
12818       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12819       if (isa<UsingShadowDecl>(Func))
12820         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12821 
12822 
12823       // Microsoft supports direct constructor calls.
12824       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12825         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12826                              Args, CandidateSet);
12827       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12828         // If explicit template arguments were provided, we can't call a
12829         // non-template member function.
12830         if (TemplateArgs)
12831           continue;
12832 
12833         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12834                            ObjectClassification, Args, CandidateSet,
12835                            /*SuppressUserConversions=*/false);
12836       } else {
12837         AddMethodTemplateCandidate(
12838             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12839             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12840             /*SuppressUsedConversions=*/false);
12841       }
12842     }
12843 
12844     DeclarationName DeclName = UnresExpr->getMemberName();
12845 
12846     UnbridgedCasts.restore();
12847 
12848     OverloadCandidateSet::iterator Best;
12849     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12850                                             Best)) {
12851     case OR_Success:
12852       Method = cast<CXXMethodDecl>(Best->Function);
12853       FoundDecl = Best->FoundDecl;
12854       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12855       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12856         return ExprError();
12857       // If FoundDecl is different from Method (such as if one is a template
12858       // and the other a specialization), make sure DiagnoseUseOfDecl is
12859       // called on both.
12860       // FIXME: This would be more comprehensively addressed by modifying
12861       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12862       // being used.
12863       if (Method != FoundDecl.getDecl() &&
12864                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12865         return ExprError();
12866       break;
12867 
12868     case OR_No_Viable_Function:
12869       Diag(UnresExpr->getMemberLoc(),
12870            diag::err_ovl_no_viable_member_function_in_call)
12871         << DeclName << MemExprE->getSourceRange();
12872       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12873       // FIXME: Leaking incoming expressions!
12874       return ExprError();
12875 
12876     case OR_Ambiguous:
12877       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12878         << DeclName << MemExprE->getSourceRange();
12879       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12880       // FIXME: Leaking incoming expressions!
12881       return ExprError();
12882 
12883     case OR_Deleted:
12884       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12885         << Best->Function->isDeleted()
12886         << DeclName
12887         << getDeletedOrUnavailableSuffix(Best->Function)
12888         << MemExprE->getSourceRange();
12889       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12890       // FIXME: Leaking incoming expressions!
12891       return ExprError();
12892     }
12893 
12894     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12895 
12896     // If overload resolution picked a static member, build a
12897     // non-member call based on that function.
12898     if (Method->isStatic()) {
12899       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12900                                    RParenLoc);
12901     }
12902 
12903     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12904   }
12905 
12906   QualType ResultType = Method->getReturnType();
12907   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12908   ResultType = ResultType.getNonLValueExprType(Context);
12909 
12910   assert(Method && "Member call to something that isn't a method?");
12911   CXXMemberCallExpr *TheCall =
12912     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12913                                     ResultType, VK, RParenLoc);
12914 
12915   // Check for a valid return type.
12916   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12917                           TheCall, Method))
12918     return ExprError();
12919 
12920   // Convert the object argument (for a non-static member function call).
12921   // We only need to do this if there was actually an overload; otherwise
12922   // it was done at lookup.
12923   if (!Method->isStatic()) {
12924     ExprResult ObjectArg =
12925       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12926                                           FoundDecl, Method);
12927     if (ObjectArg.isInvalid())
12928       return ExprError();
12929     MemExpr->setBase(ObjectArg.get());
12930   }
12931 
12932   // Convert the rest of the arguments
12933   const FunctionProtoType *Proto =
12934     Method->getType()->getAs<FunctionProtoType>();
12935   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12936                               RParenLoc))
12937     return ExprError();
12938 
12939   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12940 
12941   if (CheckFunctionCall(Method, TheCall, Proto))
12942     return ExprError();
12943 
12944   // In the case the method to call was not selected by the overloading
12945   // resolution process, we still need to handle the enable_if attribute. Do
12946   // that here, so it will not hide previous -- and more relevant -- errors.
12947   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12948     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12949       Diag(MemE->getMemberLoc(),
12950            diag::err_ovl_no_viable_member_function_in_call)
12951           << Method << Method->getSourceRange();
12952       Diag(Method->getLocation(),
12953            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12954           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12955       return ExprError();
12956     }
12957   }
12958 
12959   if ((isa<CXXConstructorDecl>(CurContext) ||
12960        isa<CXXDestructorDecl>(CurContext)) &&
12961       TheCall->getMethodDecl()->isPure()) {
12962     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12963 
12964     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12965         MemExpr->performsVirtualDispatch(getLangOpts())) {
12966       Diag(MemExpr->getLocStart(),
12967            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12968         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12969         << MD->getParent()->getDeclName();
12970 
12971       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12972       if (getLangOpts().AppleKext)
12973         Diag(MemExpr->getLocStart(),
12974              diag::note_pure_qualified_call_kext)
12975              << MD->getParent()->getDeclName()
12976              << MD->getDeclName();
12977     }
12978   }
12979 
12980   if (CXXDestructorDecl *DD =
12981           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12982     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12983     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12984     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12985                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12986                          MemExpr->getMemberLoc());
12987   }
12988 
12989   return MaybeBindToTemporary(TheCall);
12990 }
12991 
12992 /// BuildCallToObjectOfClassType - Build a call to an object of class
12993 /// type (C++ [over.call.object]), which can end up invoking an
12994 /// overloaded function call operator (@c operator()) or performing a
12995 /// user-defined conversion on the object argument.
12996 ExprResult
12997 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12998                                    SourceLocation LParenLoc,
12999                                    MultiExprArg Args,
13000                                    SourceLocation RParenLoc) {
13001   if (checkPlaceholderForOverload(*this, Obj))
13002     return ExprError();
13003   ExprResult Object = Obj;
13004 
13005   UnbridgedCastsSet UnbridgedCasts;
13006   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13007     return ExprError();
13008 
13009   assert(Object.get()->getType()->isRecordType() &&
13010          "Requires object type argument");
13011   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13012 
13013   // C++ [over.call.object]p1:
13014   //  If the primary-expression E in the function call syntax
13015   //  evaluates to a class object of type "cv T", then the set of
13016   //  candidate functions includes at least the function call
13017   //  operators of T. The function call operators of T are obtained by
13018   //  ordinary lookup of the name operator() in the context of
13019   //  (E).operator().
13020   OverloadCandidateSet CandidateSet(LParenLoc,
13021                                     OverloadCandidateSet::CSK_Operator);
13022   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13023 
13024   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13025                           diag::err_incomplete_object_call, Object.get()))
13026     return true;
13027 
13028   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13029   LookupQualifiedName(R, Record->getDecl());
13030   R.suppressDiagnostics();
13031 
13032   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13033        Oper != OperEnd; ++Oper) {
13034     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13035                        Object.get()->Classify(Context), Args, CandidateSet,
13036                        /*SuppressUserConversions=*/false);
13037   }
13038 
13039   // C++ [over.call.object]p2:
13040   //   In addition, for each (non-explicit in C++0x) conversion function
13041   //   declared in T of the form
13042   //
13043   //        operator conversion-type-id () cv-qualifier;
13044   //
13045   //   where cv-qualifier is the same cv-qualification as, or a
13046   //   greater cv-qualification than, cv, and where conversion-type-id
13047   //   denotes the type "pointer to function of (P1,...,Pn) returning
13048   //   R", or the type "reference to pointer to function of
13049   //   (P1,...,Pn) returning R", or the type "reference to function
13050   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13051   //   is also considered as a candidate function. Similarly,
13052   //   surrogate call functions are added to the set of candidate
13053   //   functions for each conversion function declared in an
13054   //   accessible base class provided the function is not hidden
13055   //   within T by another intervening declaration.
13056   const auto &Conversions =
13057       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13058   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13059     NamedDecl *D = *I;
13060     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13061     if (isa<UsingShadowDecl>(D))
13062       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13063 
13064     // Skip over templated conversion functions; they aren't
13065     // surrogates.
13066     if (isa<FunctionTemplateDecl>(D))
13067       continue;
13068 
13069     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13070     if (!Conv->isExplicit()) {
13071       // Strip the reference type (if any) and then the pointer type (if
13072       // any) to get down to what might be a function type.
13073       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13074       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13075         ConvType = ConvPtrType->getPointeeType();
13076 
13077       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13078       {
13079         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13080                               Object.get(), Args, CandidateSet);
13081       }
13082     }
13083   }
13084 
13085   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13086 
13087   // Perform overload resolution.
13088   OverloadCandidateSet::iterator Best;
13089   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13090                                           Best)) {
13091   case OR_Success:
13092     // Overload resolution succeeded; we'll build the appropriate call
13093     // below.
13094     break;
13095 
13096   case OR_No_Viable_Function:
13097     if (CandidateSet.empty())
13098       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13099         << Object.get()->getType() << /*call*/ 1
13100         << Object.get()->getSourceRange();
13101     else
13102       Diag(Object.get()->getLocStart(),
13103            diag::err_ovl_no_viable_object_call)
13104         << Object.get()->getType() << Object.get()->getSourceRange();
13105     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13106     break;
13107 
13108   case OR_Ambiguous:
13109     Diag(Object.get()->getLocStart(),
13110          diag::err_ovl_ambiguous_object_call)
13111       << Object.get()->getType() << Object.get()->getSourceRange();
13112     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13113     break;
13114 
13115   case OR_Deleted:
13116     Diag(Object.get()->getLocStart(),
13117          diag::err_ovl_deleted_object_call)
13118       << Best->Function->isDeleted()
13119       << Object.get()->getType()
13120       << getDeletedOrUnavailableSuffix(Best->Function)
13121       << Object.get()->getSourceRange();
13122     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13123     break;
13124   }
13125 
13126   if (Best == CandidateSet.end())
13127     return true;
13128 
13129   UnbridgedCasts.restore();
13130 
13131   if (Best->Function == nullptr) {
13132     // Since there is no function declaration, this is one of the
13133     // surrogate candidates. Dig out the conversion function.
13134     CXXConversionDecl *Conv
13135       = cast<CXXConversionDecl>(
13136                          Best->Conversions[0].UserDefined.ConversionFunction);
13137 
13138     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13139                               Best->FoundDecl);
13140     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13141       return ExprError();
13142     assert(Conv == Best->FoundDecl.getDecl() &&
13143              "Found Decl & conversion-to-functionptr should be same, right?!");
13144     // We selected one of the surrogate functions that converts the
13145     // object parameter to a function pointer. Perform the conversion
13146     // on the object argument, then let ActOnCallExpr finish the job.
13147 
13148     // Create an implicit member expr to refer to the conversion operator.
13149     // and then call it.
13150     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13151                                              Conv, HadMultipleCandidates);
13152     if (Call.isInvalid())
13153       return ExprError();
13154     // Record usage of conversion in an implicit cast.
13155     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13156                                     CK_UserDefinedConversion, Call.get(),
13157                                     nullptr, VK_RValue);
13158 
13159     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13160   }
13161 
13162   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13163 
13164   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13165   // that calls this method, using Object for the implicit object
13166   // parameter and passing along the remaining arguments.
13167   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13168 
13169   // An error diagnostic has already been printed when parsing the declaration.
13170   if (Method->isInvalidDecl())
13171     return ExprError();
13172 
13173   const FunctionProtoType *Proto =
13174     Method->getType()->getAs<FunctionProtoType>();
13175 
13176   unsigned NumParams = Proto->getNumParams();
13177 
13178   DeclarationNameInfo OpLocInfo(
13179                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13180   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13181   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13182                                            Obj, HadMultipleCandidates,
13183                                            OpLocInfo.getLoc(),
13184                                            OpLocInfo.getInfo());
13185   if (NewFn.isInvalid())
13186     return true;
13187 
13188   // Build the full argument list for the method call (the implicit object
13189   // parameter is placed at the beginning of the list).
13190   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13191   MethodArgs[0] = Object.get();
13192   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13193 
13194   // Once we've built TheCall, all of the expressions are properly
13195   // owned.
13196   QualType ResultTy = Method->getReturnType();
13197   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13198   ResultTy = ResultTy.getNonLValueExprType(Context);
13199 
13200   CXXOperatorCallExpr *TheCall = new (Context)
13201       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13202                           VK, RParenLoc, FPOptions());
13203 
13204   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13205     return true;
13206 
13207   // We may have default arguments. If so, we need to allocate more
13208   // slots in the call for them.
13209   if (Args.size() < NumParams)
13210     TheCall->setNumArgs(Context, NumParams + 1);
13211 
13212   bool IsError = false;
13213 
13214   // Initialize the implicit object parameter.
13215   ExprResult ObjRes =
13216     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13217                                         Best->FoundDecl, Method);
13218   if (ObjRes.isInvalid())
13219     IsError = true;
13220   else
13221     Object = ObjRes;
13222   TheCall->setArg(0, Object.get());
13223 
13224   // Check the argument types.
13225   for (unsigned i = 0; i != NumParams; i++) {
13226     Expr *Arg;
13227     if (i < Args.size()) {
13228       Arg = Args[i];
13229 
13230       // Pass the argument.
13231 
13232       ExprResult InputInit
13233         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13234                                                     Context,
13235                                                     Method->getParamDecl(i)),
13236                                     SourceLocation(), Arg);
13237 
13238       IsError |= InputInit.isInvalid();
13239       Arg = InputInit.getAs<Expr>();
13240     } else {
13241       ExprResult DefArg
13242         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13243       if (DefArg.isInvalid()) {
13244         IsError = true;
13245         break;
13246       }
13247 
13248       Arg = DefArg.getAs<Expr>();
13249     }
13250 
13251     TheCall->setArg(i + 1, Arg);
13252   }
13253 
13254   // If this is a variadic call, handle args passed through "...".
13255   if (Proto->isVariadic()) {
13256     // Promote the arguments (C99 6.5.2.2p7).
13257     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13258       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13259                                                         nullptr);
13260       IsError |= Arg.isInvalid();
13261       TheCall->setArg(i + 1, Arg.get());
13262     }
13263   }
13264 
13265   if (IsError) return true;
13266 
13267   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13268 
13269   if (CheckFunctionCall(Method, TheCall, Proto))
13270     return true;
13271 
13272   return MaybeBindToTemporary(TheCall);
13273 }
13274 
13275 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13276 ///  (if one exists), where @c Base is an expression of class type and
13277 /// @c Member is the name of the member we're trying to find.
13278 ExprResult
13279 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13280                                bool *NoArrowOperatorFound) {
13281   assert(Base->getType()->isRecordType() &&
13282          "left-hand side must have class type");
13283 
13284   if (checkPlaceholderForOverload(*this, Base))
13285     return ExprError();
13286 
13287   SourceLocation Loc = Base->getExprLoc();
13288 
13289   // C++ [over.ref]p1:
13290   //
13291   //   [...] An expression x->m is interpreted as (x.operator->())->m
13292   //   for a class object x of type T if T::operator->() exists and if
13293   //   the operator is selected as the best match function by the
13294   //   overload resolution mechanism (13.3).
13295   DeclarationName OpName =
13296     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13297   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13298   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13299 
13300   if (RequireCompleteType(Loc, Base->getType(),
13301                           diag::err_typecheck_incomplete_tag, Base))
13302     return ExprError();
13303 
13304   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13305   LookupQualifiedName(R, BaseRecord->getDecl());
13306   R.suppressDiagnostics();
13307 
13308   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13309        Oper != OperEnd; ++Oper) {
13310     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13311                        None, CandidateSet, /*SuppressUserConversions=*/false);
13312   }
13313 
13314   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13315 
13316   // Perform overload resolution.
13317   OverloadCandidateSet::iterator Best;
13318   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13319   case OR_Success:
13320     // Overload resolution succeeded; we'll build the call below.
13321     break;
13322 
13323   case OR_No_Viable_Function:
13324     if (CandidateSet.empty()) {
13325       QualType BaseType = Base->getType();
13326       if (NoArrowOperatorFound) {
13327         // Report this specific error to the caller instead of emitting a
13328         // diagnostic, as requested.
13329         *NoArrowOperatorFound = true;
13330         return ExprError();
13331       }
13332       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13333         << BaseType << Base->getSourceRange();
13334       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13335         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13336           << FixItHint::CreateReplacement(OpLoc, ".");
13337       }
13338     } else
13339       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13340         << "operator->" << Base->getSourceRange();
13341     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13342     return ExprError();
13343 
13344   case OR_Ambiguous:
13345     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13346       << "->" << Base->getType() << Base->getSourceRange();
13347     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13348     return ExprError();
13349 
13350   case OR_Deleted:
13351     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13352       << Best->Function->isDeleted()
13353       << "->"
13354       << getDeletedOrUnavailableSuffix(Best->Function)
13355       << Base->getSourceRange();
13356     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13357     return ExprError();
13358   }
13359 
13360   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13361 
13362   // Convert the object parameter.
13363   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13364   ExprResult BaseResult =
13365     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13366                                         Best->FoundDecl, Method);
13367   if (BaseResult.isInvalid())
13368     return ExprError();
13369   Base = BaseResult.get();
13370 
13371   // Build the operator call.
13372   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13373                                             Base, HadMultipleCandidates, OpLoc);
13374   if (FnExpr.isInvalid())
13375     return ExprError();
13376 
13377   QualType ResultTy = Method->getReturnType();
13378   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13379   ResultTy = ResultTy.getNonLValueExprType(Context);
13380   CXXOperatorCallExpr *TheCall =
13381     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13382                                       Base, ResultTy, VK, OpLoc, FPOptions());
13383 
13384   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13385     return ExprError();
13386 
13387   if (CheckFunctionCall(Method, TheCall,
13388                         Method->getType()->castAs<FunctionProtoType>()))
13389     return ExprError();
13390 
13391   return MaybeBindToTemporary(TheCall);
13392 }
13393 
13394 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13395 /// a literal operator described by the provided lookup results.
13396 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13397                                           DeclarationNameInfo &SuffixInfo,
13398                                           ArrayRef<Expr*> Args,
13399                                           SourceLocation LitEndLoc,
13400                                        TemplateArgumentListInfo *TemplateArgs) {
13401   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13402 
13403   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13404                                     OverloadCandidateSet::CSK_Normal);
13405   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13406                         /*SuppressUserConversions=*/true);
13407 
13408   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13409 
13410   // Perform overload resolution. This will usually be trivial, but might need
13411   // to perform substitutions for a literal operator template.
13412   OverloadCandidateSet::iterator Best;
13413   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13414   case OR_Success:
13415   case OR_Deleted:
13416     break;
13417 
13418   case OR_No_Viable_Function:
13419     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13420       << R.getLookupName();
13421     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13422     return ExprError();
13423 
13424   case OR_Ambiguous:
13425     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13426     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13427     return ExprError();
13428   }
13429 
13430   FunctionDecl *FD = Best->Function;
13431   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13432                                         nullptr, HadMultipleCandidates,
13433                                         SuffixInfo.getLoc(),
13434                                         SuffixInfo.getInfo());
13435   if (Fn.isInvalid())
13436     return true;
13437 
13438   // Check the argument types. This should almost always be a no-op, except
13439   // that array-to-pointer decay is applied to string literals.
13440   Expr *ConvArgs[2];
13441   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13442     ExprResult InputInit = PerformCopyInitialization(
13443       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13444       SourceLocation(), Args[ArgIdx]);
13445     if (InputInit.isInvalid())
13446       return true;
13447     ConvArgs[ArgIdx] = InputInit.get();
13448   }
13449 
13450   QualType ResultTy = FD->getReturnType();
13451   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13452   ResultTy = ResultTy.getNonLValueExprType(Context);
13453 
13454   UserDefinedLiteral *UDL =
13455     new (Context) UserDefinedLiteral(Context, Fn.get(),
13456                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13457                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13458 
13459   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13460     return ExprError();
13461 
13462   if (CheckFunctionCall(FD, UDL, nullptr))
13463     return ExprError();
13464 
13465   return MaybeBindToTemporary(UDL);
13466 }
13467 
13468 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13469 /// given LookupResult is non-empty, it is assumed to describe a member which
13470 /// will be invoked. Otherwise, the function will be found via argument
13471 /// dependent lookup.
13472 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13473 /// otherwise CallExpr is set to ExprError() and some non-success value
13474 /// is returned.
13475 Sema::ForRangeStatus
13476 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13477                                 SourceLocation RangeLoc,
13478                                 const DeclarationNameInfo &NameInfo,
13479                                 LookupResult &MemberLookup,
13480                                 OverloadCandidateSet *CandidateSet,
13481                                 Expr *Range, ExprResult *CallExpr) {
13482   Scope *S = nullptr;
13483 
13484   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13485   if (!MemberLookup.empty()) {
13486     ExprResult MemberRef =
13487         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13488                                  /*IsPtr=*/false, CXXScopeSpec(),
13489                                  /*TemplateKWLoc=*/SourceLocation(),
13490                                  /*FirstQualifierInScope=*/nullptr,
13491                                  MemberLookup,
13492                                  /*TemplateArgs=*/nullptr, S);
13493     if (MemberRef.isInvalid()) {
13494       *CallExpr = ExprError();
13495       return FRS_DiagnosticIssued;
13496     }
13497     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13498     if (CallExpr->isInvalid()) {
13499       *CallExpr = ExprError();
13500       return FRS_DiagnosticIssued;
13501     }
13502   } else {
13503     UnresolvedSet<0> FoundNames;
13504     UnresolvedLookupExpr *Fn =
13505       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13506                                    NestedNameSpecifierLoc(), NameInfo,
13507                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13508                                    FoundNames.begin(), FoundNames.end());
13509 
13510     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13511                                                     CandidateSet, CallExpr);
13512     if (CandidateSet->empty() || CandidateSetError) {
13513       *CallExpr = ExprError();
13514       return FRS_NoViableFunction;
13515     }
13516     OverloadCandidateSet::iterator Best;
13517     OverloadingResult OverloadResult =
13518         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13519 
13520     if (OverloadResult == OR_No_Viable_Function) {
13521       *CallExpr = ExprError();
13522       return FRS_NoViableFunction;
13523     }
13524     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13525                                          Loc, nullptr, CandidateSet, &Best,
13526                                          OverloadResult,
13527                                          /*AllowTypoCorrection=*/false);
13528     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13529       *CallExpr = ExprError();
13530       return FRS_DiagnosticIssued;
13531     }
13532   }
13533   return FRS_Success;
13534 }
13535 
13536 
13537 /// FixOverloadedFunctionReference - E is an expression that refers to
13538 /// a C++ overloaded function (possibly with some parentheses and
13539 /// perhaps a '&' around it). We have resolved the overloaded function
13540 /// to the function declaration Fn, so patch up the expression E to
13541 /// refer (possibly indirectly) to Fn. Returns the new expr.
13542 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13543                                            FunctionDecl *Fn) {
13544   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13545     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13546                                                    Found, Fn);
13547     if (SubExpr == PE->getSubExpr())
13548       return PE;
13549 
13550     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13551   }
13552 
13553   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13554     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13555                                                    Found, Fn);
13556     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13557                                SubExpr->getType()) &&
13558            "Implicit cast type cannot be determined from overload");
13559     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13560     if (SubExpr == ICE->getSubExpr())
13561       return ICE;
13562 
13563     return ImplicitCastExpr::Create(Context, ICE->getType(),
13564                                     ICE->getCastKind(),
13565                                     SubExpr, nullptr,
13566                                     ICE->getValueKind());
13567   }
13568 
13569   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13570     if (!GSE->isResultDependent()) {
13571       Expr *SubExpr =
13572           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13573       if (SubExpr == GSE->getResultExpr())
13574         return GSE;
13575 
13576       // Replace the resulting type information before rebuilding the generic
13577       // selection expression.
13578       ArrayRef<Expr *> A = GSE->getAssocExprs();
13579       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13580       unsigned ResultIdx = GSE->getResultIndex();
13581       AssocExprs[ResultIdx] = SubExpr;
13582 
13583       return new (Context) GenericSelectionExpr(
13584           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13585           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13586           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13587           ResultIdx);
13588     }
13589     // Rather than fall through to the unreachable, return the original generic
13590     // selection expression.
13591     return GSE;
13592   }
13593 
13594   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13595     assert(UnOp->getOpcode() == UO_AddrOf &&
13596            "Can only take the address of an overloaded function");
13597     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13598       if (Method->isStatic()) {
13599         // Do nothing: static member functions aren't any different
13600         // from non-member functions.
13601       } else {
13602         // Fix the subexpression, which really has to be an
13603         // UnresolvedLookupExpr holding an overloaded member function
13604         // or template.
13605         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13606                                                        Found, Fn);
13607         if (SubExpr == UnOp->getSubExpr())
13608           return UnOp;
13609 
13610         assert(isa<DeclRefExpr>(SubExpr)
13611                && "fixed to something other than a decl ref");
13612         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13613                && "fixed to a member ref with no nested name qualifier");
13614 
13615         // We have taken the address of a pointer to member
13616         // function. Perform the computation here so that we get the
13617         // appropriate pointer to member type.
13618         QualType ClassType
13619           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13620         QualType MemPtrType
13621           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13622         // Under the MS ABI, lock down the inheritance model now.
13623         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13624           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13625 
13626         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13627                                            VK_RValue, OK_Ordinary,
13628                                            UnOp->getOperatorLoc(), false);
13629       }
13630     }
13631     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13632                                                    Found, Fn);
13633     if (SubExpr == UnOp->getSubExpr())
13634       return UnOp;
13635 
13636     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13637                                      Context.getPointerType(SubExpr->getType()),
13638                                        VK_RValue, OK_Ordinary,
13639                                        UnOp->getOperatorLoc(), false);
13640   }
13641 
13642   // C++ [except.spec]p17:
13643   //   An exception-specification is considered to be needed when:
13644   //   - in an expression the function is the unique lookup result or the
13645   //     selected member of a set of overloaded functions
13646   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13647     ResolveExceptionSpec(E->getExprLoc(), FPT);
13648 
13649   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13650     // FIXME: avoid copy.
13651     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13652     if (ULE->hasExplicitTemplateArgs()) {
13653       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13654       TemplateArgs = &TemplateArgsBuffer;
13655     }
13656 
13657     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13658                                            ULE->getQualifierLoc(),
13659                                            ULE->getTemplateKeywordLoc(),
13660                                            Fn,
13661                                            /*enclosing*/ false, // FIXME?
13662                                            ULE->getNameLoc(),
13663                                            Fn->getType(),
13664                                            VK_LValue,
13665                                            Found.getDecl(),
13666                                            TemplateArgs);
13667     MarkDeclRefReferenced(DRE);
13668     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13669     return DRE;
13670   }
13671 
13672   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13673     // FIXME: avoid copy.
13674     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13675     if (MemExpr->hasExplicitTemplateArgs()) {
13676       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13677       TemplateArgs = &TemplateArgsBuffer;
13678     }
13679 
13680     Expr *Base;
13681 
13682     // If we're filling in a static method where we used to have an
13683     // implicit member access, rewrite to a simple decl ref.
13684     if (MemExpr->isImplicitAccess()) {
13685       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13686         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13687                                                MemExpr->getQualifierLoc(),
13688                                                MemExpr->getTemplateKeywordLoc(),
13689                                                Fn,
13690                                                /*enclosing*/ false,
13691                                                MemExpr->getMemberLoc(),
13692                                                Fn->getType(),
13693                                                VK_LValue,
13694                                                Found.getDecl(),
13695                                                TemplateArgs);
13696         MarkDeclRefReferenced(DRE);
13697         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13698         return DRE;
13699       } else {
13700         SourceLocation Loc = MemExpr->getMemberLoc();
13701         if (MemExpr->getQualifier())
13702           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13703         CheckCXXThisCapture(Loc);
13704         Base = new (Context) CXXThisExpr(Loc,
13705                                          MemExpr->getBaseType(),
13706                                          /*isImplicit=*/true);
13707       }
13708     } else
13709       Base = MemExpr->getBase();
13710 
13711     ExprValueKind valueKind;
13712     QualType type;
13713     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13714       valueKind = VK_LValue;
13715       type = Fn->getType();
13716     } else {
13717       valueKind = VK_RValue;
13718       type = Context.BoundMemberTy;
13719     }
13720 
13721     MemberExpr *ME = MemberExpr::Create(
13722         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13723         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13724         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13725         OK_Ordinary);
13726     ME->setHadMultipleCandidates(true);
13727     MarkMemberReferenced(ME);
13728     return ME;
13729   }
13730 
13731   llvm_unreachable("Invalid reference to overloaded function");
13732 }
13733 
13734 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13735                                                 DeclAccessPair Found,
13736                                                 FunctionDecl *Fn) {
13737   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13738 }
13739