1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isMemberPointerType() ||
227        getFromType()->isObjCObjectPointerType() ||
228        getFromType()->isBlockPointerType() ||
229        getFromType()->isNullPtrType() ||
230        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231     return true;
232 
233   return false;
234 }
235 
236 /// isPointerConversionToVoidPointer - Determines whether this
237 /// conversion is a conversion of a pointer to a void pointer. This is
238 /// used as part of the ranking of standard conversion sequences (C++
239 /// 13.3.3.2p4).
240 bool
241 StandardConversionSequence::
242 isPointerConversionToVoidPointer(ASTContext& Context) const {
243   QualType FromType = getFromType();
244   QualType ToType = getToType(1);
245 
246   // Note that FromType has not necessarily been transformed by the
247   // array-to-pointer implicit conversion, so check for its presence
248   // and redo the conversion to get a pointer.
249   if (First == ICK_Array_To_Pointer)
250     FromType = Context.getArrayDecayedType(FromType);
251 
252   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254       return ToPtrType->getPointeeType()->isVoidType();
255 
256   return false;
257 }
258 
259 /// Skip any implicit casts which could be either part of a narrowing conversion
260 /// or after one in an implicit conversion.
261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263     switch (ICE->getCastKind()) {
264     case CK_NoOp:
265     case CK_IntegralCast:
266     case CK_IntegralToBoolean:
267     case CK_IntegralToFloating:
268     case CK_BooleanToSignedIntegral:
269     case CK_FloatingToIntegral:
270     case CK_FloatingToBoolean:
271     case CK_FloatingCast:
272       Converted = ICE->getSubExpr();
273       continue;
274 
275     default:
276       return Converted;
277     }
278   }
279 
280   return Converted;
281 }
282 
283 /// Check if this standard conversion sequence represents a narrowing
284 /// conversion, according to C++11 [dcl.init.list]p7.
285 ///
286 /// \param Ctx  The AST context.
287 /// \param Converted  The result of applying this standard conversion sequence.
288 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
289 ///        value of the expression prior to the narrowing conversion.
290 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
291 ///        type of the expression prior to the narrowing conversion.
292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293 ///        from floating point types to integral types should be ignored.
294 NarrowingKind StandardConversionSequence::getNarrowingKind(
295     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298 
299   // C++11 [dcl.init.list]p7:
300   //   A narrowing conversion is an implicit conversion ...
301   QualType FromType = getToType(0);
302   QualType ToType = getToType(1);
303 
304   // A conversion to an enumeration type is narrowing if the conversion to
305   // the underlying type is narrowing. This only arises for expressions of
306   // the form 'Enum{init}'.
307   if (auto *ET = ToType->getAs<EnumType>())
308     ToType = ET->getDecl()->getIntegerType();
309 
310   switch (Second) {
311   // 'bool' is an integral type; dispatch to the right place to handle it.
312   case ICK_Boolean_Conversion:
313     if (FromType->isRealFloatingType())
314       goto FloatingIntegralConversion;
315     if (FromType->isIntegralOrUnscopedEnumerationType())
316       goto IntegralConversion;
317     // Boolean conversions can be from pointers and pointers to members
318     // [conv.bool], and those aren't considered narrowing conversions.
319     return NK_Not_Narrowing;
320 
321   // -- from a floating-point type to an integer type, or
322   //
323   // -- from an integer type or unscoped enumeration type to a floating-point
324   //    type, except where the source is a constant expression and the actual
325   //    value after conversion will fit into the target type and will produce
326   //    the original value when converted back to the original type, or
327   case ICK_Floating_Integral:
328   FloatingIntegralConversion:
329     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330       return NK_Type_Narrowing;
331     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332                ToType->isRealFloatingType()) {
333       if (IgnoreFloatToIntegralConversion)
334         return NK_Not_Narrowing;
335       llvm::APSInt IntConstantValue;
336       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337       assert(Initializer && "Unknown conversion expression");
338 
339       // If it's value-dependent, we can't tell whether it's narrowing.
340       if (Initializer->isValueDependent())
341         return NK_Dependent_Narrowing;
342 
343       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344         // Convert the integer to the floating type.
345         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347                                 llvm::APFloat::rmNearestTiesToEven);
348         // And back.
349         llvm::APSInt ConvertedValue = IntConstantValue;
350         bool ignored;
351         Result.convertToInteger(ConvertedValue,
352                                 llvm::APFloat::rmTowardZero, &ignored);
353         // If the resulting value is different, this was a narrowing conversion.
354         if (IntConstantValue != ConvertedValue) {
355           ConstantValue = APValue(IntConstantValue);
356           ConstantType = Initializer->getType();
357           return NK_Constant_Narrowing;
358         }
359       } else {
360         // Variables are always narrowings.
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365 
366   // -- from long double to double or float, or from double to float, except
367   //    where the source is a constant expression and the actual value after
368   //    conversion is within the range of values that can be represented (even
369   //    if it cannot be represented exactly), or
370   case ICK_Floating_Conversion:
371     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373       // FromType is larger than ToType.
374       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375 
376       // If it's value-dependent, we can't tell whether it's narrowing.
377       if (Initializer->isValueDependent())
378         return NK_Dependent_Narrowing;
379 
380       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381         // Constant!
382         assert(ConstantValue.isFloat());
383         llvm::APFloat FloatVal = ConstantValue.getFloat();
384         // Convert the source value into the target type.
385         bool ignored;
386         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387           Ctx.getFloatTypeSemantics(ToType),
388           llvm::APFloat::rmNearestTiesToEven, &ignored);
389         // If there was no overflow, the source value is within the range of
390         // values that can be represented.
391         if (ConvertStatus & llvm::APFloat::opOverflow) {
392           ConstantType = Initializer->getType();
393           return NK_Constant_Narrowing;
394         }
395       } else {
396         return NK_Variable_Narrowing;
397       }
398     }
399     return NK_Not_Narrowing;
400 
401   // -- from an integer type or unscoped enumeration type to an integer type
402   //    that cannot represent all the values of the original type, except where
403   //    the source is a constant expression and the actual value after
404   //    conversion will fit into the target type and will produce the original
405   //    value when converted back to the original type.
406   case ICK_Integral_Conversion:
407   IntegralConversion: {
408     assert(FromType->isIntegralOrUnscopedEnumerationType());
409     assert(ToType->isIntegralOrUnscopedEnumerationType());
410     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411     const unsigned FromWidth = Ctx.getIntWidth(FromType);
412     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413     const unsigned ToWidth = Ctx.getIntWidth(ToType);
414 
415     if (FromWidth > ToWidth ||
416         (FromWidth == ToWidth && FromSigned != ToSigned) ||
417         (FromSigned && !ToSigned)) {
418       // Not all values of FromType can be represented in ToType.
419       llvm::APSInt InitializerValue;
420       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421 
422       // If it's value-dependent, we can't tell whether it's narrowing.
423       if (Initializer->isValueDependent())
424         return NK_Dependent_Narrowing;
425 
426       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427         // Such conversions on variables are always narrowing.
428         return NK_Variable_Narrowing;
429       }
430       bool Narrowing = false;
431       if (FromWidth < ToWidth) {
432         // Negative -> unsigned is narrowing. Otherwise, more bits is never
433         // narrowing.
434         if (InitializerValue.isSigned() && InitializerValue.isNegative())
435           Narrowing = true;
436       } else {
437         // Add a bit to the InitializerValue so we don't have to worry about
438         // signed vs. unsigned comparisons.
439         InitializerValue = InitializerValue.extend(
440           InitializerValue.getBitWidth() + 1);
441         // Convert the initializer to and from the target width and signed-ness.
442         llvm::APSInt ConvertedValue = InitializerValue;
443         ConvertedValue = ConvertedValue.trunc(ToWidth);
444         ConvertedValue.setIsSigned(ToSigned);
445         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446         ConvertedValue.setIsSigned(InitializerValue.isSigned());
447         // If the result is different, this was a narrowing conversion.
448         if (ConvertedValue != InitializerValue)
449           Narrowing = true;
450       }
451       if (Narrowing) {
452         ConstantType = Initializer->getType();
453         ConstantValue = APValue(InitializerValue);
454         return NK_Constant_Narrowing;
455       }
456     }
457     return NK_Not_Narrowing;
458   }
459 
460   default:
461     // Other kinds of conversions are not narrowings.
462     return NK_Not_Narrowing;
463   }
464 }
465 
466 /// dump - Print this standard conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
469   raw_ostream &OS = llvm::errs();
470   bool PrintedSomething = false;
471   if (First != ICK_Identity) {
472     OS << GetImplicitConversionName(First);
473     PrintedSomething = true;
474   }
475 
476   if (Second != ICK_Identity) {
477     if (PrintedSomething) {
478       OS << " -> ";
479     }
480     OS << GetImplicitConversionName(Second);
481 
482     if (CopyConstructor) {
483       OS << " (by copy constructor)";
484     } else if (DirectBinding) {
485       OS << " (direct reference binding)";
486     } else if (ReferenceBinding) {
487       OS << " (reference binding)";
488     }
489     PrintedSomething = true;
490   }
491 
492   if (Third != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Third);
497     PrintedSomething = true;
498   }
499 
500   if (!PrintedSomething) {
501     OS << "No conversions required";
502   }
503 }
504 
505 /// dump - Print this user-defined conversion sequence to standard
506 /// error. Useful for debugging overloading issues.
507 void UserDefinedConversionSequence::dump() const {
508   raw_ostream &OS = llvm::errs();
509   if (Before.First || Before.Second || Before.Third) {
510     Before.dump();
511     OS << " -> ";
512   }
513   if (ConversionFunction)
514     OS << '\'' << *ConversionFunction << '\'';
515   else
516     OS << "aggregate initialization";
517   if (After.First || After.Second || After.Third) {
518     OS << " -> ";
519     After.dump();
520   }
521 }
522 
523 /// dump - Print this implicit conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
525 void ImplicitConversionSequence::dump() const {
526   raw_ostream &OS = llvm::errs();
527   if (isStdInitializerListElement())
528     OS << "Worst std::initializer_list element conversion: ";
529   switch (ConversionKind) {
530   case StandardConversion:
531     OS << "Standard conversion: ";
532     Standard.dump();
533     break;
534   case UserDefinedConversion:
535     OS << "User-defined conversion: ";
536     UserDefined.dump();
537     break;
538   case EllipsisConversion:
539     OS << "Ellipsis conversion";
540     break;
541   case AmbiguousConversion:
542     OS << "Ambiguous conversion";
543     break;
544   case BadConversion:
545     OS << "Bad conversion";
546     break;
547   }
548 
549   OS << "\n";
550 }
551 
552 void AmbiguousConversionSequence::construct() {
553   new (&conversions()) ConversionSet();
554 }
555 
556 void AmbiguousConversionSequence::destruct() {
557   conversions().~ConversionSet();
558 }
559 
560 void
561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562   FromTypePtr = O.FromTypePtr;
563   ToTypePtr = O.ToTypePtr;
564   new (&conversions()) ConversionSet(O.conversions());
565 }
566 
567 namespace {
568   // Structure used by DeductionFailureInfo to store
569   // template argument information.
570   struct DFIArguments {
571     TemplateArgument FirstArg;
572     TemplateArgument SecondArg;
573   };
574   // Structure used by DeductionFailureInfo to store
575   // template parameter and template argument information.
576   struct DFIParamWithArguments : DFIArguments {
577     TemplateParameter Param;
578   };
579   // Structure used by DeductionFailureInfo to store template argument
580   // information and the index of the problematic call argument.
581   struct DFIDeducedMismatchArgs : DFIArguments {
582     TemplateArgumentList *TemplateArgs;
583     unsigned CallArgIndex;
584   };
585 }
586 
587 /// Convert from Sema's representation of template deduction information
588 /// to the form used in overload-candidate information.
589 DeductionFailureInfo
590 clang::MakeDeductionFailureInfo(ASTContext &Context,
591                                 Sema::TemplateDeductionResult TDK,
592                                 TemplateDeductionInfo &Info) {
593   DeductionFailureInfo Result;
594   Result.Result = static_cast<unsigned>(TDK);
595   Result.HasDiagnostic = false;
596   switch (TDK) {
597   case Sema::TDK_Invalid:
598   case Sema::TDK_InstantiationDepth:
599   case Sema::TDK_TooManyArguments:
600   case Sema::TDK_TooFewArguments:
601   case Sema::TDK_MiscellaneousDeductionFailure:
602   case Sema::TDK_CUDATargetMismatch:
603     Result.Data = nullptr;
604     break;
605 
606   case Sema::TDK_Incomplete:
607   case Sema::TDK_InvalidExplicitArguments:
608     Result.Data = Info.Param.getOpaqueValue();
609     break;
610 
611   case Sema::TDK_DeducedMismatch:
612   case Sema::TDK_DeducedMismatchNested: {
613     // FIXME: Should allocate from normal heap so that we can free this later.
614     auto *Saved = new (Context) DFIDeducedMismatchArgs;
615     Saved->FirstArg = Info.FirstArg;
616     Saved->SecondArg = Info.SecondArg;
617     Saved->TemplateArgs = Info.take();
618     Saved->CallArgIndex = Info.CallArgIndex;
619     Result.Data = Saved;
620     break;
621   }
622 
623   case Sema::TDK_NonDeducedMismatch: {
624     // FIXME: Should allocate from normal heap so that we can free this later.
625     DFIArguments *Saved = new (Context) DFIArguments;
626     Saved->FirstArg = Info.FirstArg;
627     Saved->SecondArg = Info.SecondArg;
628     Result.Data = Saved;
629     break;
630   }
631 
632   case Sema::TDK_Inconsistent:
633   case Sema::TDK_Underqualified: {
634     // FIXME: Should allocate from normal heap so that we can free this later.
635     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
636     Saved->Param = Info.Param;
637     Saved->FirstArg = Info.FirstArg;
638     Saved->SecondArg = Info.SecondArg;
639     Result.Data = Saved;
640     break;
641   }
642 
643   case Sema::TDK_SubstitutionFailure:
644     Result.Data = Info.take();
645     if (Info.hasSFINAEDiagnostic()) {
646       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
647           SourceLocation(), PartialDiagnostic::NullDiagnostic());
648       Info.takeSFINAEDiagnostic(*Diag);
649       Result.HasDiagnostic = true;
650     }
651     break;
652 
653   case Sema::TDK_Success:
654   case Sema::TDK_NonDependentConversionFailure:
655     llvm_unreachable("not a deduction failure");
656   }
657 
658   return Result;
659 }
660 
661 void DeductionFailureInfo::Destroy() {
662   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663   case Sema::TDK_Success:
664   case Sema::TDK_Invalid:
665   case Sema::TDK_InstantiationDepth:
666   case Sema::TDK_Incomplete:
667   case Sema::TDK_TooManyArguments:
668   case Sema::TDK_TooFewArguments:
669   case Sema::TDK_InvalidExplicitArguments:
670   case Sema::TDK_CUDATargetMismatch:
671   case Sema::TDK_NonDependentConversionFailure:
672     break;
673 
674   case Sema::TDK_Inconsistent:
675   case Sema::TDK_Underqualified:
676   case Sema::TDK_DeducedMismatch:
677   case Sema::TDK_DeducedMismatchNested:
678   case Sema::TDK_NonDeducedMismatch:
679     // FIXME: Destroy the data?
680     Data = nullptr;
681     break;
682 
683   case Sema::TDK_SubstitutionFailure:
684     // FIXME: Destroy the template argument list?
685     Data = nullptr;
686     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
687       Diag->~PartialDiagnosticAt();
688       HasDiagnostic = false;
689     }
690     break;
691 
692   // Unhandled
693   case Sema::TDK_MiscellaneousDeductionFailure:
694     break;
695   }
696 }
697 
698 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
699   if (HasDiagnostic)
700     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
701   return nullptr;
702 }
703 
704 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
705   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
706   case Sema::TDK_Success:
707   case Sema::TDK_Invalid:
708   case Sema::TDK_InstantiationDepth:
709   case Sema::TDK_TooManyArguments:
710   case Sema::TDK_TooFewArguments:
711   case Sema::TDK_SubstitutionFailure:
712   case Sema::TDK_DeducedMismatch:
713   case Sema::TDK_DeducedMismatchNested:
714   case Sema::TDK_NonDeducedMismatch:
715   case Sema::TDK_CUDATargetMismatch:
716   case Sema::TDK_NonDependentConversionFailure:
717     return TemplateParameter();
718 
719   case Sema::TDK_Incomplete:
720   case Sema::TDK_InvalidExplicitArguments:
721     return TemplateParameter::getFromOpaqueValue(Data);
722 
723   case Sema::TDK_Inconsistent:
724   case Sema::TDK_Underqualified:
725     return static_cast<DFIParamWithArguments*>(Data)->Param;
726 
727   // Unhandled
728   case Sema::TDK_MiscellaneousDeductionFailure:
729     break;
730   }
731 
732   return TemplateParameter();
733 }
734 
735 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
736   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
737   case Sema::TDK_Success:
738   case Sema::TDK_Invalid:
739   case Sema::TDK_InstantiationDepth:
740   case Sema::TDK_TooManyArguments:
741   case Sema::TDK_TooFewArguments:
742   case Sema::TDK_Incomplete:
743   case Sema::TDK_InvalidExplicitArguments:
744   case Sema::TDK_Inconsistent:
745   case Sema::TDK_Underqualified:
746   case Sema::TDK_NonDeducedMismatch:
747   case Sema::TDK_CUDATargetMismatch:
748   case Sema::TDK_NonDependentConversionFailure:
749     return nullptr;
750 
751   case Sema::TDK_DeducedMismatch:
752   case Sema::TDK_DeducedMismatchNested:
753     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
754 
755   case Sema::TDK_SubstitutionFailure:
756     return static_cast<TemplateArgumentList*>(Data);
757 
758   // Unhandled
759   case Sema::TDK_MiscellaneousDeductionFailure:
760     break;
761   }
762 
763   return nullptr;
764 }
765 
766 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
767   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768   case Sema::TDK_Success:
769   case Sema::TDK_Invalid:
770   case Sema::TDK_InstantiationDepth:
771   case Sema::TDK_Incomplete:
772   case Sema::TDK_TooManyArguments:
773   case Sema::TDK_TooFewArguments:
774   case Sema::TDK_InvalidExplicitArguments:
775   case Sema::TDK_SubstitutionFailure:
776   case Sema::TDK_CUDATargetMismatch:
777   case Sema::TDK_NonDependentConversionFailure:
778     return nullptr;
779 
780   case Sema::TDK_Inconsistent:
781   case Sema::TDK_Underqualified:
782   case Sema::TDK_DeducedMismatch:
783   case Sema::TDK_DeducedMismatchNested:
784   case Sema::TDK_NonDeducedMismatch:
785     return &static_cast<DFIArguments*>(Data)->FirstArg;
786 
787   // Unhandled
788   case Sema::TDK_MiscellaneousDeductionFailure:
789     break;
790   }
791 
792   return nullptr;
793 }
794 
795 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
796   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
797   case Sema::TDK_Success:
798   case Sema::TDK_Invalid:
799   case Sema::TDK_InstantiationDepth:
800   case Sema::TDK_Incomplete:
801   case Sema::TDK_TooManyArguments:
802   case Sema::TDK_TooFewArguments:
803   case Sema::TDK_InvalidExplicitArguments:
804   case Sema::TDK_SubstitutionFailure:
805   case Sema::TDK_CUDATargetMismatch:
806   case Sema::TDK_NonDependentConversionFailure:
807     return nullptr;
808 
809   case Sema::TDK_Inconsistent:
810   case Sema::TDK_Underqualified:
811   case Sema::TDK_DeducedMismatch:
812   case Sema::TDK_DeducedMismatchNested:
813   case Sema::TDK_NonDeducedMismatch:
814     return &static_cast<DFIArguments*>(Data)->SecondArg;
815 
816   // Unhandled
817   case Sema::TDK_MiscellaneousDeductionFailure:
818     break;
819   }
820 
821   return nullptr;
822 }
823 
824 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
825   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
826   case Sema::TDK_DeducedMismatch:
827   case Sema::TDK_DeducedMismatchNested:
828     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
829 
830   default:
831     return llvm::None;
832   }
833 }
834 
835 void OverloadCandidateSet::destroyCandidates() {
836   for (iterator i = begin(), e = end(); i != e; ++i) {
837     for (auto &C : i->Conversions)
838       C.~ImplicitConversionSequence();
839     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
840       i->DeductionFailure.Destroy();
841   }
842 }
843 
844 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
845   destroyCandidates();
846   SlabAllocator.Reset();
847   NumInlineBytesUsed = 0;
848   Candidates.clear();
849   Functions.clear();
850   Kind = CSK;
851 }
852 
853 namespace {
854   class UnbridgedCastsSet {
855     struct Entry {
856       Expr **Addr;
857       Expr *Saved;
858     };
859     SmallVector<Entry, 2> Entries;
860 
861   public:
862     void save(Sema &S, Expr *&E) {
863       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
864       Entry entry = { &E, E };
865       Entries.push_back(entry);
866       E = S.stripARCUnbridgedCast(E);
867     }
868 
869     void restore() {
870       for (SmallVectorImpl<Entry>::iterator
871              i = Entries.begin(), e = Entries.end(); i != e; ++i)
872         *i->Addr = i->Saved;
873     }
874   };
875 }
876 
877 /// checkPlaceholderForOverload - Do any interesting placeholder-like
878 /// preprocessing on the given expression.
879 ///
880 /// \param unbridgedCasts a collection to which to add unbridged casts;
881 ///   without this, they will be immediately diagnosed as errors
882 ///
883 /// Return true on unrecoverable error.
884 static bool
885 checkPlaceholderForOverload(Sema &S, Expr *&E,
886                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
887   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
888     // We can't handle overloaded expressions here because overload
889     // resolution might reasonably tweak them.
890     if (placeholder->getKind() == BuiltinType::Overload) return false;
891 
892     // If the context potentially accepts unbridged ARC casts, strip
893     // the unbridged cast and add it to the collection for later restoration.
894     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
895         unbridgedCasts) {
896       unbridgedCasts->save(S, E);
897       return false;
898     }
899 
900     // Go ahead and check everything else.
901     ExprResult result = S.CheckPlaceholderExpr(E);
902     if (result.isInvalid())
903       return true;
904 
905     E = result.get();
906     return false;
907   }
908 
909   // Nothing to do.
910   return false;
911 }
912 
913 /// checkArgPlaceholdersForOverload - Check a set of call operands for
914 /// placeholders.
915 static bool checkArgPlaceholdersForOverload(Sema &S,
916                                             MultiExprArg Args,
917                                             UnbridgedCastsSet &unbridged) {
918   for (unsigned i = 0, e = Args.size(); i != e; ++i)
919     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
920       return true;
921 
922   return false;
923 }
924 
925 /// Determine whether the given New declaration is an overload of the
926 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
927 /// New and Old cannot be overloaded, e.g., if New has the same signature as
928 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
929 /// functions (or function templates) at all. When it does return Ovl_Match or
930 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
931 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
932 /// declaration.
933 ///
934 /// Example: Given the following input:
935 ///
936 ///   void f(int, float); // #1
937 ///   void f(int, int); // #2
938 ///   int f(int, int); // #3
939 ///
940 /// When we process #1, there is no previous declaration of "f", so IsOverload
941 /// will not be used.
942 ///
943 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
944 /// the parameter types, we see that #1 and #2 are overloaded (since they have
945 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
946 /// unchanged.
947 ///
948 /// When we process #3, Old is an overload set containing #1 and #2. We compare
949 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
950 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
951 /// functions are not part of the signature), IsOverload returns Ovl_Match and
952 /// MatchedDecl will be set to point to the FunctionDecl for #2.
953 ///
954 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
955 /// by a using declaration. The rules for whether to hide shadow declarations
956 /// ignore some properties which otherwise figure into a function template's
957 /// signature.
958 Sema::OverloadKind
959 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
960                     NamedDecl *&Match, bool NewIsUsingDecl) {
961   for (LookupResult::iterator I = Old.begin(), E = Old.end();
962          I != E; ++I) {
963     NamedDecl *OldD = *I;
964 
965     bool OldIsUsingDecl = false;
966     if (isa<UsingShadowDecl>(OldD)) {
967       OldIsUsingDecl = true;
968 
969       // We can always introduce two using declarations into the same
970       // context, even if they have identical signatures.
971       if (NewIsUsingDecl) continue;
972 
973       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
974     }
975 
976     // A using-declaration does not conflict with another declaration
977     // if one of them is hidden.
978     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
979       continue;
980 
981     // If either declaration was introduced by a using declaration,
982     // we'll need to use slightly different rules for matching.
983     // Essentially, these rules are the normal rules, except that
984     // function templates hide function templates with different
985     // return types or template parameter lists.
986     bool UseMemberUsingDeclRules =
987       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
988       !New->getFriendObjectKind();
989 
990     if (FunctionDecl *OldF = OldD->getAsFunction()) {
991       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
992         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
993           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
994           continue;
995         }
996 
997         if (!isa<FunctionTemplateDecl>(OldD) &&
998             !shouldLinkPossiblyHiddenDecl(*I, New))
999           continue;
1000 
1001         Match = *I;
1002         return Ovl_Match;
1003       }
1004 
1005       // Builtins that have custom typechecking or have a reference should
1006       // not be overloadable or redeclarable.
1007       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1008         Match = *I;
1009         return Ovl_NonFunction;
1010       }
1011     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1012       // We can overload with these, which can show up when doing
1013       // redeclaration checks for UsingDecls.
1014       assert(Old.getLookupKind() == LookupUsingDeclName);
1015     } else if (isa<TagDecl>(OldD)) {
1016       // We can always overload with tags by hiding them.
1017     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1018       // Optimistically assume that an unresolved using decl will
1019       // overload; if it doesn't, we'll have to diagnose during
1020       // template instantiation.
1021       //
1022       // Exception: if the scope is dependent and this is not a class
1023       // member, the using declaration can only introduce an enumerator.
1024       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1025         Match = *I;
1026         return Ovl_NonFunction;
1027       }
1028     } else {
1029       // (C++ 13p1):
1030       //   Only function declarations can be overloaded; object and type
1031       //   declarations cannot be overloaded.
1032       Match = *I;
1033       return Ovl_NonFunction;
1034     }
1035   }
1036 
1037   return Ovl_Overload;
1038 }
1039 
1040 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1041                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1042   // C++ [basic.start.main]p2: This function shall not be overloaded.
1043   if (New->isMain())
1044     return false;
1045 
1046   // MSVCRT user defined entry points cannot be overloaded.
1047   if (New->isMSVCRTEntryPoint())
1048     return false;
1049 
1050   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1051   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1052 
1053   // C++ [temp.fct]p2:
1054   //   A function template can be overloaded with other function templates
1055   //   and with normal (non-template) functions.
1056   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1057     return true;
1058 
1059   // Is the function New an overload of the function Old?
1060   QualType OldQType = Context.getCanonicalType(Old->getType());
1061   QualType NewQType = Context.getCanonicalType(New->getType());
1062 
1063   // Compare the signatures (C++ 1.3.10) of the two functions to
1064   // determine whether they are overloads. If we find any mismatch
1065   // in the signature, they are overloads.
1066 
1067   // If either of these functions is a K&R-style function (no
1068   // prototype), then we consider them to have matching signatures.
1069   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1070       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1071     return false;
1072 
1073   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1074   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1075 
1076   // The signature of a function includes the types of its
1077   // parameters (C++ 1.3.10), which includes the presence or absence
1078   // of the ellipsis; see C++ DR 357).
1079   if (OldQType != NewQType &&
1080       (OldType->getNumParams() != NewType->getNumParams() ||
1081        OldType->isVariadic() != NewType->isVariadic() ||
1082        !FunctionParamTypesAreEqual(OldType, NewType)))
1083     return true;
1084 
1085   // C++ [temp.over.link]p4:
1086   //   The signature of a function template consists of its function
1087   //   signature, its return type and its template parameter list. The names
1088   //   of the template parameters are significant only for establishing the
1089   //   relationship between the template parameters and the rest of the
1090   //   signature.
1091   //
1092   // We check the return type and template parameter lists for function
1093   // templates first; the remaining checks follow.
1094   //
1095   // However, we don't consider either of these when deciding whether
1096   // a member introduced by a shadow declaration is hidden.
1097   if (!UseMemberUsingDeclRules && NewTemplate &&
1098       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1099                                        OldTemplate->getTemplateParameters(),
1100                                        false, TPL_TemplateMatch) ||
1101        OldType->getReturnType() != NewType->getReturnType()))
1102     return true;
1103 
1104   // If the function is a class member, its signature includes the
1105   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1106   //
1107   // As part of this, also check whether one of the member functions
1108   // is static, in which case they are not overloads (C++
1109   // 13.1p2). While not part of the definition of the signature,
1110   // this check is important to determine whether these functions
1111   // can be overloaded.
1112   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1113   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1114   if (OldMethod && NewMethod &&
1115       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1116     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1117       if (!UseMemberUsingDeclRules &&
1118           (OldMethod->getRefQualifier() == RQ_None ||
1119            NewMethod->getRefQualifier() == RQ_None)) {
1120         // C++0x [over.load]p2:
1121         //   - Member function declarations with the same name and the same
1122         //     parameter-type-list as well as member function template
1123         //     declarations with the same name, the same parameter-type-list, and
1124         //     the same template parameter lists cannot be overloaded if any of
1125         //     them, but not all, have a ref-qualifier (8.3.5).
1126         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1127           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1128         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1129       }
1130       return true;
1131     }
1132 
1133     // We may not have applied the implicit const for a constexpr member
1134     // function yet (because we haven't yet resolved whether this is a static
1135     // or non-static member function). Add it now, on the assumption that this
1136     // is a redeclaration of OldMethod.
1137     unsigned OldQuals = OldMethod->getTypeQualifiers();
1138     unsigned NewQuals = NewMethod->getTypeQualifiers();
1139     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1140         !isa<CXXConstructorDecl>(NewMethod))
1141       NewQuals |= Qualifiers::Const;
1142 
1143     // We do not allow overloading based off of '__restrict'.
1144     OldQuals &= ~Qualifiers::Restrict;
1145     NewQuals &= ~Qualifiers::Restrict;
1146     if (OldQuals != NewQuals)
1147       return true;
1148   }
1149 
1150   // Though pass_object_size is placed on parameters and takes an argument, we
1151   // consider it to be a function-level modifier for the sake of function
1152   // identity. Either the function has one or more parameters with
1153   // pass_object_size or it doesn't.
1154   if (functionHasPassObjectSizeParams(New) !=
1155       functionHasPassObjectSizeParams(Old))
1156     return true;
1157 
1158   // enable_if attributes are an order-sensitive part of the signature.
1159   for (specific_attr_iterator<EnableIfAttr>
1160          NewI = New->specific_attr_begin<EnableIfAttr>(),
1161          NewE = New->specific_attr_end<EnableIfAttr>(),
1162          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1163          OldE = Old->specific_attr_end<EnableIfAttr>();
1164        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1165     if (NewI == NewE || OldI == OldE)
1166       return true;
1167     llvm::FoldingSetNodeID NewID, OldID;
1168     NewI->getCond()->Profile(NewID, Context, true);
1169     OldI->getCond()->Profile(OldID, Context, true);
1170     if (NewID != OldID)
1171       return true;
1172   }
1173 
1174   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1175     // Don't allow overloading of destructors.  (In theory we could, but it
1176     // would be a giant change to clang.)
1177     if (isa<CXXDestructorDecl>(New))
1178       return false;
1179 
1180     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1181                        OldTarget = IdentifyCUDATarget(Old);
1182     if (NewTarget == CFT_InvalidTarget)
1183       return false;
1184 
1185     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1186 
1187     // Allow overloading of functions with same signature and different CUDA
1188     // target attributes.
1189     return NewTarget != OldTarget;
1190   }
1191 
1192   // The signatures match; this is not an overload.
1193   return false;
1194 }
1195 
1196 /// Checks availability of the function depending on the current
1197 /// function context. Inside an unavailable function, unavailability is ignored.
1198 ///
1199 /// \returns true if \arg FD is unavailable and current context is inside
1200 /// an available function, false otherwise.
1201 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1202   if (!FD->isUnavailable())
1203     return false;
1204 
1205   // Walk up the context of the caller.
1206   Decl *C = cast<Decl>(CurContext);
1207   do {
1208     if (C->isUnavailable())
1209       return false;
1210   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1211   return true;
1212 }
1213 
1214 /// Tries a user-defined conversion from From to ToType.
1215 ///
1216 /// Produces an implicit conversion sequence for when a standard conversion
1217 /// is not an option. See TryImplicitConversion for more information.
1218 static ImplicitConversionSequence
1219 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1220                          bool SuppressUserConversions,
1221                          bool AllowExplicit,
1222                          bool InOverloadResolution,
1223                          bool CStyle,
1224                          bool AllowObjCWritebackConversion,
1225                          bool AllowObjCConversionOnExplicit) {
1226   ImplicitConversionSequence ICS;
1227 
1228   if (SuppressUserConversions) {
1229     // We're not in the case above, so there is no conversion that
1230     // we can perform.
1231     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1232     return ICS;
1233   }
1234 
1235   // Attempt user-defined conversion.
1236   OverloadCandidateSet Conversions(From->getExprLoc(),
1237                                    OverloadCandidateSet::CSK_Normal);
1238   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1239                                   Conversions, AllowExplicit,
1240                                   AllowObjCConversionOnExplicit)) {
1241   case OR_Success:
1242   case OR_Deleted:
1243     ICS.setUserDefined();
1244     // C++ [over.ics.user]p4:
1245     //   A conversion of an expression of class type to the same class
1246     //   type is given Exact Match rank, and a conversion of an
1247     //   expression of class type to a base class of that type is
1248     //   given Conversion rank, in spite of the fact that a copy
1249     //   constructor (i.e., a user-defined conversion function) is
1250     //   called for those cases.
1251     if (CXXConstructorDecl *Constructor
1252           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1253       QualType FromCanon
1254         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1255       QualType ToCanon
1256         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1257       if (Constructor->isCopyConstructor() &&
1258           (FromCanon == ToCanon ||
1259            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1260         // Turn this into a "standard" conversion sequence, so that it
1261         // gets ranked with standard conversion sequences.
1262         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1263         ICS.setStandard();
1264         ICS.Standard.setAsIdentityConversion();
1265         ICS.Standard.setFromType(From->getType());
1266         ICS.Standard.setAllToTypes(ToType);
1267         ICS.Standard.CopyConstructor = Constructor;
1268         ICS.Standard.FoundCopyConstructor = Found;
1269         if (ToCanon != FromCanon)
1270           ICS.Standard.Second = ICK_Derived_To_Base;
1271       }
1272     }
1273     break;
1274 
1275   case OR_Ambiguous:
1276     ICS.setAmbiguous();
1277     ICS.Ambiguous.setFromType(From->getType());
1278     ICS.Ambiguous.setToType(ToType);
1279     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1280          Cand != Conversions.end(); ++Cand)
1281       if (Cand->Viable)
1282         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1283     break;
1284 
1285     // Fall through.
1286   case OR_No_Viable_Function:
1287     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1288     break;
1289   }
1290 
1291   return ICS;
1292 }
1293 
1294 /// TryImplicitConversion - Attempt to perform an implicit conversion
1295 /// from the given expression (Expr) to the given type (ToType). This
1296 /// function returns an implicit conversion sequence that can be used
1297 /// to perform the initialization. Given
1298 ///
1299 ///   void f(float f);
1300 ///   void g(int i) { f(i); }
1301 ///
1302 /// this routine would produce an implicit conversion sequence to
1303 /// describe the initialization of f from i, which will be a standard
1304 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1305 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1306 //
1307 /// Note that this routine only determines how the conversion can be
1308 /// performed; it does not actually perform the conversion. As such,
1309 /// it will not produce any diagnostics if no conversion is available,
1310 /// but will instead return an implicit conversion sequence of kind
1311 /// "BadConversion".
1312 ///
1313 /// If @p SuppressUserConversions, then user-defined conversions are
1314 /// not permitted.
1315 /// If @p AllowExplicit, then explicit user-defined conversions are
1316 /// permitted.
1317 ///
1318 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1319 /// writeback conversion, which allows __autoreleasing id* parameters to
1320 /// be initialized with __strong id* or __weak id* arguments.
1321 static ImplicitConversionSequence
1322 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1323                       bool SuppressUserConversions,
1324                       bool AllowExplicit,
1325                       bool InOverloadResolution,
1326                       bool CStyle,
1327                       bool AllowObjCWritebackConversion,
1328                       bool AllowObjCConversionOnExplicit) {
1329   ImplicitConversionSequence ICS;
1330   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1331                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1332     ICS.setStandard();
1333     return ICS;
1334   }
1335 
1336   if (!S.getLangOpts().CPlusPlus) {
1337     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1338     return ICS;
1339   }
1340 
1341   // C++ [over.ics.user]p4:
1342   //   A conversion of an expression of class type to the same class
1343   //   type is given Exact Match rank, and a conversion of an
1344   //   expression of class type to a base class of that type is
1345   //   given Conversion rank, in spite of the fact that a copy/move
1346   //   constructor (i.e., a user-defined conversion function) is
1347   //   called for those cases.
1348   QualType FromType = From->getType();
1349   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1350       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1351        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1352     ICS.setStandard();
1353     ICS.Standard.setAsIdentityConversion();
1354     ICS.Standard.setFromType(FromType);
1355     ICS.Standard.setAllToTypes(ToType);
1356 
1357     // We don't actually check at this point whether there is a valid
1358     // copy/move constructor, since overloading just assumes that it
1359     // exists. When we actually perform initialization, we'll find the
1360     // appropriate constructor to copy the returned object, if needed.
1361     ICS.Standard.CopyConstructor = nullptr;
1362 
1363     // Determine whether this is considered a derived-to-base conversion.
1364     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1365       ICS.Standard.Second = ICK_Derived_To_Base;
1366 
1367     return ICS;
1368   }
1369 
1370   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1371                                   AllowExplicit, InOverloadResolution, CStyle,
1372                                   AllowObjCWritebackConversion,
1373                                   AllowObjCConversionOnExplicit);
1374 }
1375 
1376 ImplicitConversionSequence
1377 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1378                             bool SuppressUserConversions,
1379                             bool AllowExplicit,
1380                             bool InOverloadResolution,
1381                             bool CStyle,
1382                             bool AllowObjCWritebackConversion) {
1383   return ::TryImplicitConversion(*this, From, ToType,
1384                                  SuppressUserConversions, AllowExplicit,
1385                                  InOverloadResolution, CStyle,
1386                                  AllowObjCWritebackConversion,
1387                                  /*AllowObjCConversionOnExplicit=*/false);
1388 }
1389 
1390 /// PerformImplicitConversion - Perform an implicit conversion of the
1391 /// expression From to the type ToType. Returns the
1392 /// converted expression. Flavor is the kind of conversion we're
1393 /// performing, used in the error message. If @p AllowExplicit,
1394 /// explicit user-defined conversions are permitted.
1395 ExprResult
1396 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1397                                 AssignmentAction Action, bool AllowExplicit) {
1398   ImplicitConversionSequence ICS;
1399   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1400 }
1401 
1402 ExprResult
1403 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1404                                 AssignmentAction Action, bool AllowExplicit,
1405                                 ImplicitConversionSequence& ICS) {
1406   if (checkPlaceholderForOverload(*this, From))
1407     return ExprError();
1408 
1409   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1410   bool AllowObjCWritebackConversion
1411     = getLangOpts().ObjCAutoRefCount &&
1412       (Action == AA_Passing || Action == AA_Sending);
1413   if (getLangOpts().ObjC1)
1414     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1415                                       ToType, From->getType(), From);
1416   ICS = ::TryImplicitConversion(*this, From, ToType,
1417                                 /*SuppressUserConversions=*/false,
1418                                 AllowExplicit,
1419                                 /*InOverloadResolution=*/false,
1420                                 /*CStyle=*/false,
1421                                 AllowObjCWritebackConversion,
1422                                 /*AllowObjCConversionOnExplicit=*/false);
1423   return PerformImplicitConversion(From, ToType, ICS, Action);
1424 }
1425 
1426 /// Determine whether the conversion from FromType to ToType is a valid
1427 /// conversion that strips "noexcept" or "noreturn" off the nested function
1428 /// type.
1429 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1430                                 QualType &ResultTy) {
1431   if (Context.hasSameUnqualifiedType(FromType, ToType))
1432     return false;
1433 
1434   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1435   //                    or F(t noexcept) -> F(t)
1436   // where F adds one of the following at most once:
1437   //   - a pointer
1438   //   - a member pointer
1439   //   - a block pointer
1440   // Changes here need matching changes in FindCompositePointerType.
1441   CanQualType CanTo = Context.getCanonicalType(ToType);
1442   CanQualType CanFrom = Context.getCanonicalType(FromType);
1443   Type::TypeClass TyClass = CanTo->getTypeClass();
1444   if (TyClass != CanFrom->getTypeClass()) return false;
1445   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1446     if (TyClass == Type::Pointer) {
1447       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1448       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1449     } else if (TyClass == Type::BlockPointer) {
1450       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1451       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1452     } else if (TyClass == Type::MemberPointer) {
1453       auto ToMPT = CanTo.getAs<MemberPointerType>();
1454       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1455       // A function pointer conversion cannot change the class of the function.
1456       if (ToMPT->getClass() != FromMPT->getClass())
1457         return false;
1458       CanTo = ToMPT->getPointeeType();
1459       CanFrom = FromMPT->getPointeeType();
1460     } else {
1461       return false;
1462     }
1463 
1464     TyClass = CanTo->getTypeClass();
1465     if (TyClass != CanFrom->getTypeClass()) return false;
1466     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1467       return false;
1468   }
1469 
1470   const auto *FromFn = cast<FunctionType>(CanFrom);
1471   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1472 
1473   const auto *ToFn = cast<FunctionType>(CanTo);
1474   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1475 
1476   bool Changed = false;
1477 
1478   // Drop 'noreturn' if not present in target type.
1479   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1480     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1481     Changed = true;
1482   }
1483 
1484   // Drop 'noexcept' if not present in target type.
1485   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1486     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1487     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1488       FromFn = cast<FunctionType>(
1489           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1490                                                    EST_None)
1491                  .getTypePtr());
1492       Changed = true;
1493     }
1494 
1495     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1496     // only if the ExtParameterInfo lists of the two function prototypes can be
1497     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1498     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1499     bool CanUseToFPT, CanUseFromFPT;
1500     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1501                                       CanUseFromFPT, NewParamInfos) &&
1502         CanUseToFPT && !CanUseFromFPT) {
1503       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1504       ExtInfo.ExtParameterInfos =
1505           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1506       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1507                                             FromFPT->getParamTypes(), ExtInfo);
1508       FromFn = QT->getAs<FunctionType>();
1509       Changed = true;
1510     }
1511   }
1512 
1513   if (!Changed)
1514     return false;
1515 
1516   assert(QualType(FromFn, 0).isCanonical());
1517   if (QualType(FromFn, 0) != CanTo) return false;
1518 
1519   ResultTy = ToType;
1520   return true;
1521 }
1522 
1523 /// Determine whether the conversion from FromType to ToType is a valid
1524 /// vector conversion.
1525 ///
1526 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1527 /// conversion.
1528 static bool IsVectorConversion(Sema &S, QualType FromType,
1529                                QualType ToType, ImplicitConversionKind &ICK) {
1530   // We need at least one of these types to be a vector type to have a vector
1531   // conversion.
1532   if (!ToType->isVectorType() && !FromType->isVectorType())
1533     return false;
1534 
1535   // Identical types require no conversions.
1536   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1537     return false;
1538 
1539   // There are no conversions between extended vector types, only identity.
1540   if (ToType->isExtVectorType()) {
1541     // There are no conversions between extended vector types other than the
1542     // identity conversion.
1543     if (FromType->isExtVectorType())
1544       return false;
1545 
1546     // Vector splat from any arithmetic type to a vector.
1547     if (FromType->isArithmeticType()) {
1548       ICK = ICK_Vector_Splat;
1549       return true;
1550     }
1551   }
1552 
1553   // We can perform the conversion between vector types in the following cases:
1554   // 1)vector types are equivalent AltiVec and GCC vector types
1555   // 2)lax vector conversions are permitted and the vector types are of the
1556   //   same size
1557   if (ToType->isVectorType() && FromType->isVectorType()) {
1558     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1559         S.isLaxVectorConversion(FromType, ToType)) {
1560       ICK = ICK_Vector_Conversion;
1561       return true;
1562     }
1563   }
1564 
1565   return false;
1566 }
1567 
1568 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1569                                 bool InOverloadResolution,
1570                                 StandardConversionSequence &SCS,
1571                                 bool CStyle);
1572 
1573 /// IsStandardConversion - Determines whether there is a standard
1574 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1575 /// expression From to the type ToType. Standard conversion sequences
1576 /// only consider non-class types; for conversions that involve class
1577 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1578 /// contain the standard conversion sequence required to perform this
1579 /// conversion and this routine will return true. Otherwise, this
1580 /// routine will return false and the value of SCS is unspecified.
1581 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1582                                  bool InOverloadResolution,
1583                                  StandardConversionSequence &SCS,
1584                                  bool CStyle,
1585                                  bool AllowObjCWritebackConversion) {
1586   QualType FromType = From->getType();
1587 
1588   // Standard conversions (C++ [conv])
1589   SCS.setAsIdentityConversion();
1590   SCS.IncompatibleObjC = false;
1591   SCS.setFromType(FromType);
1592   SCS.CopyConstructor = nullptr;
1593 
1594   // There are no standard conversions for class types in C++, so
1595   // abort early. When overloading in C, however, we do permit them.
1596   if (S.getLangOpts().CPlusPlus &&
1597       (FromType->isRecordType() || ToType->isRecordType()))
1598     return false;
1599 
1600   // The first conversion can be an lvalue-to-rvalue conversion,
1601   // array-to-pointer conversion, or function-to-pointer conversion
1602   // (C++ 4p1).
1603 
1604   if (FromType == S.Context.OverloadTy) {
1605     DeclAccessPair AccessPair;
1606     if (FunctionDecl *Fn
1607           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1608                                                  AccessPair)) {
1609       // We were able to resolve the address of the overloaded function,
1610       // so we can convert to the type of that function.
1611       FromType = Fn->getType();
1612       SCS.setFromType(FromType);
1613 
1614       // we can sometimes resolve &foo<int> regardless of ToType, so check
1615       // if the type matches (identity) or we are converting to bool
1616       if (!S.Context.hasSameUnqualifiedType(
1617                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1618         QualType resultTy;
1619         // if the function type matches except for [[noreturn]], it's ok
1620         if (!S.IsFunctionConversion(FromType,
1621               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1622           // otherwise, only a boolean conversion is standard
1623           if (!ToType->isBooleanType())
1624             return false;
1625       }
1626 
1627       // Check if the "from" expression is taking the address of an overloaded
1628       // function and recompute the FromType accordingly. Take advantage of the
1629       // fact that non-static member functions *must* have such an address-of
1630       // expression.
1631       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1632       if (Method && !Method->isStatic()) {
1633         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1634                "Non-unary operator on non-static member address");
1635         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1636                == UO_AddrOf &&
1637                "Non-address-of operator on non-static member address");
1638         const Type *ClassType
1639           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1640         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1641       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1642         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1643                UO_AddrOf &&
1644                "Non-address-of operator for overloaded function expression");
1645         FromType = S.Context.getPointerType(FromType);
1646       }
1647 
1648       // Check that we've computed the proper type after overload resolution.
1649       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1650       // be calling it from within an NDEBUG block.
1651       assert(S.Context.hasSameType(
1652         FromType,
1653         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1654     } else {
1655       return false;
1656     }
1657   }
1658   // Lvalue-to-rvalue conversion (C++11 4.1):
1659   //   A glvalue (3.10) of a non-function, non-array type T can
1660   //   be converted to a prvalue.
1661   bool argIsLValue = From->isGLValue();
1662   if (argIsLValue &&
1663       !FromType->isFunctionType() && !FromType->isArrayType() &&
1664       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1665     SCS.First = ICK_Lvalue_To_Rvalue;
1666 
1667     // C11 6.3.2.1p2:
1668     //   ... if the lvalue has atomic type, the value has the non-atomic version
1669     //   of the type of the lvalue ...
1670     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1671       FromType = Atomic->getValueType();
1672 
1673     // If T is a non-class type, the type of the rvalue is the
1674     // cv-unqualified version of T. Otherwise, the type of the rvalue
1675     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1676     // just strip the qualifiers because they don't matter.
1677     FromType = FromType.getUnqualifiedType();
1678   } else if (FromType->isArrayType()) {
1679     // Array-to-pointer conversion (C++ 4.2)
1680     SCS.First = ICK_Array_To_Pointer;
1681 
1682     // An lvalue or rvalue of type "array of N T" or "array of unknown
1683     // bound of T" can be converted to an rvalue of type "pointer to
1684     // T" (C++ 4.2p1).
1685     FromType = S.Context.getArrayDecayedType(FromType);
1686 
1687     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1688       // This conversion is deprecated in C++03 (D.4)
1689       SCS.DeprecatedStringLiteralToCharPtr = true;
1690 
1691       // For the purpose of ranking in overload resolution
1692       // (13.3.3.1.1), this conversion is considered an
1693       // array-to-pointer conversion followed by a qualification
1694       // conversion (4.4). (C++ 4.2p2)
1695       SCS.Second = ICK_Identity;
1696       SCS.Third = ICK_Qualification;
1697       SCS.QualificationIncludesObjCLifetime = false;
1698       SCS.setAllToTypes(FromType);
1699       return true;
1700     }
1701   } else if (FromType->isFunctionType() && argIsLValue) {
1702     // Function-to-pointer conversion (C++ 4.3).
1703     SCS.First = ICK_Function_To_Pointer;
1704 
1705     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1706       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1707         if (!S.checkAddressOfFunctionIsAvailable(FD))
1708           return false;
1709 
1710     // An lvalue of function type T can be converted to an rvalue of
1711     // type "pointer to T." The result is a pointer to the
1712     // function. (C++ 4.3p1).
1713     FromType = S.Context.getPointerType(FromType);
1714   } else {
1715     // We don't require any conversions for the first step.
1716     SCS.First = ICK_Identity;
1717   }
1718   SCS.setToType(0, FromType);
1719 
1720   // The second conversion can be an integral promotion, floating
1721   // point promotion, integral conversion, floating point conversion,
1722   // floating-integral conversion, pointer conversion,
1723   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1724   // For overloading in C, this can also be a "compatible-type"
1725   // conversion.
1726   bool IncompatibleObjC = false;
1727   ImplicitConversionKind SecondICK = ICK_Identity;
1728   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1729     // The unqualified versions of the types are the same: there's no
1730     // conversion to do.
1731     SCS.Second = ICK_Identity;
1732   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1733     // Integral promotion (C++ 4.5).
1734     SCS.Second = ICK_Integral_Promotion;
1735     FromType = ToType.getUnqualifiedType();
1736   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1737     // Floating point promotion (C++ 4.6).
1738     SCS.Second = ICK_Floating_Promotion;
1739     FromType = ToType.getUnqualifiedType();
1740   } else if (S.IsComplexPromotion(FromType, ToType)) {
1741     // Complex promotion (Clang extension)
1742     SCS.Second = ICK_Complex_Promotion;
1743     FromType = ToType.getUnqualifiedType();
1744   } else if (ToType->isBooleanType() &&
1745              (FromType->isArithmeticType() ||
1746               FromType->isAnyPointerType() ||
1747               FromType->isBlockPointerType() ||
1748               FromType->isMemberPointerType() ||
1749               FromType->isNullPtrType())) {
1750     // Boolean conversions (C++ 4.12).
1751     SCS.Second = ICK_Boolean_Conversion;
1752     FromType = S.Context.BoolTy;
1753   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1754              ToType->isIntegralType(S.Context)) {
1755     // Integral conversions (C++ 4.7).
1756     SCS.Second = ICK_Integral_Conversion;
1757     FromType = ToType.getUnqualifiedType();
1758   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1759     // Complex conversions (C99 6.3.1.6)
1760     SCS.Second = ICK_Complex_Conversion;
1761     FromType = ToType.getUnqualifiedType();
1762   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1763              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1764     // Complex-real conversions (C99 6.3.1.7)
1765     SCS.Second = ICK_Complex_Real;
1766     FromType = ToType.getUnqualifiedType();
1767   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1768     // FIXME: disable conversions between long double and __float128 if
1769     // their representation is different until there is back end support
1770     // We of course allow this conversion if long double is really double.
1771     if (&S.Context.getFloatTypeSemantics(FromType) !=
1772         &S.Context.getFloatTypeSemantics(ToType)) {
1773       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1774                                     ToType == S.Context.LongDoubleTy) ||
1775                                    (FromType == S.Context.LongDoubleTy &&
1776                                     ToType == S.Context.Float128Ty));
1777       if (Float128AndLongDouble &&
1778           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1779            &llvm::APFloat::PPCDoubleDouble()))
1780         return false;
1781     }
1782     // Floating point conversions (C++ 4.8).
1783     SCS.Second = ICK_Floating_Conversion;
1784     FromType = ToType.getUnqualifiedType();
1785   } else if ((FromType->isRealFloatingType() &&
1786               ToType->isIntegralType(S.Context)) ||
1787              (FromType->isIntegralOrUnscopedEnumerationType() &&
1788               ToType->isRealFloatingType())) {
1789     // Floating-integral conversions (C++ 4.9).
1790     SCS.Second = ICK_Floating_Integral;
1791     FromType = ToType.getUnqualifiedType();
1792   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1793     SCS.Second = ICK_Block_Pointer_Conversion;
1794   } else if (AllowObjCWritebackConversion &&
1795              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1796     SCS.Second = ICK_Writeback_Conversion;
1797   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1798                                    FromType, IncompatibleObjC)) {
1799     // Pointer conversions (C++ 4.10).
1800     SCS.Second = ICK_Pointer_Conversion;
1801     SCS.IncompatibleObjC = IncompatibleObjC;
1802     FromType = FromType.getUnqualifiedType();
1803   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1804                                          InOverloadResolution, FromType)) {
1805     // Pointer to member conversions (4.11).
1806     SCS.Second = ICK_Pointer_Member;
1807   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1808     SCS.Second = SecondICK;
1809     FromType = ToType.getUnqualifiedType();
1810   } else if (!S.getLangOpts().CPlusPlus &&
1811              S.Context.typesAreCompatible(ToType, FromType)) {
1812     // Compatible conversions (Clang extension for C function overloading)
1813     SCS.Second = ICK_Compatible_Conversion;
1814     FromType = ToType.getUnqualifiedType();
1815   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1816                                              InOverloadResolution,
1817                                              SCS, CStyle)) {
1818     SCS.Second = ICK_TransparentUnionConversion;
1819     FromType = ToType;
1820   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1821                                  CStyle)) {
1822     // tryAtomicConversion has updated the standard conversion sequence
1823     // appropriately.
1824     return true;
1825   } else if (ToType->isEventT() &&
1826              From->isIntegerConstantExpr(S.getASTContext()) &&
1827              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1828     SCS.Second = ICK_Zero_Event_Conversion;
1829     FromType = ToType;
1830   } else if (ToType->isQueueT() &&
1831              From->isIntegerConstantExpr(S.getASTContext()) &&
1832              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1833     SCS.Second = ICK_Zero_Queue_Conversion;
1834     FromType = ToType;
1835   } else {
1836     // No second conversion required.
1837     SCS.Second = ICK_Identity;
1838   }
1839   SCS.setToType(1, FromType);
1840 
1841   // The third conversion can be a function pointer conversion or a
1842   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1843   bool ObjCLifetimeConversion;
1844   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1845     // Function pointer conversions (removing 'noexcept') including removal of
1846     // 'noreturn' (Clang extension).
1847     SCS.Third = ICK_Function_Conversion;
1848   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1849                                          ObjCLifetimeConversion)) {
1850     SCS.Third = ICK_Qualification;
1851     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1852     FromType = ToType;
1853   } else {
1854     // No conversion required
1855     SCS.Third = ICK_Identity;
1856   }
1857 
1858   // C++ [over.best.ics]p6:
1859   //   [...] Any difference in top-level cv-qualification is
1860   //   subsumed by the initialization itself and does not constitute
1861   //   a conversion. [...]
1862   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1863   QualType CanonTo = S.Context.getCanonicalType(ToType);
1864   if (CanonFrom.getLocalUnqualifiedType()
1865                                      == CanonTo.getLocalUnqualifiedType() &&
1866       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1867     FromType = ToType;
1868     CanonFrom = CanonTo;
1869   }
1870 
1871   SCS.setToType(2, FromType);
1872 
1873   if (CanonFrom == CanonTo)
1874     return true;
1875 
1876   // If we have not converted the argument type to the parameter type,
1877   // this is a bad conversion sequence, unless we're resolving an overload in C.
1878   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1879     return false;
1880 
1881   ExprResult ER = ExprResult{From};
1882   Sema::AssignConvertType Conv =
1883       S.CheckSingleAssignmentConstraints(ToType, ER,
1884                                          /*Diagnose=*/false,
1885                                          /*DiagnoseCFAudited=*/false,
1886                                          /*ConvertRHS=*/false);
1887   ImplicitConversionKind SecondConv;
1888   switch (Conv) {
1889   case Sema::Compatible:
1890     SecondConv = ICK_C_Only_Conversion;
1891     break;
1892   // For our purposes, discarding qualifiers is just as bad as using an
1893   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1894   // qualifiers, as well.
1895   case Sema::CompatiblePointerDiscardsQualifiers:
1896   case Sema::IncompatiblePointer:
1897   case Sema::IncompatiblePointerSign:
1898     SecondConv = ICK_Incompatible_Pointer_Conversion;
1899     break;
1900   default:
1901     return false;
1902   }
1903 
1904   // First can only be an lvalue conversion, so we pretend that this was the
1905   // second conversion. First should already be valid from earlier in the
1906   // function.
1907   SCS.Second = SecondConv;
1908   SCS.setToType(1, ToType);
1909 
1910   // Third is Identity, because Second should rank us worse than any other
1911   // conversion. This could also be ICK_Qualification, but it's simpler to just
1912   // lump everything in with the second conversion, and we don't gain anything
1913   // from making this ICK_Qualification.
1914   SCS.Third = ICK_Identity;
1915   SCS.setToType(2, ToType);
1916   return true;
1917 }
1918 
1919 static bool
1920 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1921                                      QualType &ToType,
1922                                      bool InOverloadResolution,
1923                                      StandardConversionSequence &SCS,
1924                                      bool CStyle) {
1925 
1926   const RecordType *UT = ToType->getAsUnionType();
1927   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1928     return false;
1929   // The field to initialize within the transparent union.
1930   RecordDecl *UD = UT->getDecl();
1931   // It's compatible if the expression matches any of the fields.
1932   for (const auto *it : UD->fields()) {
1933     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1934                              CStyle, /*ObjCWritebackConversion=*/false)) {
1935       ToType = it->getType();
1936       return true;
1937     }
1938   }
1939   return false;
1940 }
1941 
1942 /// IsIntegralPromotion - Determines whether the conversion from the
1943 /// expression From (whose potentially-adjusted type is FromType) to
1944 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1945 /// sets PromotedType to the promoted type.
1946 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1947   const BuiltinType *To = ToType->getAs<BuiltinType>();
1948   // All integers are built-in.
1949   if (!To) {
1950     return false;
1951   }
1952 
1953   // An rvalue of type char, signed char, unsigned char, short int, or
1954   // unsigned short int can be converted to an rvalue of type int if
1955   // int can represent all the values of the source type; otherwise,
1956   // the source rvalue can be converted to an rvalue of type unsigned
1957   // int (C++ 4.5p1).
1958   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1959       !FromType->isEnumeralType()) {
1960     if (// We can promote any signed, promotable integer type to an int
1961         (FromType->isSignedIntegerType() ||
1962          // We can promote any unsigned integer type whose size is
1963          // less than int to an int.
1964          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1965       return To->getKind() == BuiltinType::Int;
1966     }
1967 
1968     return To->getKind() == BuiltinType::UInt;
1969   }
1970 
1971   // C++11 [conv.prom]p3:
1972   //   A prvalue of an unscoped enumeration type whose underlying type is not
1973   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1974   //   following types that can represent all the values of the enumeration
1975   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1976   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1977   //   long long int. If none of the types in that list can represent all the
1978   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1979   //   type can be converted to an rvalue a prvalue of the extended integer type
1980   //   with lowest integer conversion rank (4.13) greater than the rank of long
1981   //   long in which all the values of the enumeration can be represented. If
1982   //   there are two such extended types, the signed one is chosen.
1983   // C++11 [conv.prom]p4:
1984   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1985   //   can be converted to a prvalue of its underlying type. Moreover, if
1986   //   integral promotion can be applied to its underlying type, a prvalue of an
1987   //   unscoped enumeration type whose underlying type is fixed can also be
1988   //   converted to a prvalue of the promoted underlying type.
1989   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1990     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1991     // provided for a scoped enumeration.
1992     if (FromEnumType->getDecl()->isScoped())
1993       return false;
1994 
1995     // We can perform an integral promotion to the underlying type of the enum,
1996     // even if that's not the promoted type. Note that the check for promoting
1997     // the underlying type is based on the type alone, and does not consider
1998     // the bitfield-ness of the actual source expression.
1999     if (FromEnumType->getDecl()->isFixed()) {
2000       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2001       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2002              IsIntegralPromotion(nullptr, Underlying, ToType);
2003     }
2004 
2005     // We have already pre-calculated the promotion type, so this is trivial.
2006     if (ToType->isIntegerType() &&
2007         isCompleteType(From->getLocStart(), FromType))
2008       return Context.hasSameUnqualifiedType(
2009           ToType, FromEnumType->getDecl()->getPromotionType());
2010 
2011     // C++ [conv.prom]p5:
2012     //   If the bit-field has an enumerated type, it is treated as any other
2013     //   value of that type for promotion purposes.
2014     //
2015     // ... so do not fall through into the bit-field checks below in C++.
2016     if (getLangOpts().CPlusPlus)
2017       return false;
2018   }
2019 
2020   // C++0x [conv.prom]p2:
2021   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2022   //   to an rvalue a prvalue of the first of the following types that can
2023   //   represent all the values of its underlying type: int, unsigned int,
2024   //   long int, unsigned long int, long long int, or unsigned long long int.
2025   //   If none of the types in that list can represent all the values of its
2026   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2027   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2028   //   type.
2029   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2030       ToType->isIntegerType()) {
2031     // Determine whether the type we're converting from is signed or
2032     // unsigned.
2033     bool FromIsSigned = FromType->isSignedIntegerType();
2034     uint64_t FromSize = Context.getTypeSize(FromType);
2035 
2036     // The types we'll try to promote to, in the appropriate
2037     // order. Try each of these types.
2038     QualType PromoteTypes[6] = {
2039       Context.IntTy, Context.UnsignedIntTy,
2040       Context.LongTy, Context.UnsignedLongTy ,
2041       Context.LongLongTy, Context.UnsignedLongLongTy
2042     };
2043     for (int Idx = 0; Idx < 6; ++Idx) {
2044       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2045       if (FromSize < ToSize ||
2046           (FromSize == ToSize &&
2047            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2048         // We found the type that we can promote to. If this is the
2049         // type we wanted, we have a promotion. Otherwise, no
2050         // promotion.
2051         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2052       }
2053     }
2054   }
2055 
2056   // An rvalue for an integral bit-field (9.6) can be converted to an
2057   // rvalue of type int if int can represent all the values of the
2058   // bit-field; otherwise, it can be converted to unsigned int if
2059   // unsigned int can represent all the values of the bit-field. If
2060   // the bit-field is larger yet, no integral promotion applies to
2061   // it. If the bit-field has an enumerated type, it is treated as any
2062   // other value of that type for promotion purposes (C++ 4.5p3).
2063   // FIXME: We should delay checking of bit-fields until we actually perform the
2064   // conversion.
2065   //
2066   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2067   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2068   // bit-fields and those whose underlying type is larger than int) for GCC
2069   // compatibility.
2070   if (From) {
2071     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2072       llvm::APSInt BitWidth;
2073       if (FromType->isIntegralType(Context) &&
2074           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2075         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2076         ToSize = Context.getTypeSize(ToType);
2077 
2078         // Are we promoting to an int from a bitfield that fits in an int?
2079         if (BitWidth < ToSize ||
2080             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2081           return To->getKind() == BuiltinType::Int;
2082         }
2083 
2084         // Are we promoting to an unsigned int from an unsigned bitfield
2085         // that fits into an unsigned int?
2086         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2087           return To->getKind() == BuiltinType::UInt;
2088         }
2089 
2090         return false;
2091       }
2092     }
2093   }
2094 
2095   // An rvalue of type bool can be converted to an rvalue of type int,
2096   // with false becoming zero and true becoming one (C++ 4.5p4).
2097   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2098     return true;
2099   }
2100 
2101   return false;
2102 }
2103 
2104 /// IsFloatingPointPromotion - Determines whether the conversion from
2105 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2106 /// returns true and sets PromotedType to the promoted type.
2107 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2108   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2109     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2110       /// An rvalue of type float can be converted to an rvalue of type
2111       /// double. (C++ 4.6p1).
2112       if (FromBuiltin->getKind() == BuiltinType::Float &&
2113           ToBuiltin->getKind() == BuiltinType::Double)
2114         return true;
2115 
2116       // C99 6.3.1.5p1:
2117       //   When a float is promoted to double or long double, or a
2118       //   double is promoted to long double [...].
2119       if (!getLangOpts().CPlusPlus &&
2120           (FromBuiltin->getKind() == BuiltinType::Float ||
2121            FromBuiltin->getKind() == BuiltinType::Double) &&
2122           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2123            ToBuiltin->getKind() == BuiltinType::Float128))
2124         return true;
2125 
2126       // Half can be promoted to float.
2127       if (!getLangOpts().NativeHalfType &&
2128            FromBuiltin->getKind() == BuiltinType::Half &&
2129           ToBuiltin->getKind() == BuiltinType::Float)
2130         return true;
2131     }
2132 
2133   return false;
2134 }
2135 
2136 /// Determine if a conversion is a complex promotion.
2137 ///
2138 /// A complex promotion is defined as a complex -> complex conversion
2139 /// where the conversion between the underlying real types is a
2140 /// floating-point or integral promotion.
2141 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2142   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2143   if (!FromComplex)
2144     return false;
2145 
2146   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2147   if (!ToComplex)
2148     return false;
2149 
2150   return IsFloatingPointPromotion(FromComplex->getElementType(),
2151                                   ToComplex->getElementType()) ||
2152     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2153                         ToComplex->getElementType());
2154 }
2155 
2156 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2157 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2158 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2159 /// if non-empty, will be a pointer to ToType that may or may not have
2160 /// the right set of qualifiers on its pointee.
2161 ///
2162 static QualType
2163 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2164                                    QualType ToPointee, QualType ToType,
2165                                    ASTContext &Context,
2166                                    bool StripObjCLifetime = false) {
2167   assert((FromPtr->getTypeClass() == Type::Pointer ||
2168           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2169          "Invalid similarly-qualified pointer type");
2170 
2171   /// Conversions to 'id' subsume cv-qualifier conversions.
2172   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2173     return ToType.getUnqualifiedType();
2174 
2175   QualType CanonFromPointee
2176     = Context.getCanonicalType(FromPtr->getPointeeType());
2177   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2178   Qualifiers Quals = CanonFromPointee.getQualifiers();
2179 
2180   if (StripObjCLifetime)
2181     Quals.removeObjCLifetime();
2182 
2183   // Exact qualifier match -> return the pointer type we're converting to.
2184   if (CanonToPointee.getLocalQualifiers() == Quals) {
2185     // ToType is exactly what we need. Return it.
2186     if (!ToType.isNull())
2187       return ToType.getUnqualifiedType();
2188 
2189     // Build a pointer to ToPointee. It has the right qualifiers
2190     // already.
2191     if (isa<ObjCObjectPointerType>(ToType))
2192       return Context.getObjCObjectPointerType(ToPointee);
2193     return Context.getPointerType(ToPointee);
2194   }
2195 
2196   // Just build a canonical type that has the right qualifiers.
2197   QualType QualifiedCanonToPointee
2198     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2199 
2200   if (isa<ObjCObjectPointerType>(ToType))
2201     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2202   return Context.getPointerType(QualifiedCanonToPointee);
2203 }
2204 
2205 static bool isNullPointerConstantForConversion(Expr *Expr,
2206                                                bool InOverloadResolution,
2207                                                ASTContext &Context) {
2208   // Handle value-dependent integral null pointer constants correctly.
2209   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2210   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2211       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2212     return !InOverloadResolution;
2213 
2214   return Expr->isNullPointerConstant(Context,
2215                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2216                                         : Expr::NPC_ValueDependentIsNull);
2217 }
2218 
2219 /// IsPointerConversion - Determines whether the conversion of the
2220 /// expression From, which has the (possibly adjusted) type FromType,
2221 /// can be converted to the type ToType via a pointer conversion (C++
2222 /// 4.10). If so, returns true and places the converted type (that
2223 /// might differ from ToType in its cv-qualifiers at some level) into
2224 /// ConvertedType.
2225 ///
2226 /// This routine also supports conversions to and from block pointers
2227 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2228 /// pointers to interfaces. FIXME: Once we've determined the
2229 /// appropriate overloading rules for Objective-C, we may want to
2230 /// split the Objective-C checks into a different routine; however,
2231 /// GCC seems to consider all of these conversions to be pointer
2232 /// conversions, so for now they live here. IncompatibleObjC will be
2233 /// set if the conversion is an allowed Objective-C conversion that
2234 /// should result in a warning.
2235 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2236                                bool InOverloadResolution,
2237                                QualType& ConvertedType,
2238                                bool &IncompatibleObjC) {
2239   IncompatibleObjC = false;
2240   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2241                               IncompatibleObjC))
2242     return true;
2243 
2244   // Conversion from a null pointer constant to any Objective-C pointer type.
2245   if (ToType->isObjCObjectPointerType() &&
2246       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247     ConvertedType = ToType;
2248     return true;
2249   }
2250 
2251   // Blocks: Block pointers can be converted to void*.
2252   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2253       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2254     ConvertedType = ToType;
2255     return true;
2256   }
2257   // Blocks: A null pointer constant can be converted to a block
2258   // pointer type.
2259   if (ToType->isBlockPointerType() &&
2260       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2261     ConvertedType = ToType;
2262     return true;
2263   }
2264 
2265   // If the left-hand-side is nullptr_t, the right side can be a null
2266   // pointer constant.
2267   if (ToType->isNullPtrType() &&
2268       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2269     ConvertedType = ToType;
2270     return true;
2271   }
2272 
2273   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2274   if (!ToTypePtr)
2275     return false;
2276 
2277   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2278   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2279     ConvertedType = ToType;
2280     return true;
2281   }
2282 
2283   // Beyond this point, both types need to be pointers
2284   // , including objective-c pointers.
2285   QualType ToPointeeType = ToTypePtr->getPointeeType();
2286   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2287       !getLangOpts().ObjCAutoRefCount) {
2288     ConvertedType = BuildSimilarlyQualifiedPointerType(
2289                                       FromType->getAs<ObjCObjectPointerType>(),
2290                                                        ToPointeeType,
2291                                                        ToType, Context);
2292     return true;
2293   }
2294   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2295   if (!FromTypePtr)
2296     return false;
2297 
2298   QualType FromPointeeType = FromTypePtr->getPointeeType();
2299 
2300   // If the unqualified pointee types are the same, this can't be a
2301   // pointer conversion, so don't do all of the work below.
2302   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2303     return false;
2304 
2305   // An rvalue of type "pointer to cv T," where T is an object type,
2306   // can be converted to an rvalue of type "pointer to cv void" (C++
2307   // 4.10p2).
2308   if (FromPointeeType->isIncompleteOrObjectType() &&
2309       ToPointeeType->isVoidType()) {
2310     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2311                                                        ToPointeeType,
2312                                                        ToType, Context,
2313                                                    /*StripObjCLifetime=*/true);
2314     return true;
2315   }
2316 
2317   // MSVC allows implicit function to void* type conversion.
2318   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2319       ToPointeeType->isVoidType()) {
2320     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2321                                                        ToPointeeType,
2322                                                        ToType, Context);
2323     return true;
2324   }
2325 
2326   // When we're overloading in C, we allow a special kind of pointer
2327   // conversion for compatible-but-not-identical pointee types.
2328   if (!getLangOpts().CPlusPlus &&
2329       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2330     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331                                                        ToPointeeType,
2332                                                        ToType, Context);
2333     return true;
2334   }
2335 
2336   // C++ [conv.ptr]p3:
2337   //
2338   //   An rvalue of type "pointer to cv D," where D is a class type,
2339   //   can be converted to an rvalue of type "pointer to cv B," where
2340   //   B is a base class (clause 10) of D. If B is an inaccessible
2341   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2342   //   necessitates this conversion is ill-formed. The result of the
2343   //   conversion is a pointer to the base class sub-object of the
2344   //   derived class object. The null pointer value is converted to
2345   //   the null pointer value of the destination type.
2346   //
2347   // Note that we do not check for ambiguity or inaccessibility
2348   // here. That is handled by CheckPointerConversion.
2349   if (getLangOpts().CPlusPlus &&
2350       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2351       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2352       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2353     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354                                                        ToPointeeType,
2355                                                        ToType, Context);
2356     return true;
2357   }
2358 
2359   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2360       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2361     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2362                                                        ToPointeeType,
2363                                                        ToType, Context);
2364     return true;
2365   }
2366 
2367   return false;
2368 }
2369 
2370 /// Adopt the given qualifiers for the given type.
2371 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2372   Qualifiers TQs = T.getQualifiers();
2373 
2374   // Check whether qualifiers already match.
2375   if (TQs == Qs)
2376     return T;
2377 
2378   if (Qs.compatiblyIncludes(TQs))
2379     return Context.getQualifiedType(T, Qs);
2380 
2381   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2382 }
2383 
2384 /// isObjCPointerConversion - Determines whether this is an
2385 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2386 /// with the same arguments and return values.
2387 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2388                                    QualType& ConvertedType,
2389                                    bool &IncompatibleObjC) {
2390   if (!getLangOpts().ObjC1)
2391     return false;
2392 
2393   // The set of qualifiers on the type we're converting from.
2394   Qualifiers FromQualifiers = FromType.getQualifiers();
2395 
2396   // First, we handle all conversions on ObjC object pointer types.
2397   const ObjCObjectPointerType* ToObjCPtr =
2398     ToType->getAs<ObjCObjectPointerType>();
2399   const ObjCObjectPointerType *FromObjCPtr =
2400     FromType->getAs<ObjCObjectPointerType>();
2401 
2402   if (ToObjCPtr && FromObjCPtr) {
2403     // If the pointee types are the same (ignoring qualifications),
2404     // then this is not a pointer conversion.
2405     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2406                                        FromObjCPtr->getPointeeType()))
2407       return false;
2408 
2409     // Conversion between Objective-C pointers.
2410     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2411       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2412       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2413       if (getLangOpts().CPlusPlus && LHS && RHS &&
2414           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2415                                                 FromObjCPtr->getPointeeType()))
2416         return false;
2417       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2418                                                    ToObjCPtr->getPointeeType(),
2419                                                          ToType, Context);
2420       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2421       return true;
2422     }
2423 
2424     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2425       // Okay: this is some kind of implicit downcast of Objective-C
2426       // interfaces, which is permitted. However, we're going to
2427       // complain about it.
2428       IncompatibleObjC = true;
2429       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2430                                                    ToObjCPtr->getPointeeType(),
2431                                                          ToType, Context);
2432       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2433       return true;
2434     }
2435   }
2436   // Beyond this point, both types need to be C pointers or block pointers.
2437   QualType ToPointeeType;
2438   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2439     ToPointeeType = ToCPtr->getPointeeType();
2440   else if (const BlockPointerType *ToBlockPtr =
2441             ToType->getAs<BlockPointerType>()) {
2442     // Objective C++: We're able to convert from a pointer to any object
2443     // to a block pointer type.
2444     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2445       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2446       return true;
2447     }
2448     ToPointeeType = ToBlockPtr->getPointeeType();
2449   }
2450   else if (FromType->getAs<BlockPointerType>() &&
2451            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2452     // Objective C++: We're able to convert from a block pointer type to a
2453     // pointer to any object.
2454     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2455     return true;
2456   }
2457   else
2458     return false;
2459 
2460   QualType FromPointeeType;
2461   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2462     FromPointeeType = FromCPtr->getPointeeType();
2463   else if (const BlockPointerType *FromBlockPtr =
2464            FromType->getAs<BlockPointerType>())
2465     FromPointeeType = FromBlockPtr->getPointeeType();
2466   else
2467     return false;
2468 
2469   // If we have pointers to pointers, recursively check whether this
2470   // is an Objective-C conversion.
2471   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2472       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2473                               IncompatibleObjC)) {
2474     // We always complain about this conversion.
2475     IncompatibleObjC = true;
2476     ConvertedType = Context.getPointerType(ConvertedType);
2477     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2478     return true;
2479   }
2480   // Allow conversion of pointee being objective-c pointer to another one;
2481   // as in I* to id.
2482   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2483       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2484       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2485                               IncompatibleObjC)) {
2486 
2487     ConvertedType = Context.getPointerType(ConvertedType);
2488     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2489     return true;
2490   }
2491 
2492   // If we have pointers to functions or blocks, check whether the only
2493   // differences in the argument and result types are in Objective-C
2494   // pointer conversions. If so, we permit the conversion (but
2495   // complain about it).
2496   const FunctionProtoType *FromFunctionType
2497     = FromPointeeType->getAs<FunctionProtoType>();
2498   const FunctionProtoType *ToFunctionType
2499     = ToPointeeType->getAs<FunctionProtoType>();
2500   if (FromFunctionType && ToFunctionType) {
2501     // If the function types are exactly the same, this isn't an
2502     // Objective-C pointer conversion.
2503     if (Context.getCanonicalType(FromPointeeType)
2504           == Context.getCanonicalType(ToPointeeType))
2505       return false;
2506 
2507     // Perform the quick checks that will tell us whether these
2508     // function types are obviously different.
2509     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2510         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2511         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2512       return false;
2513 
2514     bool HasObjCConversion = false;
2515     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2516         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2517       // Okay, the types match exactly. Nothing to do.
2518     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2519                                        ToFunctionType->getReturnType(),
2520                                        ConvertedType, IncompatibleObjC)) {
2521       // Okay, we have an Objective-C pointer conversion.
2522       HasObjCConversion = true;
2523     } else {
2524       // Function types are too different. Abort.
2525       return false;
2526     }
2527 
2528     // Check argument types.
2529     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2530          ArgIdx != NumArgs; ++ArgIdx) {
2531       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2532       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2533       if (Context.getCanonicalType(FromArgType)
2534             == Context.getCanonicalType(ToArgType)) {
2535         // Okay, the types match exactly. Nothing to do.
2536       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2537                                          ConvertedType, IncompatibleObjC)) {
2538         // Okay, we have an Objective-C pointer conversion.
2539         HasObjCConversion = true;
2540       } else {
2541         // Argument types are too different. Abort.
2542         return false;
2543       }
2544     }
2545 
2546     if (HasObjCConversion) {
2547       // We had an Objective-C conversion. Allow this pointer
2548       // conversion, but complain about it.
2549       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2550       IncompatibleObjC = true;
2551       return true;
2552     }
2553   }
2554 
2555   return false;
2556 }
2557 
2558 /// Determine whether this is an Objective-C writeback conversion,
2559 /// used for parameter passing when performing automatic reference counting.
2560 ///
2561 /// \param FromType The type we're converting form.
2562 ///
2563 /// \param ToType The type we're converting to.
2564 ///
2565 /// \param ConvertedType The type that will be produced after applying
2566 /// this conversion.
2567 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2568                                      QualType &ConvertedType) {
2569   if (!getLangOpts().ObjCAutoRefCount ||
2570       Context.hasSameUnqualifiedType(FromType, ToType))
2571     return false;
2572 
2573   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2574   QualType ToPointee;
2575   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2576     ToPointee = ToPointer->getPointeeType();
2577   else
2578     return false;
2579 
2580   Qualifiers ToQuals = ToPointee.getQualifiers();
2581   if (!ToPointee->isObjCLifetimeType() ||
2582       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2583       !ToQuals.withoutObjCLifetime().empty())
2584     return false;
2585 
2586   // Argument must be a pointer to __strong to __weak.
2587   QualType FromPointee;
2588   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2589     FromPointee = FromPointer->getPointeeType();
2590   else
2591     return false;
2592 
2593   Qualifiers FromQuals = FromPointee.getQualifiers();
2594   if (!FromPointee->isObjCLifetimeType() ||
2595       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2596        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2597     return false;
2598 
2599   // Make sure that we have compatible qualifiers.
2600   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2601   if (!ToQuals.compatiblyIncludes(FromQuals))
2602     return false;
2603 
2604   // Remove qualifiers from the pointee type we're converting from; they
2605   // aren't used in the compatibility check belong, and we'll be adding back
2606   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2607   FromPointee = FromPointee.getUnqualifiedType();
2608 
2609   // The unqualified form of the pointee types must be compatible.
2610   ToPointee = ToPointee.getUnqualifiedType();
2611   bool IncompatibleObjC;
2612   if (Context.typesAreCompatible(FromPointee, ToPointee))
2613     FromPointee = ToPointee;
2614   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2615                                     IncompatibleObjC))
2616     return false;
2617 
2618   /// Construct the type we're converting to, which is a pointer to
2619   /// __autoreleasing pointee.
2620   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2621   ConvertedType = Context.getPointerType(FromPointee);
2622   return true;
2623 }
2624 
2625 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2626                                     QualType& ConvertedType) {
2627   QualType ToPointeeType;
2628   if (const BlockPointerType *ToBlockPtr =
2629         ToType->getAs<BlockPointerType>())
2630     ToPointeeType = ToBlockPtr->getPointeeType();
2631   else
2632     return false;
2633 
2634   QualType FromPointeeType;
2635   if (const BlockPointerType *FromBlockPtr =
2636       FromType->getAs<BlockPointerType>())
2637     FromPointeeType = FromBlockPtr->getPointeeType();
2638   else
2639     return false;
2640   // We have pointer to blocks, check whether the only
2641   // differences in the argument and result types are in Objective-C
2642   // pointer conversions. If so, we permit the conversion.
2643 
2644   const FunctionProtoType *FromFunctionType
2645     = FromPointeeType->getAs<FunctionProtoType>();
2646   const FunctionProtoType *ToFunctionType
2647     = ToPointeeType->getAs<FunctionProtoType>();
2648 
2649   if (!FromFunctionType || !ToFunctionType)
2650     return false;
2651 
2652   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2653     return true;
2654 
2655   // Perform the quick checks that will tell us whether these
2656   // function types are obviously different.
2657   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2658       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2659     return false;
2660 
2661   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2662   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2663   if (FromEInfo != ToEInfo)
2664     return false;
2665 
2666   bool IncompatibleObjC = false;
2667   if (Context.hasSameType(FromFunctionType->getReturnType(),
2668                           ToFunctionType->getReturnType())) {
2669     // Okay, the types match exactly. Nothing to do.
2670   } else {
2671     QualType RHS = FromFunctionType->getReturnType();
2672     QualType LHS = ToFunctionType->getReturnType();
2673     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2674         !RHS.hasQualifiers() && LHS.hasQualifiers())
2675        LHS = LHS.getUnqualifiedType();
2676 
2677      if (Context.hasSameType(RHS,LHS)) {
2678        // OK exact match.
2679      } else if (isObjCPointerConversion(RHS, LHS,
2680                                         ConvertedType, IncompatibleObjC)) {
2681      if (IncompatibleObjC)
2682        return false;
2683      // Okay, we have an Objective-C pointer conversion.
2684      }
2685      else
2686        return false;
2687    }
2688 
2689    // Check argument types.
2690    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2691         ArgIdx != NumArgs; ++ArgIdx) {
2692      IncompatibleObjC = false;
2693      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2694      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2695      if (Context.hasSameType(FromArgType, ToArgType)) {
2696        // Okay, the types match exactly. Nothing to do.
2697      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2698                                         ConvertedType, IncompatibleObjC)) {
2699        if (IncompatibleObjC)
2700          return false;
2701        // Okay, we have an Objective-C pointer conversion.
2702      } else
2703        // Argument types are too different. Abort.
2704        return false;
2705    }
2706 
2707    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2708    bool CanUseToFPT, CanUseFromFPT;
2709    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2710                                       CanUseToFPT, CanUseFromFPT,
2711                                       NewParamInfos))
2712      return false;
2713 
2714    ConvertedType = ToType;
2715    return true;
2716 }
2717 
2718 enum {
2719   ft_default,
2720   ft_different_class,
2721   ft_parameter_arity,
2722   ft_parameter_mismatch,
2723   ft_return_type,
2724   ft_qualifer_mismatch,
2725   ft_noexcept
2726 };
2727 
2728 /// Attempts to get the FunctionProtoType from a Type. Handles
2729 /// MemberFunctionPointers properly.
2730 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2731   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2732     return FPT;
2733 
2734   if (auto *MPT = FromType->getAs<MemberPointerType>())
2735     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2736 
2737   return nullptr;
2738 }
2739 
2740 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2741 /// function types.  Catches different number of parameter, mismatch in
2742 /// parameter types, and different return types.
2743 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2744                                       QualType FromType, QualType ToType) {
2745   // If either type is not valid, include no extra info.
2746   if (FromType.isNull() || ToType.isNull()) {
2747     PDiag << ft_default;
2748     return;
2749   }
2750 
2751   // Get the function type from the pointers.
2752   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2753     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2754                             *ToMember = ToType->getAs<MemberPointerType>();
2755     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2756       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2757             << QualType(FromMember->getClass(), 0);
2758       return;
2759     }
2760     FromType = FromMember->getPointeeType();
2761     ToType = ToMember->getPointeeType();
2762   }
2763 
2764   if (FromType->isPointerType())
2765     FromType = FromType->getPointeeType();
2766   if (ToType->isPointerType())
2767     ToType = ToType->getPointeeType();
2768 
2769   // Remove references.
2770   FromType = FromType.getNonReferenceType();
2771   ToType = ToType.getNonReferenceType();
2772 
2773   // Don't print extra info for non-specialized template functions.
2774   if (FromType->isInstantiationDependentType() &&
2775       !FromType->getAs<TemplateSpecializationType>()) {
2776     PDiag << ft_default;
2777     return;
2778   }
2779 
2780   // No extra info for same types.
2781   if (Context.hasSameType(FromType, ToType)) {
2782     PDiag << ft_default;
2783     return;
2784   }
2785 
2786   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2787                           *ToFunction = tryGetFunctionProtoType(ToType);
2788 
2789   // Both types need to be function types.
2790   if (!FromFunction || !ToFunction) {
2791     PDiag << ft_default;
2792     return;
2793   }
2794 
2795   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2796     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2797           << FromFunction->getNumParams();
2798     return;
2799   }
2800 
2801   // Handle different parameter types.
2802   unsigned ArgPos;
2803   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2804     PDiag << ft_parameter_mismatch << ArgPos + 1
2805           << ToFunction->getParamType(ArgPos)
2806           << FromFunction->getParamType(ArgPos);
2807     return;
2808   }
2809 
2810   // Handle different return type.
2811   if (!Context.hasSameType(FromFunction->getReturnType(),
2812                            ToFunction->getReturnType())) {
2813     PDiag << ft_return_type << ToFunction->getReturnType()
2814           << FromFunction->getReturnType();
2815     return;
2816   }
2817 
2818   unsigned FromQuals = FromFunction->getTypeQuals(),
2819            ToQuals = ToFunction->getTypeQuals();
2820   if (FromQuals != ToQuals) {
2821     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2822     return;
2823   }
2824 
2825   // Handle exception specification differences on canonical type (in C++17
2826   // onwards).
2827   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2828           ->isNothrow() !=
2829       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2830           ->isNothrow()) {
2831     PDiag << ft_noexcept;
2832     return;
2833   }
2834 
2835   // Unable to find a difference, so add no extra info.
2836   PDiag << ft_default;
2837 }
2838 
2839 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2840 /// for equality of their argument types. Caller has already checked that
2841 /// they have same number of arguments.  If the parameters are different,
2842 /// ArgPos will have the parameter index of the first different parameter.
2843 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2844                                       const FunctionProtoType *NewType,
2845                                       unsigned *ArgPos) {
2846   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2847                                               N = NewType->param_type_begin(),
2848                                               E = OldType->param_type_end();
2849        O && (O != E); ++O, ++N) {
2850     if (!Context.hasSameType(O->getUnqualifiedType(),
2851                              N->getUnqualifiedType())) {
2852       if (ArgPos)
2853         *ArgPos = O - OldType->param_type_begin();
2854       return false;
2855     }
2856   }
2857   return true;
2858 }
2859 
2860 /// CheckPointerConversion - Check the pointer conversion from the
2861 /// expression From to the type ToType. This routine checks for
2862 /// ambiguous or inaccessible derived-to-base pointer
2863 /// conversions for which IsPointerConversion has already returned
2864 /// true. It returns true and produces a diagnostic if there was an
2865 /// error, or returns false otherwise.
2866 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2867                                   CastKind &Kind,
2868                                   CXXCastPath& BasePath,
2869                                   bool IgnoreBaseAccess,
2870                                   bool Diagnose) {
2871   QualType FromType = From->getType();
2872   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2873 
2874   Kind = CK_BitCast;
2875 
2876   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2877       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2878           Expr::NPCK_ZeroExpression) {
2879     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2880       DiagRuntimeBehavior(From->getExprLoc(), From,
2881                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2882                             << ToType << From->getSourceRange());
2883     else if (!isUnevaluatedContext())
2884       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2885         << ToType << From->getSourceRange();
2886   }
2887   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2888     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2889       QualType FromPointeeType = FromPtrType->getPointeeType(),
2890                ToPointeeType   = ToPtrType->getPointeeType();
2891 
2892       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2893           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2894         // We must have a derived-to-base conversion. Check an
2895         // ambiguous or inaccessible conversion.
2896         unsigned InaccessibleID = 0;
2897         unsigned AmbigiousID = 0;
2898         if (Diagnose) {
2899           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2900           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2901         }
2902         if (CheckDerivedToBaseConversion(
2903                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2904                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2905                 &BasePath, IgnoreBaseAccess))
2906           return true;
2907 
2908         // The conversion was successful.
2909         Kind = CK_DerivedToBase;
2910       }
2911 
2912       if (Diagnose && !IsCStyleOrFunctionalCast &&
2913           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2914         assert(getLangOpts().MSVCCompat &&
2915                "this should only be possible with MSVCCompat!");
2916         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2917             << From->getSourceRange();
2918       }
2919     }
2920   } else if (const ObjCObjectPointerType *ToPtrType =
2921                ToType->getAs<ObjCObjectPointerType>()) {
2922     if (const ObjCObjectPointerType *FromPtrType =
2923           FromType->getAs<ObjCObjectPointerType>()) {
2924       // Objective-C++ conversions are always okay.
2925       // FIXME: We should have a different class of conversions for the
2926       // Objective-C++ implicit conversions.
2927       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2928         return false;
2929     } else if (FromType->isBlockPointerType()) {
2930       Kind = CK_BlockPointerToObjCPointerCast;
2931     } else {
2932       Kind = CK_CPointerToObjCPointerCast;
2933     }
2934   } else if (ToType->isBlockPointerType()) {
2935     if (!FromType->isBlockPointerType())
2936       Kind = CK_AnyPointerToBlockPointerCast;
2937   }
2938 
2939   // We shouldn't fall into this case unless it's valid for other
2940   // reasons.
2941   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2942     Kind = CK_NullToPointer;
2943 
2944   return false;
2945 }
2946 
2947 /// IsMemberPointerConversion - Determines whether the conversion of the
2948 /// expression From, which has the (possibly adjusted) type FromType, can be
2949 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2950 /// If so, returns true and places the converted type (that might differ from
2951 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2952 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2953                                      QualType ToType,
2954                                      bool InOverloadResolution,
2955                                      QualType &ConvertedType) {
2956   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2957   if (!ToTypePtr)
2958     return false;
2959 
2960   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2961   if (From->isNullPointerConstant(Context,
2962                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2963                                         : Expr::NPC_ValueDependentIsNull)) {
2964     ConvertedType = ToType;
2965     return true;
2966   }
2967 
2968   // Otherwise, both types have to be member pointers.
2969   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2970   if (!FromTypePtr)
2971     return false;
2972 
2973   // A pointer to member of B can be converted to a pointer to member of D,
2974   // where D is derived from B (C++ 4.11p2).
2975   QualType FromClass(FromTypePtr->getClass(), 0);
2976   QualType ToClass(ToTypePtr->getClass(), 0);
2977 
2978   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2979       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2980     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2981                                                  ToClass.getTypePtr());
2982     return true;
2983   }
2984 
2985   return false;
2986 }
2987 
2988 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2989 /// expression From to the type ToType. This routine checks for ambiguous or
2990 /// virtual or inaccessible base-to-derived member pointer conversions
2991 /// for which IsMemberPointerConversion has already returned true. It returns
2992 /// true and produces a diagnostic if there was an error, or returns false
2993 /// otherwise.
2994 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2995                                         CastKind &Kind,
2996                                         CXXCastPath &BasePath,
2997                                         bool IgnoreBaseAccess) {
2998   QualType FromType = From->getType();
2999   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3000   if (!FromPtrType) {
3001     // This must be a null pointer to member pointer conversion
3002     assert(From->isNullPointerConstant(Context,
3003                                        Expr::NPC_ValueDependentIsNull) &&
3004            "Expr must be null pointer constant!");
3005     Kind = CK_NullToMemberPointer;
3006     return false;
3007   }
3008 
3009   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3010   assert(ToPtrType && "No member pointer cast has a target type "
3011                       "that is not a member pointer.");
3012 
3013   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3014   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3015 
3016   // FIXME: What about dependent types?
3017   assert(FromClass->isRecordType() && "Pointer into non-class.");
3018   assert(ToClass->isRecordType() && "Pointer into non-class.");
3019 
3020   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3021                      /*DetectVirtual=*/true);
3022   bool DerivationOkay =
3023       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3024   assert(DerivationOkay &&
3025          "Should not have been called if derivation isn't OK.");
3026   (void)DerivationOkay;
3027 
3028   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3029                                   getUnqualifiedType())) {
3030     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3031     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3032       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3033     return true;
3034   }
3035 
3036   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3037     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3038       << FromClass << ToClass << QualType(VBase, 0)
3039       << From->getSourceRange();
3040     return true;
3041   }
3042 
3043   if (!IgnoreBaseAccess)
3044     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3045                          Paths.front(),
3046                          diag::err_downcast_from_inaccessible_base);
3047 
3048   // Must be a base to derived member conversion.
3049   BuildBasePathArray(Paths, BasePath);
3050   Kind = CK_BaseToDerivedMemberPointer;
3051   return false;
3052 }
3053 
3054 /// Determine whether the lifetime conversion between the two given
3055 /// qualifiers sets is nontrivial.
3056 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3057                                                Qualifiers ToQuals) {
3058   // Converting anything to const __unsafe_unretained is trivial.
3059   if (ToQuals.hasConst() &&
3060       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3061     return false;
3062 
3063   return true;
3064 }
3065 
3066 /// IsQualificationConversion - Determines whether the conversion from
3067 /// an rvalue of type FromType to ToType is a qualification conversion
3068 /// (C++ 4.4).
3069 ///
3070 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3071 /// when the qualification conversion involves a change in the Objective-C
3072 /// object lifetime.
3073 bool
3074 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3075                                 bool CStyle, bool &ObjCLifetimeConversion) {
3076   FromType = Context.getCanonicalType(FromType);
3077   ToType = Context.getCanonicalType(ToType);
3078   ObjCLifetimeConversion = false;
3079 
3080   // If FromType and ToType are the same type, this is not a
3081   // qualification conversion.
3082   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3083     return false;
3084 
3085   // (C++ 4.4p4):
3086   //   A conversion can add cv-qualifiers at levels other than the first
3087   //   in multi-level pointers, subject to the following rules: [...]
3088   bool PreviousToQualsIncludeConst = true;
3089   bool UnwrappedAnyPointer = false;
3090   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3091     // Within each iteration of the loop, we check the qualifiers to
3092     // determine if this still looks like a qualification
3093     // conversion. Then, if all is well, we unwrap one more level of
3094     // pointers or pointers-to-members and do it all again
3095     // until there are no more pointers or pointers-to-members left to
3096     // unwrap.
3097     UnwrappedAnyPointer = true;
3098 
3099     Qualifiers FromQuals = FromType.getQualifiers();
3100     Qualifiers ToQuals = ToType.getQualifiers();
3101 
3102     // Ignore __unaligned qualifier if this type is void.
3103     if (ToType.getUnqualifiedType()->isVoidType())
3104       FromQuals.removeUnaligned();
3105 
3106     // Objective-C ARC:
3107     //   Check Objective-C lifetime conversions.
3108     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3109         UnwrappedAnyPointer) {
3110       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3111         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3112           ObjCLifetimeConversion = true;
3113         FromQuals.removeObjCLifetime();
3114         ToQuals.removeObjCLifetime();
3115       } else {
3116         // Qualification conversions cannot cast between different
3117         // Objective-C lifetime qualifiers.
3118         return false;
3119       }
3120     }
3121 
3122     // Allow addition/removal of GC attributes but not changing GC attributes.
3123     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3124         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3125       FromQuals.removeObjCGCAttr();
3126       ToQuals.removeObjCGCAttr();
3127     }
3128 
3129     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3130     //      2,j, and similarly for volatile.
3131     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3132       return false;
3133 
3134     //   -- if the cv 1,j and cv 2,j are different, then const is in
3135     //      every cv for 0 < k < j.
3136     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3137         && !PreviousToQualsIncludeConst)
3138       return false;
3139 
3140     // Keep track of whether all prior cv-qualifiers in the "to" type
3141     // include const.
3142     PreviousToQualsIncludeConst
3143       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3144   }
3145 
3146   // We are left with FromType and ToType being the pointee types
3147   // after unwrapping the original FromType and ToType the same number
3148   // of types. If we unwrapped any pointers, and if FromType and
3149   // ToType have the same unqualified type (since we checked
3150   // qualifiers above), then this is a qualification conversion.
3151   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3152 }
3153 
3154 /// - Determine whether this is a conversion from a scalar type to an
3155 /// atomic type.
3156 ///
3157 /// If successful, updates \c SCS's second and third steps in the conversion
3158 /// sequence to finish the conversion.
3159 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3160                                 bool InOverloadResolution,
3161                                 StandardConversionSequence &SCS,
3162                                 bool CStyle) {
3163   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3164   if (!ToAtomic)
3165     return false;
3166 
3167   StandardConversionSequence InnerSCS;
3168   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3169                             InOverloadResolution, InnerSCS,
3170                             CStyle, /*AllowObjCWritebackConversion=*/false))
3171     return false;
3172 
3173   SCS.Second = InnerSCS.Second;
3174   SCS.setToType(1, InnerSCS.getToType(1));
3175   SCS.Third = InnerSCS.Third;
3176   SCS.QualificationIncludesObjCLifetime
3177     = InnerSCS.QualificationIncludesObjCLifetime;
3178   SCS.setToType(2, InnerSCS.getToType(2));
3179   return true;
3180 }
3181 
3182 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3183                                               CXXConstructorDecl *Constructor,
3184                                               QualType Type) {
3185   const FunctionProtoType *CtorType =
3186       Constructor->getType()->getAs<FunctionProtoType>();
3187   if (CtorType->getNumParams() > 0) {
3188     QualType FirstArg = CtorType->getParamType(0);
3189     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3190       return true;
3191   }
3192   return false;
3193 }
3194 
3195 static OverloadingResult
3196 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3197                                        CXXRecordDecl *To,
3198                                        UserDefinedConversionSequence &User,
3199                                        OverloadCandidateSet &CandidateSet,
3200                                        bool AllowExplicit) {
3201   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3202   for (auto *D : S.LookupConstructors(To)) {
3203     auto Info = getConstructorInfo(D);
3204     if (!Info)
3205       continue;
3206 
3207     bool Usable = !Info.Constructor->isInvalidDecl() &&
3208                   S.isInitListConstructor(Info.Constructor) &&
3209                   (AllowExplicit || !Info.Constructor->isExplicit());
3210     if (Usable) {
3211       // If the first argument is (a reference to) the target type,
3212       // suppress conversions.
3213       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3214           S.Context, Info.Constructor, ToType);
3215       if (Info.ConstructorTmpl)
3216         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3217                                        /*ExplicitArgs*/ nullptr, From,
3218                                        CandidateSet, SuppressUserConversions);
3219       else
3220         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3221                                CandidateSet, SuppressUserConversions);
3222     }
3223   }
3224 
3225   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3226 
3227   OverloadCandidateSet::iterator Best;
3228   switch (auto Result =
3229             CandidateSet.BestViableFunction(S, From->getLocStart(),
3230                                             Best)) {
3231   case OR_Deleted:
3232   case OR_Success: {
3233     // Record the standard conversion we used and the conversion function.
3234     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3235     QualType ThisType = Constructor->getThisType(S.Context);
3236     // Initializer lists don't have conversions as such.
3237     User.Before.setAsIdentityConversion();
3238     User.HadMultipleCandidates = HadMultipleCandidates;
3239     User.ConversionFunction = Constructor;
3240     User.FoundConversionFunction = Best->FoundDecl;
3241     User.After.setAsIdentityConversion();
3242     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3243     User.After.setAllToTypes(ToType);
3244     return Result;
3245   }
3246 
3247   case OR_No_Viable_Function:
3248     return OR_No_Viable_Function;
3249   case OR_Ambiguous:
3250     return OR_Ambiguous;
3251   }
3252 
3253   llvm_unreachable("Invalid OverloadResult!");
3254 }
3255 
3256 /// Determines whether there is a user-defined conversion sequence
3257 /// (C++ [over.ics.user]) that converts expression From to the type
3258 /// ToType. If such a conversion exists, User will contain the
3259 /// user-defined conversion sequence that performs such a conversion
3260 /// and this routine will return true. Otherwise, this routine returns
3261 /// false and User is unspecified.
3262 ///
3263 /// \param AllowExplicit  true if the conversion should consider C++0x
3264 /// "explicit" conversion functions as well as non-explicit conversion
3265 /// functions (C++0x [class.conv.fct]p2).
3266 ///
3267 /// \param AllowObjCConversionOnExplicit true if the conversion should
3268 /// allow an extra Objective-C pointer conversion on uses of explicit
3269 /// constructors. Requires \c AllowExplicit to also be set.
3270 static OverloadingResult
3271 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3272                         UserDefinedConversionSequence &User,
3273                         OverloadCandidateSet &CandidateSet,
3274                         bool AllowExplicit,
3275                         bool AllowObjCConversionOnExplicit) {
3276   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3277   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3278 
3279   // Whether we will only visit constructors.
3280   bool ConstructorsOnly = false;
3281 
3282   // If the type we are conversion to is a class type, enumerate its
3283   // constructors.
3284   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3285     // C++ [over.match.ctor]p1:
3286     //   When objects of class type are direct-initialized (8.5), or
3287     //   copy-initialized from an expression of the same or a
3288     //   derived class type (8.5), overload resolution selects the
3289     //   constructor. [...] For copy-initialization, the candidate
3290     //   functions are all the converting constructors (12.3.1) of
3291     //   that class. The argument list is the expression-list within
3292     //   the parentheses of the initializer.
3293     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3294         (From->getType()->getAs<RecordType>() &&
3295          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3296       ConstructorsOnly = true;
3297 
3298     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3299       // We're not going to find any constructors.
3300     } else if (CXXRecordDecl *ToRecordDecl
3301                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3302 
3303       Expr **Args = &From;
3304       unsigned NumArgs = 1;
3305       bool ListInitializing = false;
3306       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3307         // But first, see if there is an init-list-constructor that will work.
3308         OverloadingResult Result = IsInitializerListConstructorConversion(
3309             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3310         if (Result != OR_No_Viable_Function)
3311           return Result;
3312         // Never mind.
3313         CandidateSet.clear(
3314             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3315 
3316         // If we're list-initializing, we pass the individual elements as
3317         // arguments, not the entire list.
3318         Args = InitList->getInits();
3319         NumArgs = InitList->getNumInits();
3320         ListInitializing = true;
3321       }
3322 
3323       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3324         auto Info = getConstructorInfo(D);
3325         if (!Info)
3326           continue;
3327 
3328         bool Usable = !Info.Constructor->isInvalidDecl();
3329         if (ListInitializing)
3330           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3331         else
3332           Usable = Usable &&
3333                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3334         if (Usable) {
3335           bool SuppressUserConversions = !ConstructorsOnly;
3336           if (SuppressUserConversions && ListInitializing) {
3337             SuppressUserConversions = false;
3338             if (NumArgs == 1) {
3339               // If the first argument is (a reference to) the target type,
3340               // suppress conversions.
3341               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3342                   S.Context, Info.Constructor, ToType);
3343             }
3344           }
3345           if (Info.ConstructorTmpl)
3346             S.AddTemplateOverloadCandidate(
3347                 Info.ConstructorTmpl, Info.FoundDecl,
3348                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3349                 CandidateSet, SuppressUserConversions);
3350           else
3351             // Allow one user-defined conversion when user specifies a
3352             // From->ToType conversion via an static cast (c-style, etc).
3353             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3354                                    llvm::makeArrayRef(Args, NumArgs),
3355                                    CandidateSet, SuppressUserConversions);
3356         }
3357       }
3358     }
3359   }
3360 
3361   // Enumerate conversion functions, if we're allowed to.
3362   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3363   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3364     // No conversion functions from incomplete types.
3365   } else if (const RecordType *FromRecordType
3366                                    = From->getType()->getAs<RecordType>()) {
3367     if (CXXRecordDecl *FromRecordDecl
3368          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3369       // Add all of the conversion functions as candidates.
3370       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3371       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3372         DeclAccessPair FoundDecl = I.getPair();
3373         NamedDecl *D = FoundDecl.getDecl();
3374         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3375         if (isa<UsingShadowDecl>(D))
3376           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3377 
3378         CXXConversionDecl *Conv;
3379         FunctionTemplateDecl *ConvTemplate;
3380         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3381           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3382         else
3383           Conv = cast<CXXConversionDecl>(D);
3384 
3385         if (AllowExplicit || !Conv->isExplicit()) {
3386           if (ConvTemplate)
3387             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3388                                              ActingContext, From, ToType,
3389                                              CandidateSet,
3390                                              AllowObjCConversionOnExplicit);
3391           else
3392             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3393                                      From, ToType, CandidateSet,
3394                                      AllowObjCConversionOnExplicit);
3395         }
3396       }
3397     }
3398   }
3399 
3400   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3401 
3402   OverloadCandidateSet::iterator Best;
3403   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3404                                                         Best)) {
3405   case OR_Success:
3406   case OR_Deleted:
3407     // Record the standard conversion we used and the conversion function.
3408     if (CXXConstructorDecl *Constructor
3409           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3410       // C++ [over.ics.user]p1:
3411       //   If the user-defined conversion is specified by a
3412       //   constructor (12.3.1), the initial standard conversion
3413       //   sequence converts the source type to the type required by
3414       //   the argument of the constructor.
3415       //
3416       QualType ThisType = Constructor->getThisType(S.Context);
3417       if (isa<InitListExpr>(From)) {
3418         // Initializer lists don't have conversions as such.
3419         User.Before.setAsIdentityConversion();
3420       } else {
3421         if (Best->Conversions[0].isEllipsis())
3422           User.EllipsisConversion = true;
3423         else {
3424           User.Before = Best->Conversions[0].Standard;
3425           User.EllipsisConversion = false;
3426         }
3427       }
3428       User.HadMultipleCandidates = HadMultipleCandidates;
3429       User.ConversionFunction = Constructor;
3430       User.FoundConversionFunction = Best->FoundDecl;
3431       User.After.setAsIdentityConversion();
3432       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3433       User.After.setAllToTypes(ToType);
3434       return Result;
3435     }
3436     if (CXXConversionDecl *Conversion
3437                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3438       // C++ [over.ics.user]p1:
3439       //
3440       //   [...] If the user-defined conversion is specified by a
3441       //   conversion function (12.3.2), the initial standard
3442       //   conversion sequence converts the source type to the
3443       //   implicit object parameter of the conversion function.
3444       User.Before = Best->Conversions[0].Standard;
3445       User.HadMultipleCandidates = HadMultipleCandidates;
3446       User.ConversionFunction = Conversion;
3447       User.FoundConversionFunction = Best->FoundDecl;
3448       User.EllipsisConversion = false;
3449 
3450       // C++ [over.ics.user]p2:
3451       //   The second standard conversion sequence converts the
3452       //   result of the user-defined conversion to the target type
3453       //   for the sequence. Since an implicit conversion sequence
3454       //   is an initialization, the special rules for
3455       //   initialization by user-defined conversion apply when
3456       //   selecting the best user-defined conversion for a
3457       //   user-defined conversion sequence (see 13.3.3 and
3458       //   13.3.3.1).
3459       User.After = Best->FinalConversion;
3460       return Result;
3461     }
3462     llvm_unreachable("Not a constructor or conversion function?");
3463 
3464   case OR_No_Viable_Function:
3465     return OR_No_Viable_Function;
3466 
3467   case OR_Ambiguous:
3468     return OR_Ambiguous;
3469   }
3470 
3471   llvm_unreachable("Invalid OverloadResult!");
3472 }
3473 
3474 bool
3475 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3476   ImplicitConversionSequence ICS;
3477   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3478                                     OverloadCandidateSet::CSK_Normal);
3479   OverloadingResult OvResult =
3480     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3481                             CandidateSet, false, false);
3482   if (OvResult == OR_Ambiguous)
3483     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3484         << From->getType() << ToType << From->getSourceRange();
3485   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3486     if (!RequireCompleteType(From->getLocStart(), ToType,
3487                              diag::err_typecheck_nonviable_condition_incomplete,
3488                              From->getType(), From->getSourceRange()))
3489       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3490           << false << From->getType() << From->getSourceRange() << ToType;
3491   } else
3492     return false;
3493   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3494   return true;
3495 }
3496 
3497 /// Compare the user-defined conversion functions or constructors
3498 /// of two user-defined conversion sequences to determine whether any ordering
3499 /// is possible.
3500 static ImplicitConversionSequence::CompareKind
3501 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3502                            FunctionDecl *Function2) {
3503   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3504     return ImplicitConversionSequence::Indistinguishable;
3505 
3506   // Objective-C++:
3507   //   If both conversion functions are implicitly-declared conversions from
3508   //   a lambda closure type to a function pointer and a block pointer,
3509   //   respectively, always prefer the conversion to a function pointer,
3510   //   because the function pointer is more lightweight and is more likely
3511   //   to keep code working.
3512   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3513   if (!Conv1)
3514     return ImplicitConversionSequence::Indistinguishable;
3515 
3516   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3517   if (!Conv2)
3518     return ImplicitConversionSequence::Indistinguishable;
3519 
3520   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3521     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3522     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3523     if (Block1 != Block2)
3524       return Block1 ? ImplicitConversionSequence::Worse
3525                     : ImplicitConversionSequence::Better;
3526   }
3527 
3528   return ImplicitConversionSequence::Indistinguishable;
3529 }
3530 
3531 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3532     const ImplicitConversionSequence &ICS) {
3533   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3534          (ICS.isUserDefined() &&
3535           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3536 }
3537 
3538 /// CompareImplicitConversionSequences - Compare two implicit
3539 /// conversion sequences to determine whether one is better than the
3540 /// other or if they are indistinguishable (C++ 13.3.3.2).
3541 static ImplicitConversionSequence::CompareKind
3542 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3543                                    const ImplicitConversionSequence& ICS1,
3544                                    const ImplicitConversionSequence& ICS2)
3545 {
3546   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3547   // conversion sequences (as defined in 13.3.3.1)
3548   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3549   //      conversion sequence than a user-defined conversion sequence or
3550   //      an ellipsis conversion sequence, and
3551   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3552   //      conversion sequence than an ellipsis conversion sequence
3553   //      (13.3.3.1.3).
3554   //
3555   // C++0x [over.best.ics]p10:
3556   //   For the purpose of ranking implicit conversion sequences as
3557   //   described in 13.3.3.2, the ambiguous conversion sequence is
3558   //   treated as a user-defined sequence that is indistinguishable
3559   //   from any other user-defined conversion sequence.
3560 
3561   // String literal to 'char *' conversion has been deprecated in C++03. It has
3562   // been removed from C++11. We still accept this conversion, if it happens at
3563   // the best viable function. Otherwise, this conversion is considered worse
3564   // than ellipsis conversion. Consider this as an extension; this is not in the
3565   // standard. For example:
3566   //
3567   // int &f(...);    // #1
3568   // void f(char*);  // #2
3569   // void g() { int &r = f("foo"); }
3570   //
3571   // In C++03, we pick #2 as the best viable function.
3572   // In C++11, we pick #1 as the best viable function, because ellipsis
3573   // conversion is better than string-literal to char* conversion (since there
3574   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3575   // convert arguments, #2 would be the best viable function in C++11.
3576   // If the best viable function has this conversion, a warning will be issued
3577   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3578 
3579   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3580       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3581       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3582     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3583                ? ImplicitConversionSequence::Worse
3584                : ImplicitConversionSequence::Better;
3585 
3586   if (ICS1.getKindRank() < ICS2.getKindRank())
3587     return ImplicitConversionSequence::Better;
3588   if (ICS2.getKindRank() < ICS1.getKindRank())
3589     return ImplicitConversionSequence::Worse;
3590 
3591   // The following checks require both conversion sequences to be of
3592   // the same kind.
3593   if (ICS1.getKind() != ICS2.getKind())
3594     return ImplicitConversionSequence::Indistinguishable;
3595 
3596   ImplicitConversionSequence::CompareKind Result =
3597       ImplicitConversionSequence::Indistinguishable;
3598 
3599   // Two implicit conversion sequences of the same form are
3600   // indistinguishable conversion sequences unless one of the
3601   // following rules apply: (C++ 13.3.3.2p3):
3602 
3603   // List-initialization sequence L1 is a better conversion sequence than
3604   // list-initialization sequence L2 if:
3605   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3606   //   if not that,
3607   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3608   //   and N1 is smaller than N2.,
3609   // even if one of the other rules in this paragraph would otherwise apply.
3610   if (!ICS1.isBad()) {
3611     if (ICS1.isStdInitializerListElement() &&
3612         !ICS2.isStdInitializerListElement())
3613       return ImplicitConversionSequence::Better;
3614     if (!ICS1.isStdInitializerListElement() &&
3615         ICS2.isStdInitializerListElement())
3616       return ImplicitConversionSequence::Worse;
3617   }
3618 
3619   if (ICS1.isStandard())
3620     // Standard conversion sequence S1 is a better conversion sequence than
3621     // standard conversion sequence S2 if [...]
3622     Result = CompareStandardConversionSequences(S, Loc,
3623                                                 ICS1.Standard, ICS2.Standard);
3624   else if (ICS1.isUserDefined()) {
3625     // User-defined conversion sequence U1 is a better conversion
3626     // sequence than another user-defined conversion sequence U2 if
3627     // they contain the same user-defined conversion function or
3628     // constructor and if the second standard conversion sequence of
3629     // U1 is better than the second standard conversion sequence of
3630     // U2 (C++ 13.3.3.2p3).
3631     if (ICS1.UserDefined.ConversionFunction ==
3632           ICS2.UserDefined.ConversionFunction)
3633       Result = CompareStandardConversionSequences(S, Loc,
3634                                                   ICS1.UserDefined.After,
3635                                                   ICS2.UserDefined.After);
3636     else
3637       Result = compareConversionFunctions(S,
3638                                           ICS1.UserDefined.ConversionFunction,
3639                                           ICS2.UserDefined.ConversionFunction);
3640   }
3641 
3642   return Result;
3643 }
3644 
3645 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3646   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3647     Qualifiers Quals;
3648     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3649     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3650   }
3651 
3652   return Context.hasSameUnqualifiedType(T1, T2);
3653 }
3654 
3655 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3656 // determine if one is a proper subset of the other.
3657 static ImplicitConversionSequence::CompareKind
3658 compareStandardConversionSubsets(ASTContext &Context,
3659                                  const StandardConversionSequence& SCS1,
3660                                  const StandardConversionSequence& SCS2) {
3661   ImplicitConversionSequence::CompareKind Result
3662     = ImplicitConversionSequence::Indistinguishable;
3663 
3664   // the identity conversion sequence is considered to be a subsequence of
3665   // any non-identity conversion sequence
3666   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3667     return ImplicitConversionSequence::Better;
3668   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3669     return ImplicitConversionSequence::Worse;
3670 
3671   if (SCS1.Second != SCS2.Second) {
3672     if (SCS1.Second == ICK_Identity)
3673       Result = ImplicitConversionSequence::Better;
3674     else if (SCS2.Second == ICK_Identity)
3675       Result = ImplicitConversionSequence::Worse;
3676     else
3677       return ImplicitConversionSequence::Indistinguishable;
3678   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3679     return ImplicitConversionSequence::Indistinguishable;
3680 
3681   if (SCS1.Third == SCS2.Third) {
3682     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3683                              : ImplicitConversionSequence::Indistinguishable;
3684   }
3685 
3686   if (SCS1.Third == ICK_Identity)
3687     return Result == ImplicitConversionSequence::Worse
3688              ? ImplicitConversionSequence::Indistinguishable
3689              : ImplicitConversionSequence::Better;
3690 
3691   if (SCS2.Third == ICK_Identity)
3692     return Result == ImplicitConversionSequence::Better
3693              ? ImplicitConversionSequence::Indistinguishable
3694              : ImplicitConversionSequence::Worse;
3695 
3696   return ImplicitConversionSequence::Indistinguishable;
3697 }
3698 
3699 /// Determine whether one of the given reference bindings is better
3700 /// than the other based on what kind of bindings they are.
3701 static bool
3702 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3703                              const StandardConversionSequence &SCS2) {
3704   // C++0x [over.ics.rank]p3b4:
3705   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3706   //      implicit object parameter of a non-static member function declared
3707   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3708   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3709   //      lvalue reference to a function lvalue and S2 binds an rvalue
3710   //      reference*.
3711   //
3712   // FIXME: Rvalue references. We're going rogue with the above edits,
3713   // because the semantics in the current C++0x working paper (N3225 at the
3714   // time of this writing) break the standard definition of std::forward
3715   // and std::reference_wrapper when dealing with references to functions.
3716   // Proposed wording changes submitted to CWG for consideration.
3717   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3718       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3719     return false;
3720 
3721   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3722           SCS2.IsLvalueReference) ||
3723          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3724           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3725 }
3726 
3727 /// CompareStandardConversionSequences - Compare two standard
3728 /// conversion sequences to determine whether one is better than the
3729 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3730 static ImplicitConversionSequence::CompareKind
3731 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3732                                    const StandardConversionSequence& SCS1,
3733                                    const StandardConversionSequence& SCS2)
3734 {
3735   // Standard conversion sequence S1 is a better conversion sequence
3736   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3737 
3738   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3739   //     sequences in the canonical form defined by 13.3.3.1.1,
3740   //     excluding any Lvalue Transformation; the identity conversion
3741   //     sequence is considered to be a subsequence of any
3742   //     non-identity conversion sequence) or, if not that,
3743   if (ImplicitConversionSequence::CompareKind CK
3744         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3745     return CK;
3746 
3747   //  -- the rank of S1 is better than the rank of S2 (by the rules
3748   //     defined below), or, if not that,
3749   ImplicitConversionRank Rank1 = SCS1.getRank();
3750   ImplicitConversionRank Rank2 = SCS2.getRank();
3751   if (Rank1 < Rank2)
3752     return ImplicitConversionSequence::Better;
3753   else if (Rank2 < Rank1)
3754     return ImplicitConversionSequence::Worse;
3755 
3756   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3757   // are indistinguishable unless one of the following rules
3758   // applies:
3759 
3760   //   A conversion that is not a conversion of a pointer, or
3761   //   pointer to member, to bool is better than another conversion
3762   //   that is such a conversion.
3763   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3764     return SCS2.isPointerConversionToBool()
3765              ? ImplicitConversionSequence::Better
3766              : ImplicitConversionSequence::Worse;
3767 
3768   // C++ [over.ics.rank]p4b2:
3769   //
3770   //   If class B is derived directly or indirectly from class A,
3771   //   conversion of B* to A* is better than conversion of B* to
3772   //   void*, and conversion of A* to void* is better than conversion
3773   //   of B* to void*.
3774   bool SCS1ConvertsToVoid
3775     = SCS1.isPointerConversionToVoidPointer(S.Context);
3776   bool SCS2ConvertsToVoid
3777     = SCS2.isPointerConversionToVoidPointer(S.Context);
3778   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3779     // Exactly one of the conversion sequences is a conversion to
3780     // a void pointer; it's the worse conversion.
3781     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3782                               : ImplicitConversionSequence::Worse;
3783   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3784     // Neither conversion sequence converts to a void pointer; compare
3785     // their derived-to-base conversions.
3786     if (ImplicitConversionSequence::CompareKind DerivedCK
3787           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3788       return DerivedCK;
3789   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3790              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3791     // Both conversion sequences are conversions to void
3792     // pointers. Compare the source types to determine if there's an
3793     // inheritance relationship in their sources.
3794     QualType FromType1 = SCS1.getFromType();
3795     QualType FromType2 = SCS2.getFromType();
3796 
3797     // Adjust the types we're converting from via the array-to-pointer
3798     // conversion, if we need to.
3799     if (SCS1.First == ICK_Array_To_Pointer)
3800       FromType1 = S.Context.getArrayDecayedType(FromType1);
3801     if (SCS2.First == ICK_Array_To_Pointer)
3802       FromType2 = S.Context.getArrayDecayedType(FromType2);
3803 
3804     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3805     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3806 
3807     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3808       return ImplicitConversionSequence::Better;
3809     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3810       return ImplicitConversionSequence::Worse;
3811 
3812     // Objective-C++: If one interface is more specific than the
3813     // other, it is the better one.
3814     const ObjCObjectPointerType* FromObjCPtr1
3815       = FromType1->getAs<ObjCObjectPointerType>();
3816     const ObjCObjectPointerType* FromObjCPtr2
3817       = FromType2->getAs<ObjCObjectPointerType>();
3818     if (FromObjCPtr1 && FromObjCPtr2) {
3819       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3820                                                           FromObjCPtr2);
3821       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3822                                                            FromObjCPtr1);
3823       if (AssignLeft != AssignRight) {
3824         return AssignLeft? ImplicitConversionSequence::Better
3825                          : ImplicitConversionSequence::Worse;
3826       }
3827     }
3828   }
3829 
3830   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3831   // bullet 3).
3832   if (ImplicitConversionSequence::CompareKind QualCK
3833         = CompareQualificationConversions(S, SCS1, SCS2))
3834     return QualCK;
3835 
3836   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3837     // Check for a better reference binding based on the kind of bindings.
3838     if (isBetterReferenceBindingKind(SCS1, SCS2))
3839       return ImplicitConversionSequence::Better;
3840     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3841       return ImplicitConversionSequence::Worse;
3842 
3843     // C++ [over.ics.rank]p3b4:
3844     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3845     //      which the references refer are the same type except for
3846     //      top-level cv-qualifiers, and the type to which the reference
3847     //      initialized by S2 refers is more cv-qualified than the type
3848     //      to which the reference initialized by S1 refers.
3849     QualType T1 = SCS1.getToType(2);
3850     QualType T2 = SCS2.getToType(2);
3851     T1 = S.Context.getCanonicalType(T1);
3852     T2 = S.Context.getCanonicalType(T2);
3853     Qualifiers T1Quals, T2Quals;
3854     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3855     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3856     if (UnqualT1 == UnqualT2) {
3857       // Objective-C++ ARC: If the references refer to objects with different
3858       // lifetimes, prefer bindings that don't change lifetime.
3859       if (SCS1.ObjCLifetimeConversionBinding !=
3860                                           SCS2.ObjCLifetimeConversionBinding) {
3861         return SCS1.ObjCLifetimeConversionBinding
3862                                            ? ImplicitConversionSequence::Worse
3863                                            : ImplicitConversionSequence::Better;
3864       }
3865 
3866       // If the type is an array type, promote the element qualifiers to the
3867       // type for comparison.
3868       if (isa<ArrayType>(T1) && T1Quals)
3869         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3870       if (isa<ArrayType>(T2) && T2Quals)
3871         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3872       if (T2.isMoreQualifiedThan(T1))
3873         return ImplicitConversionSequence::Better;
3874       else if (T1.isMoreQualifiedThan(T2))
3875         return ImplicitConversionSequence::Worse;
3876     }
3877   }
3878 
3879   // In Microsoft mode, prefer an integral conversion to a
3880   // floating-to-integral conversion if the integral conversion
3881   // is between types of the same size.
3882   // For example:
3883   // void f(float);
3884   // void f(int);
3885   // int main {
3886   //    long a;
3887   //    f(a);
3888   // }
3889   // Here, MSVC will call f(int) instead of generating a compile error
3890   // as clang will do in standard mode.
3891   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3892       SCS2.Second == ICK_Floating_Integral &&
3893       S.Context.getTypeSize(SCS1.getFromType()) ==
3894           S.Context.getTypeSize(SCS1.getToType(2)))
3895     return ImplicitConversionSequence::Better;
3896 
3897   return ImplicitConversionSequence::Indistinguishable;
3898 }
3899 
3900 /// CompareQualificationConversions - Compares two standard conversion
3901 /// sequences to determine whether they can be ranked based on their
3902 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3903 static ImplicitConversionSequence::CompareKind
3904 CompareQualificationConversions(Sema &S,
3905                                 const StandardConversionSequence& SCS1,
3906                                 const StandardConversionSequence& SCS2) {
3907   // C++ 13.3.3.2p3:
3908   //  -- S1 and S2 differ only in their qualification conversion and
3909   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3910   //     cv-qualification signature of type T1 is a proper subset of
3911   //     the cv-qualification signature of type T2, and S1 is not the
3912   //     deprecated string literal array-to-pointer conversion (4.2).
3913   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3914       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3915     return ImplicitConversionSequence::Indistinguishable;
3916 
3917   // FIXME: the example in the standard doesn't use a qualification
3918   // conversion (!)
3919   QualType T1 = SCS1.getToType(2);
3920   QualType T2 = SCS2.getToType(2);
3921   T1 = S.Context.getCanonicalType(T1);
3922   T2 = S.Context.getCanonicalType(T2);
3923   Qualifiers T1Quals, T2Quals;
3924   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3925   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3926 
3927   // If the types are the same, we won't learn anything by unwrapped
3928   // them.
3929   if (UnqualT1 == UnqualT2)
3930     return ImplicitConversionSequence::Indistinguishable;
3931 
3932   // If the type is an array type, promote the element qualifiers to the type
3933   // for comparison.
3934   if (isa<ArrayType>(T1) && T1Quals)
3935     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3936   if (isa<ArrayType>(T2) && T2Quals)
3937     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3938 
3939   ImplicitConversionSequence::CompareKind Result
3940     = ImplicitConversionSequence::Indistinguishable;
3941 
3942   // Objective-C++ ARC:
3943   //   Prefer qualification conversions not involving a change in lifetime
3944   //   to qualification conversions that do not change lifetime.
3945   if (SCS1.QualificationIncludesObjCLifetime !=
3946                                       SCS2.QualificationIncludesObjCLifetime) {
3947     Result = SCS1.QualificationIncludesObjCLifetime
3948                ? ImplicitConversionSequence::Worse
3949                : ImplicitConversionSequence::Better;
3950   }
3951 
3952   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3953     // Within each iteration of the loop, we check the qualifiers to
3954     // determine if this still looks like a qualification
3955     // conversion. Then, if all is well, we unwrap one more level of
3956     // pointers or pointers-to-members and do it all again
3957     // until there are no more pointers or pointers-to-members left
3958     // to unwrap. This essentially mimics what
3959     // IsQualificationConversion does, but here we're checking for a
3960     // strict subset of qualifiers.
3961     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3962       // The qualifiers are the same, so this doesn't tell us anything
3963       // about how the sequences rank.
3964       ;
3965     else if (T2.isMoreQualifiedThan(T1)) {
3966       // T1 has fewer qualifiers, so it could be the better sequence.
3967       if (Result == ImplicitConversionSequence::Worse)
3968         // Neither has qualifiers that are a subset of the other's
3969         // qualifiers.
3970         return ImplicitConversionSequence::Indistinguishable;
3971 
3972       Result = ImplicitConversionSequence::Better;
3973     } else if (T1.isMoreQualifiedThan(T2)) {
3974       // T2 has fewer qualifiers, so it could be the better sequence.
3975       if (Result == ImplicitConversionSequence::Better)
3976         // Neither has qualifiers that are a subset of the other's
3977         // qualifiers.
3978         return ImplicitConversionSequence::Indistinguishable;
3979 
3980       Result = ImplicitConversionSequence::Worse;
3981     } else {
3982       // Qualifiers are disjoint.
3983       return ImplicitConversionSequence::Indistinguishable;
3984     }
3985 
3986     // If the types after this point are equivalent, we're done.
3987     if (S.Context.hasSameUnqualifiedType(T1, T2))
3988       break;
3989   }
3990 
3991   // Check that the winning standard conversion sequence isn't using
3992   // the deprecated string literal array to pointer conversion.
3993   switch (Result) {
3994   case ImplicitConversionSequence::Better:
3995     if (SCS1.DeprecatedStringLiteralToCharPtr)
3996       Result = ImplicitConversionSequence::Indistinguishable;
3997     break;
3998 
3999   case ImplicitConversionSequence::Indistinguishable:
4000     break;
4001 
4002   case ImplicitConversionSequence::Worse:
4003     if (SCS2.DeprecatedStringLiteralToCharPtr)
4004       Result = ImplicitConversionSequence::Indistinguishable;
4005     break;
4006   }
4007 
4008   return Result;
4009 }
4010 
4011 /// CompareDerivedToBaseConversions - Compares two standard conversion
4012 /// sequences to determine whether they can be ranked based on their
4013 /// various kinds of derived-to-base conversions (C++
4014 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4015 /// conversions between Objective-C interface types.
4016 static ImplicitConversionSequence::CompareKind
4017 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4018                                 const StandardConversionSequence& SCS1,
4019                                 const StandardConversionSequence& SCS2) {
4020   QualType FromType1 = SCS1.getFromType();
4021   QualType ToType1 = SCS1.getToType(1);
4022   QualType FromType2 = SCS2.getFromType();
4023   QualType ToType2 = SCS2.getToType(1);
4024 
4025   // Adjust the types we're converting from via the array-to-pointer
4026   // conversion, if we need to.
4027   if (SCS1.First == ICK_Array_To_Pointer)
4028     FromType1 = S.Context.getArrayDecayedType(FromType1);
4029   if (SCS2.First == ICK_Array_To_Pointer)
4030     FromType2 = S.Context.getArrayDecayedType(FromType2);
4031 
4032   // Canonicalize all of the types.
4033   FromType1 = S.Context.getCanonicalType(FromType1);
4034   ToType1 = S.Context.getCanonicalType(ToType1);
4035   FromType2 = S.Context.getCanonicalType(FromType2);
4036   ToType2 = S.Context.getCanonicalType(ToType2);
4037 
4038   // C++ [over.ics.rank]p4b3:
4039   //
4040   //   If class B is derived directly or indirectly from class A and
4041   //   class C is derived directly or indirectly from B,
4042   //
4043   // Compare based on pointer conversions.
4044   if (SCS1.Second == ICK_Pointer_Conversion &&
4045       SCS2.Second == ICK_Pointer_Conversion &&
4046       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4047       FromType1->isPointerType() && FromType2->isPointerType() &&
4048       ToType1->isPointerType() && ToType2->isPointerType()) {
4049     QualType FromPointee1
4050       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4051     QualType ToPointee1
4052       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4053     QualType FromPointee2
4054       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4055     QualType ToPointee2
4056       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4057 
4058     //   -- conversion of C* to B* is better than conversion of C* to A*,
4059     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4060       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4061         return ImplicitConversionSequence::Better;
4062       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4063         return ImplicitConversionSequence::Worse;
4064     }
4065 
4066     //   -- conversion of B* to A* is better than conversion of C* to A*,
4067     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4068       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4069         return ImplicitConversionSequence::Better;
4070       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4071         return ImplicitConversionSequence::Worse;
4072     }
4073   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4074              SCS2.Second == ICK_Pointer_Conversion) {
4075     const ObjCObjectPointerType *FromPtr1
4076       = FromType1->getAs<ObjCObjectPointerType>();
4077     const ObjCObjectPointerType *FromPtr2
4078       = FromType2->getAs<ObjCObjectPointerType>();
4079     const ObjCObjectPointerType *ToPtr1
4080       = ToType1->getAs<ObjCObjectPointerType>();
4081     const ObjCObjectPointerType *ToPtr2
4082       = ToType2->getAs<ObjCObjectPointerType>();
4083 
4084     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4085       // Apply the same conversion ranking rules for Objective-C pointer types
4086       // that we do for C++ pointers to class types. However, we employ the
4087       // Objective-C pseudo-subtyping relationship used for assignment of
4088       // Objective-C pointer types.
4089       bool FromAssignLeft
4090         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4091       bool FromAssignRight
4092         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4093       bool ToAssignLeft
4094         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4095       bool ToAssignRight
4096         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4097 
4098       // A conversion to an a non-id object pointer type or qualified 'id'
4099       // type is better than a conversion to 'id'.
4100       if (ToPtr1->isObjCIdType() &&
4101           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4102         return ImplicitConversionSequence::Worse;
4103       if (ToPtr2->isObjCIdType() &&
4104           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4105         return ImplicitConversionSequence::Better;
4106 
4107       // A conversion to a non-id object pointer type is better than a
4108       // conversion to a qualified 'id' type
4109       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4110         return ImplicitConversionSequence::Worse;
4111       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4112         return ImplicitConversionSequence::Better;
4113 
4114       // A conversion to an a non-Class object pointer type or qualified 'Class'
4115       // type is better than a conversion to 'Class'.
4116       if (ToPtr1->isObjCClassType() &&
4117           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4118         return ImplicitConversionSequence::Worse;
4119       if (ToPtr2->isObjCClassType() &&
4120           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4121         return ImplicitConversionSequence::Better;
4122 
4123       // A conversion to a non-Class object pointer type is better than a
4124       // conversion to a qualified 'Class' type.
4125       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4126         return ImplicitConversionSequence::Worse;
4127       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4128         return ImplicitConversionSequence::Better;
4129 
4130       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4131       if (S.Context.hasSameType(FromType1, FromType2) &&
4132           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4133           (ToAssignLeft != ToAssignRight)) {
4134         if (FromPtr1->isSpecialized()) {
4135           // "conversion of B<A> * to B * is better than conversion of B * to
4136           // C *.
4137           bool IsFirstSame =
4138               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4139           bool IsSecondSame =
4140               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4141           if (IsFirstSame) {
4142             if (!IsSecondSame)
4143               return ImplicitConversionSequence::Better;
4144           } else if (IsSecondSame)
4145             return ImplicitConversionSequence::Worse;
4146         }
4147         return ToAssignLeft? ImplicitConversionSequence::Worse
4148                            : ImplicitConversionSequence::Better;
4149       }
4150 
4151       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4152       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4153           (FromAssignLeft != FromAssignRight))
4154         return FromAssignLeft? ImplicitConversionSequence::Better
4155         : ImplicitConversionSequence::Worse;
4156     }
4157   }
4158 
4159   // Ranking of member-pointer types.
4160   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4161       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4162       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4163     const MemberPointerType * FromMemPointer1 =
4164                                         FromType1->getAs<MemberPointerType>();
4165     const MemberPointerType * ToMemPointer1 =
4166                                           ToType1->getAs<MemberPointerType>();
4167     const MemberPointerType * FromMemPointer2 =
4168                                           FromType2->getAs<MemberPointerType>();
4169     const MemberPointerType * ToMemPointer2 =
4170                                           ToType2->getAs<MemberPointerType>();
4171     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4172     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4173     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4174     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4175     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4176     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4177     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4178     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4179     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4180     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4181       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4182         return ImplicitConversionSequence::Worse;
4183       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4184         return ImplicitConversionSequence::Better;
4185     }
4186     // conversion of B::* to C::* is better than conversion of A::* to C::*
4187     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4188       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4189         return ImplicitConversionSequence::Better;
4190       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4191         return ImplicitConversionSequence::Worse;
4192     }
4193   }
4194 
4195   if (SCS1.Second == ICK_Derived_To_Base) {
4196     //   -- conversion of C to B is better than conversion of C to A,
4197     //   -- binding of an expression of type C to a reference of type
4198     //      B& is better than binding an expression of type C to a
4199     //      reference of type A&,
4200     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4201         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4202       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4203         return ImplicitConversionSequence::Better;
4204       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4205         return ImplicitConversionSequence::Worse;
4206     }
4207 
4208     //   -- conversion of B to A is better than conversion of C to A.
4209     //   -- binding of an expression of type B to a reference of type
4210     //      A& is better than binding an expression of type C to a
4211     //      reference of type A&,
4212     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4213         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4214       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4215         return ImplicitConversionSequence::Better;
4216       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4217         return ImplicitConversionSequence::Worse;
4218     }
4219   }
4220 
4221   return ImplicitConversionSequence::Indistinguishable;
4222 }
4223 
4224 /// Determine whether the given type is valid, e.g., it is not an invalid
4225 /// C++ class.
4226 static bool isTypeValid(QualType T) {
4227   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4228     return !Record->isInvalidDecl();
4229 
4230   return true;
4231 }
4232 
4233 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4234 /// determine whether they are reference-related,
4235 /// reference-compatible, reference-compatible with added
4236 /// qualification, or incompatible, for use in C++ initialization by
4237 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4238 /// type, and the first type (T1) is the pointee type of the reference
4239 /// type being initialized.
4240 Sema::ReferenceCompareResult
4241 Sema::CompareReferenceRelationship(SourceLocation Loc,
4242                                    QualType OrigT1, QualType OrigT2,
4243                                    bool &DerivedToBase,
4244                                    bool &ObjCConversion,
4245                                    bool &ObjCLifetimeConversion) {
4246   assert(!OrigT1->isReferenceType() &&
4247     "T1 must be the pointee type of the reference type");
4248   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4249 
4250   QualType T1 = Context.getCanonicalType(OrigT1);
4251   QualType T2 = Context.getCanonicalType(OrigT2);
4252   Qualifiers T1Quals, T2Quals;
4253   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4254   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4255 
4256   // C++ [dcl.init.ref]p4:
4257   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4258   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4259   //   T1 is a base class of T2.
4260   DerivedToBase = false;
4261   ObjCConversion = false;
4262   ObjCLifetimeConversion = false;
4263   QualType ConvertedT2;
4264   if (UnqualT1 == UnqualT2) {
4265     // Nothing to do.
4266   } else if (isCompleteType(Loc, OrigT2) &&
4267              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4268              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4269     DerivedToBase = true;
4270   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4271            UnqualT2->isObjCObjectOrInterfaceType() &&
4272            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4273     ObjCConversion = true;
4274   else if (UnqualT2->isFunctionType() &&
4275            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4276     // C++1z [dcl.init.ref]p4:
4277     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4278     //   function" and T1 is "function"
4279     //
4280     // We extend this to also apply to 'noreturn', so allow any function
4281     // conversion between function types.
4282     return Ref_Compatible;
4283   else
4284     return Ref_Incompatible;
4285 
4286   // At this point, we know that T1 and T2 are reference-related (at
4287   // least).
4288 
4289   // If the type is an array type, promote the element qualifiers to the type
4290   // for comparison.
4291   if (isa<ArrayType>(T1) && T1Quals)
4292     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4293   if (isa<ArrayType>(T2) && T2Quals)
4294     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4295 
4296   // C++ [dcl.init.ref]p4:
4297   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4298   //   reference-related to T2 and cv1 is the same cv-qualification
4299   //   as, or greater cv-qualification than, cv2. For purposes of
4300   //   overload resolution, cases for which cv1 is greater
4301   //   cv-qualification than cv2 are identified as
4302   //   reference-compatible with added qualification (see 13.3.3.2).
4303   //
4304   // Note that we also require equivalence of Objective-C GC and address-space
4305   // qualifiers when performing these computations, so that e.g., an int in
4306   // address space 1 is not reference-compatible with an int in address
4307   // space 2.
4308   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4309       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4310     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4311       ObjCLifetimeConversion = true;
4312 
4313     T1Quals.removeObjCLifetime();
4314     T2Quals.removeObjCLifetime();
4315   }
4316 
4317   // MS compiler ignores __unaligned qualifier for references; do the same.
4318   T1Quals.removeUnaligned();
4319   T2Quals.removeUnaligned();
4320 
4321   if (T1Quals.compatiblyIncludes(T2Quals))
4322     return Ref_Compatible;
4323   else
4324     return Ref_Related;
4325 }
4326 
4327 /// Look for a user-defined conversion to a value reference-compatible
4328 ///        with DeclType. Return true if something definite is found.
4329 static bool
4330 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4331                          QualType DeclType, SourceLocation DeclLoc,
4332                          Expr *Init, QualType T2, bool AllowRvalues,
4333                          bool AllowExplicit) {
4334   assert(T2->isRecordType() && "Can only find conversions of record types.");
4335   CXXRecordDecl *T2RecordDecl
4336     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4337 
4338   OverloadCandidateSet CandidateSet(
4339       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4340   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4341   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4342     NamedDecl *D = *I;
4343     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4344     if (isa<UsingShadowDecl>(D))
4345       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4346 
4347     FunctionTemplateDecl *ConvTemplate
4348       = dyn_cast<FunctionTemplateDecl>(D);
4349     CXXConversionDecl *Conv;
4350     if (ConvTemplate)
4351       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4352     else
4353       Conv = cast<CXXConversionDecl>(D);
4354 
4355     // If this is an explicit conversion, and we're not allowed to consider
4356     // explicit conversions, skip it.
4357     if (!AllowExplicit && Conv->isExplicit())
4358       continue;
4359 
4360     if (AllowRvalues) {
4361       bool DerivedToBase = false;
4362       bool ObjCConversion = false;
4363       bool ObjCLifetimeConversion = false;
4364 
4365       // If we are initializing an rvalue reference, don't permit conversion
4366       // functions that return lvalues.
4367       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4368         const ReferenceType *RefType
4369           = Conv->getConversionType()->getAs<LValueReferenceType>();
4370         if (RefType && !RefType->getPointeeType()->isFunctionType())
4371           continue;
4372       }
4373 
4374       if (!ConvTemplate &&
4375           S.CompareReferenceRelationship(
4376             DeclLoc,
4377             Conv->getConversionType().getNonReferenceType()
4378               .getUnqualifiedType(),
4379             DeclType.getNonReferenceType().getUnqualifiedType(),
4380             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4381           Sema::Ref_Incompatible)
4382         continue;
4383     } else {
4384       // If the conversion function doesn't return a reference type,
4385       // it can't be considered for this conversion. An rvalue reference
4386       // is only acceptable if its referencee is a function type.
4387 
4388       const ReferenceType *RefType =
4389         Conv->getConversionType()->getAs<ReferenceType>();
4390       if (!RefType ||
4391           (!RefType->isLValueReferenceType() &&
4392            !RefType->getPointeeType()->isFunctionType()))
4393         continue;
4394     }
4395 
4396     if (ConvTemplate)
4397       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4398                                        Init, DeclType, CandidateSet,
4399                                        /*AllowObjCConversionOnExplicit=*/false);
4400     else
4401       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4402                                DeclType, CandidateSet,
4403                                /*AllowObjCConversionOnExplicit=*/false);
4404   }
4405 
4406   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4407 
4408   OverloadCandidateSet::iterator Best;
4409   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4410   case OR_Success:
4411     // C++ [over.ics.ref]p1:
4412     //
4413     //   [...] If the parameter binds directly to the result of
4414     //   applying a conversion function to the argument
4415     //   expression, the implicit conversion sequence is a
4416     //   user-defined conversion sequence (13.3.3.1.2), with the
4417     //   second standard conversion sequence either an identity
4418     //   conversion or, if the conversion function returns an
4419     //   entity of a type that is a derived class of the parameter
4420     //   type, a derived-to-base Conversion.
4421     if (!Best->FinalConversion.DirectBinding)
4422       return false;
4423 
4424     ICS.setUserDefined();
4425     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4426     ICS.UserDefined.After = Best->FinalConversion;
4427     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4428     ICS.UserDefined.ConversionFunction = Best->Function;
4429     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4430     ICS.UserDefined.EllipsisConversion = false;
4431     assert(ICS.UserDefined.After.ReferenceBinding &&
4432            ICS.UserDefined.After.DirectBinding &&
4433            "Expected a direct reference binding!");
4434     return true;
4435 
4436   case OR_Ambiguous:
4437     ICS.setAmbiguous();
4438     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4439          Cand != CandidateSet.end(); ++Cand)
4440       if (Cand->Viable)
4441         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4442     return true;
4443 
4444   case OR_No_Viable_Function:
4445   case OR_Deleted:
4446     // There was no suitable conversion, or we found a deleted
4447     // conversion; continue with other checks.
4448     return false;
4449   }
4450 
4451   llvm_unreachable("Invalid OverloadResult!");
4452 }
4453 
4454 /// Compute an implicit conversion sequence for reference
4455 /// initialization.
4456 static ImplicitConversionSequence
4457 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4458                  SourceLocation DeclLoc,
4459                  bool SuppressUserConversions,
4460                  bool AllowExplicit) {
4461   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4462 
4463   // Most paths end in a failed conversion.
4464   ImplicitConversionSequence ICS;
4465   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4466 
4467   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4468   QualType T2 = Init->getType();
4469 
4470   // If the initializer is the address of an overloaded function, try
4471   // to resolve the overloaded function. If all goes well, T2 is the
4472   // type of the resulting function.
4473   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4474     DeclAccessPair Found;
4475     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4476                                                                 false, Found))
4477       T2 = Fn->getType();
4478   }
4479 
4480   // Compute some basic properties of the types and the initializer.
4481   bool isRValRef = DeclType->isRValueReferenceType();
4482   bool DerivedToBase = false;
4483   bool ObjCConversion = false;
4484   bool ObjCLifetimeConversion = false;
4485   Expr::Classification InitCategory = Init->Classify(S.Context);
4486   Sema::ReferenceCompareResult RefRelationship
4487     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4488                                      ObjCConversion, ObjCLifetimeConversion);
4489 
4490 
4491   // C++0x [dcl.init.ref]p5:
4492   //   A reference to type "cv1 T1" is initialized by an expression
4493   //   of type "cv2 T2" as follows:
4494 
4495   //     -- If reference is an lvalue reference and the initializer expression
4496   if (!isRValRef) {
4497     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4498     //        reference-compatible with "cv2 T2," or
4499     //
4500     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4501     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4502       // C++ [over.ics.ref]p1:
4503       //   When a parameter of reference type binds directly (8.5.3)
4504       //   to an argument expression, the implicit conversion sequence
4505       //   is the identity conversion, unless the argument expression
4506       //   has a type that is a derived class of the parameter type,
4507       //   in which case the implicit conversion sequence is a
4508       //   derived-to-base Conversion (13.3.3.1).
4509       ICS.setStandard();
4510       ICS.Standard.First = ICK_Identity;
4511       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4512                          : ObjCConversion? ICK_Compatible_Conversion
4513                          : ICK_Identity;
4514       ICS.Standard.Third = ICK_Identity;
4515       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4516       ICS.Standard.setToType(0, T2);
4517       ICS.Standard.setToType(1, T1);
4518       ICS.Standard.setToType(2, T1);
4519       ICS.Standard.ReferenceBinding = true;
4520       ICS.Standard.DirectBinding = true;
4521       ICS.Standard.IsLvalueReference = !isRValRef;
4522       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4523       ICS.Standard.BindsToRvalue = false;
4524       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4525       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4526       ICS.Standard.CopyConstructor = nullptr;
4527       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4528 
4529       // Nothing more to do: the inaccessibility/ambiguity check for
4530       // derived-to-base conversions is suppressed when we're
4531       // computing the implicit conversion sequence (C++
4532       // [over.best.ics]p2).
4533       return ICS;
4534     }
4535 
4536     //       -- has a class type (i.e., T2 is a class type), where T1 is
4537     //          not reference-related to T2, and can be implicitly
4538     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4539     //          is reference-compatible with "cv3 T3" 92) (this
4540     //          conversion is selected by enumerating the applicable
4541     //          conversion functions (13.3.1.6) and choosing the best
4542     //          one through overload resolution (13.3)),
4543     if (!SuppressUserConversions && T2->isRecordType() &&
4544         S.isCompleteType(DeclLoc, T2) &&
4545         RefRelationship == Sema::Ref_Incompatible) {
4546       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4547                                    Init, T2, /*AllowRvalues=*/false,
4548                                    AllowExplicit))
4549         return ICS;
4550     }
4551   }
4552 
4553   //     -- Otherwise, the reference shall be an lvalue reference to a
4554   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4555   //        shall be an rvalue reference.
4556   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4557     return ICS;
4558 
4559   //       -- If the initializer expression
4560   //
4561   //            -- is an xvalue, class prvalue, array prvalue or function
4562   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4563   if (RefRelationship == Sema::Ref_Compatible &&
4564       (InitCategory.isXValue() ||
4565        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4566        (InitCategory.isLValue() && T2->isFunctionType()))) {
4567     ICS.setStandard();
4568     ICS.Standard.First = ICK_Identity;
4569     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4570                       : ObjCConversion? ICK_Compatible_Conversion
4571                       : ICK_Identity;
4572     ICS.Standard.Third = ICK_Identity;
4573     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4574     ICS.Standard.setToType(0, T2);
4575     ICS.Standard.setToType(1, T1);
4576     ICS.Standard.setToType(2, T1);
4577     ICS.Standard.ReferenceBinding = true;
4578     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4579     // binding unless we're binding to a class prvalue.
4580     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4581     // allow the use of rvalue references in C++98/03 for the benefit of
4582     // standard library implementors; therefore, we need the xvalue check here.
4583     ICS.Standard.DirectBinding =
4584       S.getLangOpts().CPlusPlus11 ||
4585       !(InitCategory.isPRValue() || T2->isRecordType());
4586     ICS.Standard.IsLvalueReference = !isRValRef;
4587     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4588     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4589     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4590     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4591     ICS.Standard.CopyConstructor = nullptr;
4592     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4593     return ICS;
4594   }
4595 
4596   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4597   //               reference-related to T2, and can be implicitly converted to
4598   //               an xvalue, class prvalue, or function lvalue of type
4599   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4600   //               "cv3 T3",
4601   //
4602   //          then the reference is bound to the value of the initializer
4603   //          expression in the first case and to the result of the conversion
4604   //          in the second case (or, in either case, to an appropriate base
4605   //          class subobject).
4606   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4607       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4608       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4609                                Init, T2, /*AllowRvalues=*/true,
4610                                AllowExplicit)) {
4611     // In the second case, if the reference is an rvalue reference
4612     // and the second standard conversion sequence of the
4613     // user-defined conversion sequence includes an lvalue-to-rvalue
4614     // conversion, the program is ill-formed.
4615     if (ICS.isUserDefined() && isRValRef &&
4616         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4617       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4618 
4619     return ICS;
4620   }
4621 
4622   // A temporary of function type cannot be created; don't even try.
4623   if (T1->isFunctionType())
4624     return ICS;
4625 
4626   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4627   //          initialized from the initializer expression using the
4628   //          rules for a non-reference copy initialization (8.5). The
4629   //          reference is then bound to the temporary. If T1 is
4630   //          reference-related to T2, cv1 must be the same
4631   //          cv-qualification as, or greater cv-qualification than,
4632   //          cv2; otherwise, the program is ill-formed.
4633   if (RefRelationship == Sema::Ref_Related) {
4634     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4635     // we would be reference-compatible or reference-compatible with
4636     // added qualification. But that wasn't the case, so the reference
4637     // initialization fails.
4638     //
4639     // Note that we only want to check address spaces and cvr-qualifiers here.
4640     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4641     Qualifiers T1Quals = T1.getQualifiers();
4642     Qualifiers T2Quals = T2.getQualifiers();
4643     T1Quals.removeObjCGCAttr();
4644     T1Quals.removeObjCLifetime();
4645     T2Quals.removeObjCGCAttr();
4646     T2Quals.removeObjCLifetime();
4647     // MS compiler ignores __unaligned qualifier for references; do the same.
4648     T1Quals.removeUnaligned();
4649     T2Quals.removeUnaligned();
4650     if (!T1Quals.compatiblyIncludes(T2Quals))
4651       return ICS;
4652   }
4653 
4654   // If at least one of the types is a class type, the types are not
4655   // related, and we aren't allowed any user conversions, the
4656   // reference binding fails. This case is important for breaking
4657   // recursion, since TryImplicitConversion below will attempt to
4658   // create a temporary through the use of a copy constructor.
4659   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4660       (T1->isRecordType() || T2->isRecordType()))
4661     return ICS;
4662 
4663   // If T1 is reference-related to T2 and the reference is an rvalue
4664   // reference, the initializer expression shall not be an lvalue.
4665   if (RefRelationship >= Sema::Ref_Related &&
4666       isRValRef && Init->Classify(S.Context).isLValue())
4667     return ICS;
4668 
4669   // C++ [over.ics.ref]p2:
4670   //   When a parameter of reference type is not bound directly to
4671   //   an argument expression, the conversion sequence is the one
4672   //   required to convert the argument expression to the
4673   //   underlying type of the reference according to
4674   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4675   //   to copy-initializing a temporary of the underlying type with
4676   //   the argument expression. Any difference in top-level
4677   //   cv-qualification is subsumed by the initialization itself
4678   //   and does not constitute a conversion.
4679   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4680                               /*AllowExplicit=*/false,
4681                               /*InOverloadResolution=*/false,
4682                               /*CStyle=*/false,
4683                               /*AllowObjCWritebackConversion=*/false,
4684                               /*AllowObjCConversionOnExplicit=*/false);
4685 
4686   // Of course, that's still a reference binding.
4687   if (ICS.isStandard()) {
4688     ICS.Standard.ReferenceBinding = true;
4689     ICS.Standard.IsLvalueReference = !isRValRef;
4690     ICS.Standard.BindsToFunctionLvalue = false;
4691     ICS.Standard.BindsToRvalue = true;
4692     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4693     ICS.Standard.ObjCLifetimeConversionBinding = false;
4694   } else if (ICS.isUserDefined()) {
4695     const ReferenceType *LValRefType =
4696         ICS.UserDefined.ConversionFunction->getReturnType()
4697             ->getAs<LValueReferenceType>();
4698 
4699     // C++ [over.ics.ref]p3:
4700     //   Except for an implicit object parameter, for which see 13.3.1, a
4701     //   standard conversion sequence cannot be formed if it requires [...]
4702     //   binding an rvalue reference to an lvalue other than a function
4703     //   lvalue.
4704     // Note that the function case is not possible here.
4705     if (DeclType->isRValueReferenceType() && LValRefType) {
4706       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4707       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4708       // reference to an rvalue!
4709       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4710       return ICS;
4711     }
4712 
4713     ICS.UserDefined.After.ReferenceBinding = true;
4714     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4715     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4716     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4717     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4718     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4719   }
4720 
4721   return ICS;
4722 }
4723 
4724 static ImplicitConversionSequence
4725 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4726                       bool SuppressUserConversions,
4727                       bool InOverloadResolution,
4728                       bool AllowObjCWritebackConversion,
4729                       bool AllowExplicit = false);
4730 
4731 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4732 /// initializer list From.
4733 static ImplicitConversionSequence
4734 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4735                   bool SuppressUserConversions,
4736                   bool InOverloadResolution,
4737                   bool AllowObjCWritebackConversion) {
4738   // C++11 [over.ics.list]p1:
4739   //   When an argument is an initializer list, it is not an expression and
4740   //   special rules apply for converting it to a parameter type.
4741 
4742   ImplicitConversionSequence Result;
4743   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4744 
4745   // We need a complete type for what follows. Incomplete types can never be
4746   // initialized from init lists.
4747   if (!S.isCompleteType(From->getLocStart(), ToType))
4748     return Result;
4749 
4750   // Per DR1467:
4751   //   If the parameter type is a class X and the initializer list has a single
4752   //   element of type cv U, where U is X or a class derived from X, the
4753   //   implicit conversion sequence is the one required to convert the element
4754   //   to the parameter type.
4755   //
4756   //   Otherwise, if the parameter type is a character array [... ]
4757   //   and the initializer list has a single element that is an
4758   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4759   //   implicit conversion sequence is the identity conversion.
4760   if (From->getNumInits() == 1) {
4761     if (ToType->isRecordType()) {
4762       QualType InitType = From->getInit(0)->getType();
4763       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4764           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4765         return TryCopyInitialization(S, From->getInit(0), ToType,
4766                                      SuppressUserConversions,
4767                                      InOverloadResolution,
4768                                      AllowObjCWritebackConversion);
4769     }
4770     // FIXME: Check the other conditions here: array of character type,
4771     // initializer is a string literal.
4772     if (ToType->isArrayType()) {
4773       InitializedEntity Entity =
4774         InitializedEntity::InitializeParameter(S.Context, ToType,
4775                                                /*Consumed=*/false);
4776       if (S.CanPerformCopyInitialization(Entity, From)) {
4777         Result.setStandard();
4778         Result.Standard.setAsIdentityConversion();
4779         Result.Standard.setFromType(ToType);
4780         Result.Standard.setAllToTypes(ToType);
4781         return Result;
4782       }
4783     }
4784   }
4785 
4786   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4787   // C++11 [over.ics.list]p2:
4788   //   If the parameter type is std::initializer_list<X> or "array of X" and
4789   //   all the elements can be implicitly converted to X, the implicit
4790   //   conversion sequence is the worst conversion necessary to convert an
4791   //   element of the list to X.
4792   //
4793   // C++14 [over.ics.list]p3:
4794   //   Otherwise, if the parameter type is "array of N X", if the initializer
4795   //   list has exactly N elements or if it has fewer than N elements and X is
4796   //   default-constructible, and if all the elements of the initializer list
4797   //   can be implicitly converted to X, the implicit conversion sequence is
4798   //   the worst conversion necessary to convert an element of the list to X.
4799   //
4800   // FIXME: We're missing a lot of these checks.
4801   bool toStdInitializerList = false;
4802   QualType X;
4803   if (ToType->isArrayType())
4804     X = S.Context.getAsArrayType(ToType)->getElementType();
4805   else
4806     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4807   if (!X.isNull()) {
4808     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4809       Expr *Init = From->getInit(i);
4810       ImplicitConversionSequence ICS =
4811           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4812                                 InOverloadResolution,
4813                                 AllowObjCWritebackConversion);
4814       // If a single element isn't convertible, fail.
4815       if (ICS.isBad()) {
4816         Result = ICS;
4817         break;
4818       }
4819       // Otherwise, look for the worst conversion.
4820       if (Result.isBad() ||
4821           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4822                                              Result) ==
4823               ImplicitConversionSequence::Worse)
4824         Result = ICS;
4825     }
4826 
4827     // For an empty list, we won't have computed any conversion sequence.
4828     // Introduce the identity conversion sequence.
4829     if (From->getNumInits() == 0) {
4830       Result.setStandard();
4831       Result.Standard.setAsIdentityConversion();
4832       Result.Standard.setFromType(ToType);
4833       Result.Standard.setAllToTypes(ToType);
4834     }
4835 
4836     Result.setStdInitializerListElement(toStdInitializerList);
4837     return Result;
4838   }
4839 
4840   // C++14 [over.ics.list]p4:
4841   // C++11 [over.ics.list]p3:
4842   //   Otherwise, if the parameter is a non-aggregate class X and overload
4843   //   resolution chooses a single best constructor [...] the implicit
4844   //   conversion sequence is a user-defined conversion sequence. If multiple
4845   //   constructors are viable but none is better than the others, the
4846   //   implicit conversion sequence is a user-defined conversion sequence.
4847   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4848     // This function can deal with initializer lists.
4849     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4850                                     /*AllowExplicit=*/false,
4851                                     InOverloadResolution, /*CStyle=*/false,
4852                                     AllowObjCWritebackConversion,
4853                                     /*AllowObjCConversionOnExplicit=*/false);
4854   }
4855 
4856   // C++14 [over.ics.list]p5:
4857   // C++11 [over.ics.list]p4:
4858   //   Otherwise, if the parameter has an aggregate type which can be
4859   //   initialized from the initializer list [...] the implicit conversion
4860   //   sequence is a user-defined conversion sequence.
4861   if (ToType->isAggregateType()) {
4862     // Type is an aggregate, argument is an init list. At this point it comes
4863     // down to checking whether the initialization works.
4864     // FIXME: Find out whether this parameter is consumed or not.
4865     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4866     // need to call into the initialization code here; overload resolution
4867     // should not be doing that.
4868     InitializedEntity Entity =
4869         InitializedEntity::InitializeParameter(S.Context, ToType,
4870                                                /*Consumed=*/false);
4871     if (S.CanPerformCopyInitialization(Entity, From)) {
4872       Result.setUserDefined();
4873       Result.UserDefined.Before.setAsIdentityConversion();
4874       // Initializer lists don't have a type.
4875       Result.UserDefined.Before.setFromType(QualType());
4876       Result.UserDefined.Before.setAllToTypes(QualType());
4877 
4878       Result.UserDefined.After.setAsIdentityConversion();
4879       Result.UserDefined.After.setFromType(ToType);
4880       Result.UserDefined.After.setAllToTypes(ToType);
4881       Result.UserDefined.ConversionFunction = nullptr;
4882     }
4883     return Result;
4884   }
4885 
4886   // C++14 [over.ics.list]p6:
4887   // C++11 [over.ics.list]p5:
4888   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4889   if (ToType->isReferenceType()) {
4890     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4891     // mention initializer lists in any way. So we go by what list-
4892     // initialization would do and try to extrapolate from that.
4893 
4894     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4895 
4896     // If the initializer list has a single element that is reference-related
4897     // to the parameter type, we initialize the reference from that.
4898     if (From->getNumInits() == 1) {
4899       Expr *Init = From->getInit(0);
4900 
4901       QualType T2 = Init->getType();
4902 
4903       // If the initializer is the address of an overloaded function, try
4904       // to resolve the overloaded function. If all goes well, T2 is the
4905       // type of the resulting function.
4906       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4907         DeclAccessPair Found;
4908         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4909                                    Init, ToType, false, Found))
4910           T2 = Fn->getType();
4911       }
4912 
4913       // Compute some basic properties of the types and the initializer.
4914       bool dummy1 = false;
4915       bool dummy2 = false;
4916       bool dummy3 = false;
4917       Sema::ReferenceCompareResult RefRelationship
4918         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4919                                          dummy2, dummy3);
4920 
4921       if (RefRelationship >= Sema::Ref_Related) {
4922         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4923                                 SuppressUserConversions,
4924                                 /*AllowExplicit=*/false);
4925       }
4926     }
4927 
4928     // Otherwise, we bind the reference to a temporary created from the
4929     // initializer list.
4930     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4931                                InOverloadResolution,
4932                                AllowObjCWritebackConversion);
4933     if (Result.isFailure())
4934       return Result;
4935     assert(!Result.isEllipsis() &&
4936            "Sub-initialization cannot result in ellipsis conversion.");
4937 
4938     // Can we even bind to a temporary?
4939     if (ToType->isRValueReferenceType() ||
4940         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4941       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4942                                             Result.UserDefined.After;
4943       SCS.ReferenceBinding = true;
4944       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4945       SCS.BindsToRvalue = true;
4946       SCS.BindsToFunctionLvalue = false;
4947       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4948       SCS.ObjCLifetimeConversionBinding = false;
4949     } else
4950       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4951                     From, ToType);
4952     return Result;
4953   }
4954 
4955   // C++14 [over.ics.list]p7:
4956   // C++11 [over.ics.list]p6:
4957   //   Otherwise, if the parameter type is not a class:
4958   if (!ToType->isRecordType()) {
4959     //    - if the initializer list has one element that is not itself an
4960     //      initializer list, the implicit conversion sequence is the one
4961     //      required to convert the element to the parameter type.
4962     unsigned NumInits = From->getNumInits();
4963     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4964       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4965                                      SuppressUserConversions,
4966                                      InOverloadResolution,
4967                                      AllowObjCWritebackConversion);
4968     //    - if the initializer list has no elements, the implicit conversion
4969     //      sequence is the identity conversion.
4970     else if (NumInits == 0) {
4971       Result.setStandard();
4972       Result.Standard.setAsIdentityConversion();
4973       Result.Standard.setFromType(ToType);
4974       Result.Standard.setAllToTypes(ToType);
4975     }
4976     return Result;
4977   }
4978 
4979   // C++14 [over.ics.list]p8:
4980   // C++11 [over.ics.list]p7:
4981   //   In all cases other than those enumerated above, no conversion is possible
4982   return Result;
4983 }
4984 
4985 /// TryCopyInitialization - Try to copy-initialize a value of type
4986 /// ToType from the expression From. Return the implicit conversion
4987 /// sequence required to pass this argument, which may be a bad
4988 /// conversion sequence (meaning that the argument cannot be passed to
4989 /// a parameter of this type). If @p SuppressUserConversions, then we
4990 /// do not permit any user-defined conversion sequences.
4991 static ImplicitConversionSequence
4992 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4993                       bool SuppressUserConversions,
4994                       bool InOverloadResolution,
4995                       bool AllowObjCWritebackConversion,
4996                       bool AllowExplicit) {
4997   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4998     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4999                              InOverloadResolution,AllowObjCWritebackConversion);
5000 
5001   if (ToType->isReferenceType())
5002     return TryReferenceInit(S, From, ToType,
5003                             /*FIXME:*/From->getLocStart(),
5004                             SuppressUserConversions,
5005                             AllowExplicit);
5006 
5007   return TryImplicitConversion(S, From, ToType,
5008                                SuppressUserConversions,
5009                                /*AllowExplicit=*/false,
5010                                InOverloadResolution,
5011                                /*CStyle=*/false,
5012                                AllowObjCWritebackConversion,
5013                                /*AllowObjCConversionOnExplicit=*/false);
5014 }
5015 
5016 static bool TryCopyInitialization(const CanQualType FromQTy,
5017                                   const CanQualType ToQTy,
5018                                   Sema &S,
5019                                   SourceLocation Loc,
5020                                   ExprValueKind FromVK) {
5021   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5022   ImplicitConversionSequence ICS =
5023     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5024 
5025   return !ICS.isBad();
5026 }
5027 
5028 /// TryObjectArgumentInitialization - Try to initialize the object
5029 /// parameter of the given member function (@c Method) from the
5030 /// expression @p From.
5031 static ImplicitConversionSequence
5032 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5033                                 Expr::Classification FromClassification,
5034                                 CXXMethodDecl *Method,
5035                                 CXXRecordDecl *ActingContext) {
5036   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5037   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5038   //                 const volatile object.
5039   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5040     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5041   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5042 
5043   // Set up the conversion sequence as a "bad" conversion, to allow us
5044   // to exit early.
5045   ImplicitConversionSequence ICS;
5046 
5047   // We need to have an object of class type.
5048   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5049     FromType = PT->getPointeeType();
5050 
5051     // When we had a pointer, it's implicitly dereferenced, so we
5052     // better have an lvalue.
5053     assert(FromClassification.isLValue());
5054   }
5055 
5056   assert(FromType->isRecordType());
5057 
5058   // C++0x [over.match.funcs]p4:
5059   //   For non-static member functions, the type of the implicit object
5060   //   parameter is
5061   //
5062   //     - "lvalue reference to cv X" for functions declared without a
5063   //        ref-qualifier or with the & ref-qualifier
5064   //     - "rvalue reference to cv X" for functions declared with the &&
5065   //        ref-qualifier
5066   //
5067   // where X is the class of which the function is a member and cv is the
5068   // cv-qualification on the member function declaration.
5069   //
5070   // However, when finding an implicit conversion sequence for the argument, we
5071   // are not allowed to perform user-defined conversions
5072   // (C++ [over.match.funcs]p5). We perform a simplified version of
5073   // reference binding here, that allows class rvalues to bind to
5074   // non-constant references.
5075 
5076   // First check the qualifiers.
5077   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5078   if (ImplicitParamType.getCVRQualifiers()
5079                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5080       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5081     ICS.setBad(BadConversionSequence::bad_qualifiers,
5082                FromType, ImplicitParamType);
5083     return ICS;
5084   }
5085 
5086   // Check that we have either the same type or a derived type. It
5087   // affects the conversion rank.
5088   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5089   ImplicitConversionKind SecondKind;
5090   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5091     SecondKind = ICK_Identity;
5092   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5093     SecondKind = ICK_Derived_To_Base;
5094   else {
5095     ICS.setBad(BadConversionSequence::unrelated_class,
5096                FromType, ImplicitParamType);
5097     return ICS;
5098   }
5099 
5100   // Check the ref-qualifier.
5101   switch (Method->getRefQualifier()) {
5102   case RQ_None:
5103     // Do nothing; we don't care about lvalueness or rvalueness.
5104     break;
5105 
5106   case RQ_LValue:
5107     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5108       // non-const lvalue reference cannot bind to an rvalue
5109       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5110                  ImplicitParamType);
5111       return ICS;
5112     }
5113     break;
5114 
5115   case RQ_RValue:
5116     if (!FromClassification.isRValue()) {
5117       // rvalue reference cannot bind to an lvalue
5118       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5119                  ImplicitParamType);
5120       return ICS;
5121     }
5122     break;
5123   }
5124 
5125   // Success. Mark this as a reference binding.
5126   ICS.setStandard();
5127   ICS.Standard.setAsIdentityConversion();
5128   ICS.Standard.Second = SecondKind;
5129   ICS.Standard.setFromType(FromType);
5130   ICS.Standard.setAllToTypes(ImplicitParamType);
5131   ICS.Standard.ReferenceBinding = true;
5132   ICS.Standard.DirectBinding = true;
5133   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5134   ICS.Standard.BindsToFunctionLvalue = false;
5135   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5136   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5137     = (Method->getRefQualifier() == RQ_None);
5138   return ICS;
5139 }
5140 
5141 /// PerformObjectArgumentInitialization - Perform initialization of
5142 /// the implicit object parameter for the given Method with the given
5143 /// expression.
5144 ExprResult
5145 Sema::PerformObjectArgumentInitialization(Expr *From,
5146                                           NestedNameSpecifier *Qualifier,
5147                                           NamedDecl *FoundDecl,
5148                                           CXXMethodDecl *Method) {
5149   QualType FromRecordType, DestType;
5150   QualType ImplicitParamRecordType  =
5151     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5152 
5153   Expr::Classification FromClassification;
5154   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5155     FromRecordType = PT->getPointeeType();
5156     DestType = Method->getThisType(Context);
5157     FromClassification = Expr::Classification::makeSimpleLValue();
5158   } else {
5159     FromRecordType = From->getType();
5160     DestType = ImplicitParamRecordType;
5161     FromClassification = From->Classify(Context);
5162   }
5163 
5164   // Note that we always use the true parent context when performing
5165   // the actual argument initialization.
5166   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5167       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5168       Method->getParent());
5169   if (ICS.isBad()) {
5170     switch (ICS.Bad.Kind) {
5171     case BadConversionSequence::bad_qualifiers: {
5172       Qualifiers FromQs = FromRecordType.getQualifiers();
5173       Qualifiers ToQs = DestType.getQualifiers();
5174       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5175       if (CVR) {
5176         Diag(From->getLocStart(),
5177              diag::err_member_function_call_bad_cvr)
5178           << Method->getDeclName() << FromRecordType << (CVR - 1)
5179           << From->getSourceRange();
5180         Diag(Method->getLocation(), diag::note_previous_decl)
5181           << Method->getDeclName();
5182         return ExprError();
5183       }
5184       break;
5185     }
5186 
5187     case BadConversionSequence::lvalue_ref_to_rvalue:
5188     case BadConversionSequence::rvalue_ref_to_lvalue: {
5189       bool IsRValueQualified =
5190         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5191       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5192         << Method->getDeclName() << FromClassification.isRValue()
5193         << IsRValueQualified;
5194       Diag(Method->getLocation(), diag::note_previous_decl)
5195         << Method->getDeclName();
5196       return ExprError();
5197     }
5198 
5199     case BadConversionSequence::no_conversion:
5200     case BadConversionSequence::unrelated_class:
5201       break;
5202     }
5203 
5204     return Diag(From->getLocStart(),
5205                 diag::err_member_function_call_bad_type)
5206        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5207   }
5208 
5209   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5210     ExprResult FromRes =
5211       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5212     if (FromRes.isInvalid())
5213       return ExprError();
5214     From = FromRes.get();
5215   }
5216 
5217   if (!Context.hasSameType(From->getType(), DestType))
5218     From = ImpCastExprToType(From, DestType, CK_NoOp,
5219                              From->getValueKind()).get();
5220   return From;
5221 }
5222 
5223 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5224 /// expression From to bool (C++0x [conv]p3).
5225 static ImplicitConversionSequence
5226 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5227   return TryImplicitConversion(S, From, S.Context.BoolTy,
5228                                /*SuppressUserConversions=*/false,
5229                                /*AllowExplicit=*/true,
5230                                /*InOverloadResolution=*/false,
5231                                /*CStyle=*/false,
5232                                /*AllowObjCWritebackConversion=*/false,
5233                                /*AllowObjCConversionOnExplicit=*/false);
5234 }
5235 
5236 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5237 /// of the expression From to bool (C++0x [conv]p3).
5238 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5239   if (checkPlaceholderForOverload(*this, From))
5240     return ExprError();
5241 
5242   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5243   if (!ICS.isBad())
5244     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5245 
5246   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5247     return Diag(From->getLocStart(),
5248                 diag::err_typecheck_bool_condition)
5249                   << From->getType() << From->getSourceRange();
5250   return ExprError();
5251 }
5252 
5253 /// Check that the specified conversion is permitted in a converted constant
5254 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5255 /// is acceptable.
5256 static bool CheckConvertedConstantConversions(Sema &S,
5257                                               StandardConversionSequence &SCS) {
5258   // Since we know that the target type is an integral or unscoped enumeration
5259   // type, most conversion kinds are impossible. All possible First and Third
5260   // conversions are fine.
5261   switch (SCS.Second) {
5262   case ICK_Identity:
5263   case ICK_Function_Conversion:
5264   case ICK_Integral_Promotion:
5265   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5266   case ICK_Zero_Queue_Conversion:
5267     return true;
5268 
5269   case ICK_Boolean_Conversion:
5270     // Conversion from an integral or unscoped enumeration type to bool is
5271     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5272     // conversion, so we allow it in a converted constant expression.
5273     //
5274     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5275     // a lot of popular code. We should at least add a warning for this
5276     // (non-conforming) extension.
5277     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5278            SCS.getToType(2)->isBooleanType();
5279 
5280   case ICK_Pointer_Conversion:
5281   case ICK_Pointer_Member:
5282     // C++1z: null pointer conversions and null member pointer conversions are
5283     // only permitted if the source type is std::nullptr_t.
5284     return SCS.getFromType()->isNullPtrType();
5285 
5286   case ICK_Floating_Promotion:
5287   case ICK_Complex_Promotion:
5288   case ICK_Floating_Conversion:
5289   case ICK_Complex_Conversion:
5290   case ICK_Floating_Integral:
5291   case ICK_Compatible_Conversion:
5292   case ICK_Derived_To_Base:
5293   case ICK_Vector_Conversion:
5294   case ICK_Vector_Splat:
5295   case ICK_Complex_Real:
5296   case ICK_Block_Pointer_Conversion:
5297   case ICK_TransparentUnionConversion:
5298   case ICK_Writeback_Conversion:
5299   case ICK_Zero_Event_Conversion:
5300   case ICK_C_Only_Conversion:
5301   case ICK_Incompatible_Pointer_Conversion:
5302     return false;
5303 
5304   case ICK_Lvalue_To_Rvalue:
5305   case ICK_Array_To_Pointer:
5306   case ICK_Function_To_Pointer:
5307     llvm_unreachable("found a first conversion kind in Second");
5308 
5309   case ICK_Qualification:
5310     llvm_unreachable("found a third conversion kind in Second");
5311 
5312   case ICK_Num_Conversion_Kinds:
5313     break;
5314   }
5315 
5316   llvm_unreachable("unknown conversion kind");
5317 }
5318 
5319 /// CheckConvertedConstantExpression - Check that the expression From is a
5320 /// converted constant expression of type T, perform the conversion and produce
5321 /// the converted expression, per C++11 [expr.const]p3.
5322 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5323                                                    QualType T, APValue &Value,
5324                                                    Sema::CCEKind CCE,
5325                                                    bool RequireInt) {
5326   assert(S.getLangOpts().CPlusPlus11 &&
5327          "converted constant expression outside C++11");
5328 
5329   if (checkPlaceholderForOverload(S, From))
5330     return ExprError();
5331 
5332   // C++1z [expr.const]p3:
5333   //  A converted constant expression of type T is an expression,
5334   //  implicitly converted to type T, where the converted
5335   //  expression is a constant expression and the implicit conversion
5336   //  sequence contains only [... list of conversions ...].
5337   // C++1z [stmt.if]p2:
5338   //  If the if statement is of the form if constexpr, the value of the
5339   //  condition shall be a contextually converted constant expression of type
5340   //  bool.
5341   ImplicitConversionSequence ICS =
5342       CCE == Sema::CCEK_ConstexprIf
5343           ? TryContextuallyConvertToBool(S, From)
5344           : TryCopyInitialization(S, From, T,
5345                                   /*SuppressUserConversions=*/false,
5346                                   /*InOverloadResolution=*/false,
5347                                   /*AllowObjcWritebackConversion=*/false,
5348                                   /*AllowExplicit=*/false);
5349   StandardConversionSequence *SCS = nullptr;
5350   switch (ICS.getKind()) {
5351   case ImplicitConversionSequence::StandardConversion:
5352     SCS = &ICS.Standard;
5353     break;
5354   case ImplicitConversionSequence::UserDefinedConversion:
5355     // We are converting to a non-class type, so the Before sequence
5356     // must be trivial.
5357     SCS = &ICS.UserDefined.After;
5358     break;
5359   case ImplicitConversionSequence::AmbiguousConversion:
5360   case ImplicitConversionSequence::BadConversion:
5361     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5362       return S.Diag(From->getLocStart(),
5363                     diag::err_typecheck_converted_constant_expression)
5364                 << From->getType() << From->getSourceRange() << T;
5365     return ExprError();
5366 
5367   case ImplicitConversionSequence::EllipsisConversion:
5368     llvm_unreachable("ellipsis conversion in converted constant expression");
5369   }
5370 
5371   // Check that we would only use permitted conversions.
5372   if (!CheckConvertedConstantConversions(S, *SCS)) {
5373     return S.Diag(From->getLocStart(),
5374                   diag::err_typecheck_converted_constant_expression_disallowed)
5375              << From->getType() << From->getSourceRange() << T;
5376   }
5377   // [...] and where the reference binding (if any) binds directly.
5378   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5379     return S.Diag(From->getLocStart(),
5380                   diag::err_typecheck_converted_constant_expression_indirect)
5381              << From->getType() << From->getSourceRange() << T;
5382   }
5383 
5384   ExprResult Result =
5385       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5386   if (Result.isInvalid())
5387     return Result;
5388 
5389   // Check for a narrowing implicit conversion.
5390   APValue PreNarrowingValue;
5391   QualType PreNarrowingType;
5392   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5393                                 PreNarrowingType)) {
5394   case NK_Dependent_Narrowing:
5395     // Implicit conversion to a narrower type, but the expression is
5396     // value-dependent so we can't tell whether it's actually narrowing.
5397   case NK_Variable_Narrowing:
5398     // Implicit conversion to a narrower type, and the value is not a constant
5399     // expression. We'll diagnose this in a moment.
5400   case NK_Not_Narrowing:
5401     break;
5402 
5403   case NK_Constant_Narrowing:
5404     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5405       << CCE << /*Constant*/1
5406       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5407     break;
5408 
5409   case NK_Type_Narrowing:
5410     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5411       << CCE << /*Constant*/0 << From->getType() << T;
5412     break;
5413   }
5414 
5415   if (Result.get()->isValueDependent()) {
5416     Value = APValue();
5417     return Result;
5418   }
5419 
5420   // Check the expression is a constant expression.
5421   SmallVector<PartialDiagnosticAt, 8> Notes;
5422   Expr::EvalResult Eval;
5423   Eval.Diag = &Notes;
5424   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5425                                    ? Expr::EvaluateForMangling
5426                                    : Expr::EvaluateForCodeGen;
5427 
5428   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5429       (RequireInt && !Eval.Val.isInt())) {
5430     // The expression can't be folded, so we can't keep it at this position in
5431     // the AST.
5432     Result = ExprError();
5433   } else {
5434     Value = Eval.Val;
5435 
5436     if (Notes.empty()) {
5437       // It's a constant expression.
5438       return Result;
5439     }
5440   }
5441 
5442   // It's not a constant expression. Produce an appropriate diagnostic.
5443   if (Notes.size() == 1 &&
5444       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5445     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5446   else {
5447     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5448       << CCE << From->getSourceRange();
5449     for (unsigned I = 0; I < Notes.size(); ++I)
5450       S.Diag(Notes[I].first, Notes[I].second);
5451   }
5452   return ExprError();
5453 }
5454 
5455 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5456                                                   APValue &Value, CCEKind CCE) {
5457   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5458 }
5459 
5460 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5461                                                   llvm::APSInt &Value,
5462                                                   CCEKind CCE) {
5463   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5464 
5465   APValue V;
5466   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5467   if (!R.isInvalid() && !R.get()->isValueDependent())
5468     Value = V.getInt();
5469   return R;
5470 }
5471 
5472 
5473 /// dropPointerConversions - If the given standard conversion sequence
5474 /// involves any pointer conversions, remove them.  This may change
5475 /// the result type of the conversion sequence.
5476 static void dropPointerConversion(StandardConversionSequence &SCS) {
5477   if (SCS.Second == ICK_Pointer_Conversion) {
5478     SCS.Second = ICK_Identity;
5479     SCS.Third = ICK_Identity;
5480     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5481   }
5482 }
5483 
5484 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5485 /// convert the expression From to an Objective-C pointer type.
5486 static ImplicitConversionSequence
5487 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5488   // Do an implicit conversion to 'id'.
5489   QualType Ty = S.Context.getObjCIdType();
5490   ImplicitConversionSequence ICS
5491     = TryImplicitConversion(S, From, Ty,
5492                             // FIXME: Are these flags correct?
5493                             /*SuppressUserConversions=*/false,
5494                             /*AllowExplicit=*/true,
5495                             /*InOverloadResolution=*/false,
5496                             /*CStyle=*/false,
5497                             /*AllowObjCWritebackConversion=*/false,
5498                             /*AllowObjCConversionOnExplicit=*/true);
5499 
5500   // Strip off any final conversions to 'id'.
5501   switch (ICS.getKind()) {
5502   case ImplicitConversionSequence::BadConversion:
5503   case ImplicitConversionSequence::AmbiguousConversion:
5504   case ImplicitConversionSequence::EllipsisConversion:
5505     break;
5506 
5507   case ImplicitConversionSequence::UserDefinedConversion:
5508     dropPointerConversion(ICS.UserDefined.After);
5509     break;
5510 
5511   case ImplicitConversionSequence::StandardConversion:
5512     dropPointerConversion(ICS.Standard);
5513     break;
5514   }
5515 
5516   return ICS;
5517 }
5518 
5519 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5520 /// conversion of the expression From to an Objective-C pointer type.
5521 /// Returns a valid but null ExprResult if no conversion sequence exists.
5522 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5523   if (checkPlaceholderForOverload(*this, From))
5524     return ExprError();
5525 
5526   QualType Ty = Context.getObjCIdType();
5527   ImplicitConversionSequence ICS =
5528     TryContextuallyConvertToObjCPointer(*this, From);
5529   if (!ICS.isBad())
5530     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5531   return ExprResult();
5532 }
5533 
5534 /// Determine whether the provided type is an integral type, or an enumeration
5535 /// type of a permitted flavor.
5536 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5537   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5538                                  : T->isIntegralOrUnscopedEnumerationType();
5539 }
5540 
5541 static ExprResult
5542 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5543                             Sema::ContextualImplicitConverter &Converter,
5544                             QualType T, UnresolvedSetImpl &ViableConversions) {
5545 
5546   if (Converter.Suppress)
5547     return ExprError();
5548 
5549   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5550   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5551     CXXConversionDecl *Conv =
5552         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5553     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5554     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5555   }
5556   return From;
5557 }
5558 
5559 static bool
5560 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5561                            Sema::ContextualImplicitConverter &Converter,
5562                            QualType T, bool HadMultipleCandidates,
5563                            UnresolvedSetImpl &ExplicitConversions) {
5564   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5565     DeclAccessPair Found = ExplicitConversions[0];
5566     CXXConversionDecl *Conversion =
5567         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5568 
5569     // The user probably meant to invoke the given explicit
5570     // conversion; use it.
5571     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5572     std::string TypeStr;
5573     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5574 
5575     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5576         << FixItHint::CreateInsertion(From->getLocStart(),
5577                                       "static_cast<" + TypeStr + ">(")
5578         << FixItHint::CreateInsertion(
5579                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5580     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5581 
5582     // If we aren't in a SFINAE context, build a call to the
5583     // explicit conversion function.
5584     if (SemaRef.isSFINAEContext())
5585       return true;
5586 
5587     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5588     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5589                                                        HadMultipleCandidates);
5590     if (Result.isInvalid())
5591       return true;
5592     // Record usage of conversion in an implicit cast.
5593     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5594                                     CK_UserDefinedConversion, Result.get(),
5595                                     nullptr, Result.get()->getValueKind());
5596   }
5597   return false;
5598 }
5599 
5600 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5601                              Sema::ContextualImplicitConverter &Converter,
5602                              QualType T, bool HadMultipleCandidates,
5603                              DeclAccessPair &Found) {
5604   CXXConversionDecl *Conversion =
5605       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5606   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5607 
5608   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5609   if (!Converter.SuppressConversion) {
5610     if (SemaRef.isSFINAEContext())
5611       return true;
5612 
5613     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5614         << From->getSourceRange();
5615   }
5616 
5617   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5618                                                      HadMultipleCandidates);
5619   if (Result.isInvalid())
5620     return true;
5621   // Record usage of conversion in an implicit cast.
5622   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5623                                   CK_UserDefinedConversion, Result.get(),
5624                                   nullptr, Result.get()->getValueKind());
5625   return false;
5626 }
5627 
5628 static ExprResult finishContextualImplicitConversion(
5629     Sema &SemaRef, SourceLocation Loc, Expr *From,
5630     Sema::ContextualImplicitConverter &Converter) {
5631   if (!Converter.match(From->getType()) && !Converter.Suppress)
5632     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5633         << From->getSourceRange();
5634 
5635   return SemaRef.DefaultLvalueConversion(From);
5636 }
5637 
5638 static void
5639 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5640                                   UnresolvedSetImpl &ViableConversions,
5641                                   OverloadCandidateSet &CandidateSet) {
5642   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5643     DeclAccessPair FoundDecl = ViableConversions[I];
5644     NamedDecl *D = FoundDecl.getDecl();
5645     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5646     if (isa<UsingShadowDecl>(D))
5647       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5648 
5649     CXXConversionDecl *Conv;
5650     FunctionTemplateDecl *ConvTemplate;
5651     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5652       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5653     else
5654       Conv = cast<CXXConversionDecl>(D);
5655 
5656     if (ConvTemplate)
5657       SemaRef.AddTemplateConversionCandidate(
5658         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5659         /*AllowObjCConversionOnExplicit=*/false);
5660     else
5661       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5662                                      ToType, CandidateSet,
5663                                      /*AllowObjCConversionOnExplicit=*/false);
5664   }
5665 }
5666 
5667 /// Attempt to convert the given expression to a type which is accepted
5668 /// by the given converter.
5669 ///
5670 /// This routine will attempt to convert an expression of class type to a
5671 /// type accepted by the specified converter. In C++11 and before, the class
5672 /// must have a single non-explicit conversion function converting to a matching
5673 /// type. In C++1y, there can be multiple such conversion functions, but only
5674 /// one target type.
5675 ///
5676 /// \param Loc The source location of the construct that requires the
5677 /// conversion.
5678 ///
5679 /// \param From The expression we're converting from.
5680 ///
5681 /// \param Converter Used to control and diagnose the conversion process.
5682 ///
5683 /// \returns The expression, converted to an integral or enumeration type if
5684 /// successful.
5685 ExprResult Sema::PerformContextualImplicitConversion(
5686     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5687   // We can't perform any more checking for type-dependent expressions.
5688   if (From->isTypeDependent())
5689     return From;
5690 
5691   // Process placeholders immediately.
5692   if (From->hasPlaceholderType()) {
5693     ExprResult result = CheckPlaceholderExpr(From);
5694     if (result.isInvalid())
5695       return result;
5696     From = result.get();
5697   }
5698 
5699   // If the expression already has a matching type, we're golden.
5700   QualType T = From->getType();
5701   if (Converter.match(T))
5702     return DefaultLvalueConversion(From);
5703 
5704   // FIXME: Check for missing '()' if T is a function type?
5705 
5706   // We can only perform contextual implicit conversions on objects of class
5707   // type.
5708   const RecordType *RecordTy = T->getAs<RecordType>();
5709   if (!RecordTy || !getLangOpts().CPlusPlus) {
5710     if (!Converter.Suppress)
5711       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5712     return From;
5713   }
5714 
5715   // We must have a complete class type.
5716   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5717     ContextualImplicitConverter &Converter;
5718     Expr *From;
5719 
5720     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5721         : Converter(Converter), From(From) {}
5722 
5723     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5724       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5725     }
5726   } IncompleteDiagnoser(Converter, From);
5727 
5728   if (Converter.Suppress ? !isCompleteType(Loc, T)
5729                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5730     return From;
5731 
5732   // Look for a conversion to an integral or enumeration type.
5733   UnresolvedSet<4>
5734       ViableConversions; // These are *potentially* viable in C++1y.
5735   UnresolvedSet<4> ExplicitConversions;
5736   const auto &Conversions =
5737       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5738 
5739   bool HadMultipleCandidates =
5740       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5741 
5742   // To check that there is only one target type, in C++1y:
5743   QualType ToType;
5744   bool HasUniqueTargetType = true;
5745 
5746   // Collect explicit or viable (potentially in C++1y) conversions.
5747   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5748     NamedDecl *D = (*I)->getUnderlyingDecl();
5749     CXXConversionDecl *Conversion;
5750     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5751     if (ConvTemplate) {
5752       if (getLangOpts().CPlusPlus14)
5753         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5754       else
5755         continue; // C++11 does not consider conversion operator templates(?).
5756     } else
5757       Conversion = cast<CXXConversionDecl>(D);
5758 
5759     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5760            "Conversion operator templates are considered potentially "
5761            "viable in C++1y");
5762 
5763     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5764     if (Converter.match(CurToType) || ConvTemplate) {
5765 
5766       if (Conversion->isExplicit()) {
5767         // FIXME: For C++1y, do we need this restriction?
5768         // cf. diagnoseNoViableConversion()
5769         if (!ConvTemplate)
5770           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5771       } else {
5772         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5773           if (ToType.isNull())
5774             ToType = CurToType.getUnqualifiedType();
5775           else if (HasUniqueTargetType &&
5776                    (CurToType.getUnqualifiedType() != ToType))
5777             HasUniqueTargetType = false;
5778         }
5779         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5780       }
5781     }
5782   }
5783 
5784   if (getLangOpts().CPlusPlus14) {
5785     // C++1y [conv]p6:
5786     // ... An expression e of class type E appearing in such a context
5787     // is said to be contextually implicitly converted to a specified
5788     // type T and is well-formed if and only if e can be implicitly
5789     // converted to a type T that is determined as follows: E is searched
5790     // for conversion functions whose return type is cv T or reference to
5791     // cv T such that T is allowed by the context. There shall be
5792     // exactly one such T.
5793 
5794     // If no unique T is found:
5795     if (ToType.isNull()) {
5796       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5797                                      HadMultipleCandidates,
5798                                      ExplicitConversions))
5799         return ExprError();
5800       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5801     }
5802 
5803     // If more than one unique Ts are found:
5804     if (!HasUniqueTargetType)
5805       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5806                                          ViableConversions);
5807 
5808     // If one unique T is found:
5809     // First, build a candidate set from the previously recorded
5810     // potentially viable conversions.
5811     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5812     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5813                                       CandidateSet);
5814 
5815     // Then, perform overload resolution over the candidate set.
5816     OverloadCandidateSet::iterator Best;
5817     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5818     case OR_Success: {
5819       // Apply this conversion.
5820       DeclAccessPair Found =
5821           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5822       if (recordConversion(*this, Loc, From, Converter, T,
5823                            HadMultipleCandidates, Found))
5824         return ExprError();
5825       break;
5826     }
5827     case OR_Ambiguous:
5828       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5829                                          ViableConversions);
5830     case OR_No_Viable_Function:
5831       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5832                                      HadMultipleCandidates,
5833                                      ExplicitConversions))
5834         return ExprError();
5835       LLVM_FALLTHROUGH;
5836     case OR_Deleted:
5837       // We'll complain below about a non-integral condition type.
5838       break;
5839     }
5840   } else {
5841     switch (ViableConversions.size()) {
5842     case 0: {
5843       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5844                                      HadMultipleCandidates,
5845                                      ExplicitConversions))
5846         return ExprError();
5847 
5848       // We'll complain below about a non-integral condition type.
5849       break;
5850     }
5851     case 1: {
5852       // Apply this conversion.
5853       DeclAccessPair Found = ViableConversions[0];
5854       if (recordConversion(*this, Loc, From, Converter, T,
5855                            HadMultipleCandidates, Found))
5856         return ExprError();
5857       break;
5858     }
5859     default:
5860       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5861                                          ViableConversions);
5862     }
5863   }
5864 
5865   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5866 }
5867 
5868 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5869 /// an acceptable non-member overloaded operator for a call whose
5870 /// arguments have types T1 (and, if non-empty, T2). This routine
5871 /// implements the check in C++ [over.match.oper]p3b2 concerning
5872 /// enumeration types.
5873 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5874                                                    FunctionDecl *Fn,
5875                                                    ArrayRef<Expr *> Args) {
5876   QualType T1 = Args[0]->getType();
5877   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5878 
5879   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5880     return true;
5881 
5882   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5883     return true;
5884 
5885   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5886   if (Proto->getNumParams() < 1)
5887     return false;
5888 
5889   if (T1->isEnumeralType()) {
5890     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5891     if (Context.hasSameUnqualifiedType(T1, ArgType))
5892       return true;
5893   }
5894 
5895   if (Proto->getNumParams() < 2)
5896     return false;
5897 
5898   if (!T2.isNull() && T2->isEnumeralType()) {
5899     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5900     if (Context.hasSameUnqualifiedType(T2, ArgType))
5901       return true;
5902   }
5903 
5904   return false;
5905 }
5906 
5907 /// AddOverloadCandidate - Adds the given function to the set of
5908 /// candidate functions, using the given function call arguments.  If
5909 /// @p SuppressUserConversions, then don't allow user-defined
5910 /// conversions via constructors or conversion operators.
5911 ///
5912 /// \param PartialOverloading true if we are performing "partial" overloading
5913 /// based on an incomplete set of function arguments. This feature is used by
5914 /// code completion.
5915 void
5916 Sema::AddOverloadCandidate(FunctionDecl *Function,
5917                            DeclAccessPair FoundDecl,
5918                            ArrayRef<Expr *> Args,
5919                            OverloadCandidateSet &CandidateSet,
5920                            bool SuppressUserConversions,
5921                            bool PartialOverloading,
5922                            bool AllowExplicit,
5923                            ConversionSequenceList EarlyConversions) {
5924   const FunctionProtoType *Proto
5925     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5926   assert(Proto && "Functions without a prototype cannot be overloaded");
5927   assert(!Function->getDescribedFunctionTemplate() &&
5928          "Use AddTemplateOverloadCandidate for function templates");
5929 
5930   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5931     if (!isa<CXXConstructorDecl>(Method)) {
5932       // If we get here, it's because we're calling a member function
5933       // that is named without a member access expression (e.g.,
5934       // "this->f") that was either written explicitly or created
5935       // implicitly. This can happen with a qualified call to a member
5936       // function, e.g., X::f(). We use an empty type for the implied
5937       // object argument (C++ [over.call.func]p3), and the acting context
5938       // is irrelevant.
5939       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5940                          Expr::Classification::makeSimpleLValue(), Args,
5941                          CandidateSet, SuppressUserConversions,
5942                          PartialOverloading, EarlyConversions);
5943       return;
5944     }
5945     // We treat a constructor like a non-member function, since its object
5946     // argument doesn't participate in overload resolution.
5947   }
5948 
5949   if (!CandidateSet.isNewCandidate(Function))
5950     return;
5951 
5952   // C++ [over.match.oper]p3:
5953   //   if no operand has a class type, only those non-member functions in the
5954   //   lookup set that have a first parameter of type T1 or "reference to
5955   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5956   //   is a right operand) a second parameter of type T2 or "reference to
5957   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5958   //   candidate functions.
5959   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5960       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5961     return;
5962 
5963   // C++11 [class.copy]p11: [DR1402]
5964   //   A defaulted move constructor that is defined as deleted is ignored by
5965   //   overload resolution.
5966   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5967   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5968       Constructor->isMoveConstructor())
5969     return;
5970 
5971   // Overload resolution is always an unevaluated context.
5972   EnterExpressionEvaluationContext Unevaluated(
5973       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5974 
5975   // Add this candidate
5976   OverloadCandidate &Candidate =
5977       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5978   Candidate.FoundDecl = FoundDecl;
5979   Candidate.Function = Function;
5980   Candidate.Viable = true;
5981   Candidate.IsSurrogate = false;
5982   Candidate.IgnoreObjectArgument = false;
5983   Candidate.ExplicitCallArguments = Args.size();
5984 
5985   if (Function->isMultiVersion() &&
5986       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5987     Candidate.Viable = false;
5988     Candidate.FailureKind = ovl_non_default_multiversion_function;
5989     return;
5990   }
5991 
5992   if (Constructor) {
5993     // C++ [class.copy]p3:
5994     //   A member function template is never instantiated to perform the copy
5995     //   of a class object to an object of its class type.
5996     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5997     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5998         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5999          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
6000                        ClassType))) {
6001       Candidate.Viable = false;
6002       Candidate.FailureKind = ovl_fail_illegal_constructor;
6003       return;
6004     }
6005 
6006     // C++ [over.match.funcs]p8: (proposed DR resolution)
6007     //   A constructor inherited from class type C that has a first parameter
6008     //   of type "reference to P" (including such a constructor instantiated
6009     //   from a template) is excluded from the set of candidate functions when
6010     //   constructing an object of type cv D if the argument list has exactly
6011     //   one argument and D is reference-related to P and P is reference-related
6012     //   to C.
6013     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6014     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6015         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6016       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6017       QualType C = Context.getRecordType(Constructor->getParent());
6018       QualType D = Context.getRecordType(Shadow->getParent());
6019       SourceLocation Loc = Args.front()->getExprLoc();
6020       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6021           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6022         Candidate.Viable = false;
6023         Candidate.FailureKind = ovl_fail_inhctor_slice;
6024         return;
6025       }
6026     }
6027   }
6028 
6029   unsigned NumParams = Proto->getNumParams();
6030 
6031   // (C++ 13.3.2p2): A candidate function having fewer than m
6032   // parameters is viable only if it has an ellipsis in its parameter
6033   // list (8.3.5).
6034   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6035       !Proto->isVariadic()) {
6036     Candidate.Viable = false;
6037     Candidate.FailureKind = ovl_fail_too_many_arguments;
6038     return;
6039   }
6040 
6041   // (C++ 13.3.2p2): A candidate function having more than m parameters
6042   // is viable only if the (m+1)st parameter has a default argument
6043   // (8.3.6). For the purposes of overload resolution, the
6044   // parameter list is truncated on the right, so that there are
6045   // exactly m parameters.
6046   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6047   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6048     // Not enough arguments.
6049     Candidate.Viable = false;
6050     Candidate.FailureKind = ovl_fail_too_few_arguments;
6051     return;
6052   }
6053 
6054   // (CUDA B.1): Check for invalid calls between targets.
6055   if (getLangOpts().CUDA)
6056     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6057       // Skip the check for callers that are implicit members, because in this
6058       // case we may not yet know what the member's target is; the target is
6059       // inferred for the member automatically, based on the bases and fields of
6060       // the class.
6061       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6062         Candidate.Viable = false;
6063         Candidate.FailureKind = ovl_fail_bad_target;
6064         return;
6065       }
6066 
6067   // Determine the implicit conversion sequences for each of the
6068   // arguments.
6069   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6070     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6071       // We already formed a conversion sequence for this parameter during
6072       // template argument deduction.
6073     } else if (ArgIdx < NumParams) {
6074       // (C++ 13.3.2p3): for F to be a viable function, there shall
6075       // exist for each argument an implicit conversion sequence
6076       // (13.3.3.1) that converts that argument to the corresponding
6077       // parameter of F.
6078       QualType ParamType = Proto->getParamType(ArgIdx);
6079       Candidate.Conversions[ArgIdx]
6080         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6081                                 SuppressUserConversions,
6082                                 /*InOverloadResolution=*/true,
6083                                 /*AllowObjCWritebackConversion=*/
6084                                   getLangOpts().ObjCAutoRefCount,
6085                                 AllowExplicit);
6086       if (Candidate.Conversions[ArgIdx].isBad()) {
6087         Candidate.Viable = false;
6088         Candidate.FailureKind = ovl_fail_bad_conversion;
6089         return;
6090       }
6091     } else {
6092       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6093       // argument for which there is no corresponding parameter is
6094       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6095       Candidate.Conversions[ArgIdx].setEllipsis();
6096     }
6097   }
6098 
6099   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6100     Candidate.Viable = false;
6101     Candidate.FailureKind = ovl_fail_enable_if;
6102     Candidate.DeductionFailure.Data = FailedAttr;
6103     return;
6104   }
6105 
6106   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6107     Candidate.Viable = false;
6108     Candidate.FailureKind = ovl_fail_ext_disabled;
6109     return;
6110   }
6111 }
6112 
6113 ObjCMethodDecl *
6114 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6115                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6116   if (Methods.size() <= 1)
6117     return nullptr;
6118 
6119   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6120     bool Match = true;
6121     ObjCMethodDecl *Method = Methods[b];
6122     unsigned NumNamedArgs = Sel.getNumArgs();
6123     // Method might have more arguments than selector indicates. This is due
6124     // to addition of c-style arguments in method.
6125     if (Method->param_size() > NumNamedArgs)
6126       NumNamedArgs = Method->param_size();
6127     if (Args.size() < NumNamedArgs)
6128       continue;
6129 
6130     for (unsigned i = 0; i < NumNamedArgs; i++) {
6131       // We can't do any type-checking on a type-dependent argument.
6132       if (Args[i]->isTypeDependent()) {
6133         Match = false;
6134         break;
6135       }
6136 
6137       ParmVarDecl *param = Method->parameters()[i];
6138       Expr *argExpr = Args[i];
6139       assert(argExpr && "SelectBestMethod(): missing expression");
6140 
6141       // Strip the unbridged-cast placeholder expression off unless it's
6142       // a consumed argument.
6143       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6144           !param->hasAttr<CFConsumedAttr>())
6145         argExpr = stripARCUnbridgedCast(argExpr);
6146 
6147       // If the parameter is __unknown_anytype, move on to the next method.
6148       if (param->getType() == Context.UnknownAnyTy) {
6149         Match = false;
6150         break;
6151       }
6152 
6153       ImplicitConversionSequence ConversionState
6154         = TryCopyInitialization(*this, argExpr, param->getType(),
6155                                 /*SuppressUserConversions*/false,
6156                                 /*InOverloadResolution=*/true,
6157                                 /*AllowObjCWritebackConversion=*/
6158                                 getLangOpts().ObjCAutoRefCount,
6159                                 /*AllowExplicit*/false);
6160       // This function looks for a reasonably-exact match, so we consider
6161       // incompatible pointer conversions to be a failure here.
6162       if (ConversionState.isBad() ||
6163           (ConversionState.isStandard() &&
6164            ConversionState.Standard.Second ==
6165                ICK_Incompatible_Pointer_Conversion)) {
6166         Match = false;
6167         break;
6168       }
6169     }
6170     // Promote additional arguments to variadic methods.
6171     if (Match && Method->isVariadic()) {
6172       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6173         if (Args[i]->isTypeDependent()) {
6174           Match = false;
6175           break;
6176         }
6177         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6178                                                           nullptr);
6179         if (Arg.isInvalid()) {
6180           Match = false;
6181           break;
6182         }
6183       }
6184     } else {
6185       // Check for extra arguments to non-variadic methods.
6186       if (Args.size() != NumNamedArgs)
6187         Match = false;
6188       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6189         // Special case when selectors have no argument. In this case, select
6190         // one with the most general result type of 'id'.
6191         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6192           QualType ReturnT = Methods[b]->getReturnType();
6193           if (ReturnT->isObjCIdType())
6194             return Methods[b];
6195         }
6196       }
6197     }
6198 
6199     if (Match)
6200       return Method;
6201   }
6202   return nullptr;
6203 }
6204 
6205 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6206 // enable_if is order-sensitive. As a result, we need to reverse things
6207 // sometimes. Size of 4 elements is arbitrary.
6208 static SmallVector<EnableIfAttr *, 4>
6209 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6210   SmallVector<EnableIfAttr *, 4> Result;
6211   if (!Function->hasAttrs())
6212     return Result;
6213 
6214   const auto &FuncAttrs = Function->getAttrs();
6215   for (Attr *Attr : FuncAttrs)
6216     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6217       Result.push_back(EnableIf);
6218 
6219   std::reverse(Result.begin(), Result.end());
6220   return Result;
6221 }
6222 
6223 static bool
6224 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6225                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6226                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6227                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6228   if (ThisArg) {
6229     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6230     assert(!isa<CXXConstructorDecl>(Method) &&
6231            "Shouldn't have `this` for ctors!");
6232     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6233     ExprResult R = S.PerformObjectArgumentInitialization(
6234         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6235     if (R.isInvalid())
6236       return false;
6237     ConvertedThis = R.get();
6238   } else {
6239     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6240       (void)MD;
6241       assert((MissingImplicitThis || MD->isStatic() ||
6242               isa<CXXConstructorDecl>(MD)) &&
6243              "Expected `this` for non-ctor instance methods");
6244     }
6245     ConvertedThis = nullptr;
6246   }
6247 
6248   // Ignore any variadic arguments. Converting them is pointless, since the
6249   // user can't refer to them in the function condition.
6250   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6251 
6252   // Convert the arguments.
6253   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6254     ExprResult R;
6255     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6256                                         S.Context, Function->getParamDecl(I)),
6257                                     SourceLocation(), Args[I]);
6258 
6259     if (R.isInvalid())
6260       return false;
6261 
6262     ConvertedArgs.push_back(R.get());
6263   }
6264 
6265   if (Trap.hasErrorOccurred())
6266     return false;
6267 
6268   // Push default arguments if needed.
6269   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6270     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6271       ParmVarDecl *P = Function->getParamDecl(i);
6272       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6273                          ? P->getUninstantiatedDefaultArg()
6274                          : P->getDefaultArg();
6275       // This can only happen in code completion, i.e. when PartialOverloading
6276       // is true.
6277       if (!DefArg)
6278         return false;
6279       ExprResult R =
6280           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6281                                           S.Context, Function->getParamDecl(i)),
6282                                       SourceLocation(), DefArg);
6283       if (R.isInvalid())
6284         return false;
6285       ConvertedArgs.push_back(R.get());
6286     }
6287 
6288     if (Trap.hasErrorOccurred())
6289       return false;
6290   }
6291   return true;
6292 }
6293 
6294 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6295                                   bool MissingImplicitThis) {
6296   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6297       getOrderedEnableIfAttrs(Function);
6298   if (EnableIfAttrs.empty())
6299     return nullptr;
6300 
6301   SFINAETrap Trap(*this);
6302   SmallVector<Expr *, 16> ConvertedArgs;
6303   // FIXME: We should look into making enable_if late-parsed.
6304   Expr *DiscardedThis;
6305   if (!convertArgsForAvailabilityChecks(
6306           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6307           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6308     return EnableIfAttrs[0];
6309 
6310   for (auto *EIA : EnableIfAttrs) {
6311     APValue Result;
6312     // FIXME: This doesn't consider value-dependent cases, because doing so is
6313     // very difficult. Ideally, we should handle them more gracefully.
6314     if (!EIA->getCond()->EvaluateWithSubstitution(
6315             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6316       return EIA;
6317 
6318     if (!Result.isInt() || !Result.getInt().getBoolValue())
6319       return EIA;
6320   }
6321   return nullptr;
6322 }
6323 
6324 template <typename CheckFn>
6325 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6326                                         bool ArgDependent, SourceLocation Loc,
6327                                         CheckFn &&IsSuccessful) {
6328   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6329   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6330     if (ArgDependent == DIA->getArgDependent())
6331       Attrs.push_back(DIA);
6332   }
6333 
6334   // Common case: No diagnose_if attributes, so we can quit early.
6335   if (Attrs.empty())
6336     return false;
6337 
6338   auto WarningBegin = std::stable_partition(
6339       Attrs.begin(), Attrs.end(),
6340       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6341 
6342   // Note that diagnose_if attributes are late-parsed, so they appear in the
6343   // correct order (unlike enable_if attributes).
6344   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6345                                IsSuccessful);
6346   if (ErrAttr != WarningBegin) {
6347     const DiagnoseIfAttr *DIA = *ErrAttr;
6348     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6349     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6350         << DIA->getParent() << DIA->getCond()->getSourceRange();
6351     return true;
6352   }
6353 
6354   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6355     if (IsSuccessful(DIA)) {
6356       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6357       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6358           << DIA->getParent() << DIA->getCond()->getSourceRange();
6359     }
6360 
6361   return false;
6362 }
6363 
6364 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6365                                                const Expr *ThisArg,
6366                                                ArrayRef<const Expr *> Args,
6367                                                SourceLocation Loc) {
6368   return diagnoseDiagnoseIfAttrsWith(
6369       *this, Function, /*ArgDependent=*/true, Loc,
6370       [&](const DiagnoseIfAttr *DIA) {
6371         APValue Result;
6372         // It's sane to use the same Args for any redecl of this function, since
6373         // EvaluateWithSubstitution only cares about the position of each
6374         // argument in the arg list, not the ParmVarDecl* it maps to.
6375         if (!DIA->getCond()->EvaluateWithSubstitution(
6376                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6377           return false;
6378         return Result.isInt() && Result.getInt().getBoolValue();
6379       });
6380 }
6381 
6382 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6383                                                  SourceLocation Loc) {
6384   return diagnoseDiagnoseIfAttrsWith(
6385       *this, ND, /*ArgDependent=*/false, Loc,
6386       [&](const DiagnoseIfAttr *DIA) {
6387         bool Result;
6388         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6389                Result;
6390       });
6391 }
6392 
6393 /// Add all of the function declarations in the given function set to
6394 /// the overload candidate set.
6395 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6396                                  ArrayRef<Expr *> Args,
6397                                  OverloadCandidateSet &CandidateSet,
6398                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6399                                  bool SuppressUserConversions,
6400                                  bool PartialOverloading,
6401                                  bool FirstArgumentIsBase) {
6402   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6403     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6404     ArrayRef<Expr *> FunctionArgs = Args;
6405 
6406     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6407     FunctionDecl *FD =
6408         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6409 
6410     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6411       QualType ObjectType;
6412       Expr::Classification ObjectClassification;
6413       if (Args.size() > 0) {
6414         if (Expr *E = Args[0]) {
6415           // Use the explicit base to restrict the lookup:
6416           ObjectType = E->getType();
6417           ObjectClassification = E->Classify(Context);
6418         } // .. else there is an implicit base.
6419         FunctionArgs = Args.slice(1);
6420       }
6421       if (FunTmpl) {
6422         AddMethodTemplateCandidate(
6423             FunTmpl, F.getPair(),
6424             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6425             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6426             FunctionArgs, CandidateSet, SuppressUserConversions,
6427             PartialOverloading);
6428       } else {
6429         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6430                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6431                            ObjectClassification, FunctionArgs, CandidateSet,
6432                            SuppressUserConversions, PartialOverloading);
6433       }
6434     } else {
6435       // This branch handles both standalone functions and static methods.
6436 
6437       // Slice the first argument (which is the base) when we access
6438       // static method as non-static.
6439       if (Args.size() > 0 &&
6440           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6441                         !isa<CXXConstructorDecl>(FD)))) {
6442         assert(cast<CXXMethodDecl>(FD)->isStatic());
6443         FunctionArgs = Args.slice(1);
6444       }
6445       if (FunTmpl) {
6446         AddTemplateOverloadCandidate(
6447             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6448             CandidateSet, SuppressUserConversions, PartialOverloading);
6449       } else {
6450         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6451                              SuppressUserConversions, PartialOverloading);
6452       }
6453     }
6454   }
6455 }
6456 
6457 /// AddMethodCandidate - Adds a named decl (which is some kind of
6458 /// method) as a method candidate to the given overload set.
6459 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6460                               QualType ObjectType,
6461                               Expr::Classification ObjectClassification,
6462                               ArrayRef<Expr *> Args,
6463                               OverloadCandidateSet& CandidateSet,
6464                               bool SuppressUserConversions) {
6465   NamedDecl *Decl = FoundDecl.getDecl();
6466   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6467 
6468   if (isa<UsingShadowDecl>(Decl))
6469     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6470 
6471   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6472     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6473            "Expected a member function template");
6474     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6475                                /*ExplicitArgs*/ nullptr, ObjectType,
6476                                ObjectClassification, Args, CandidateSet,
6477                                SuppressUserConversions);
6478   } else {
6479     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6480                        ObjectType, ObjectClassification, Args, CandidateSet,
6481                        SuppressUserConversions);
6482   }
6483 }
6484 
6485 /// AddMethodCandidate - Adds the given C++ member function to the set
6486 /// of candidate functions, using the given function call arguments
6487 /// and the object argument (@c Object). For example, in a call
6488 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6489 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6490 /// allow user-defined conversions via constructors or conversion
6491 /// operators.
6492 void
6493 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6494                          CXXRecordDecl *ActingContext, QualType ObjectType,
6495                          Expr::Classification ObjectClassification,
6496                          ArrayRef<Expr *> Args,
6497                          OverloadCandidateSet &CandidateSet,
6498                          bool SuppressUserConversions,
6499                          bool PartialOverloading,
6500                          ConversionSequenceList EarlyConversions) {
6501   const FunctionProtoType *Proto
6502     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6503   assert(Proto && "Methods without a prototype cannot be overloaded");
6504   assert(!isa<CXXConstructorDecl>(Method) &&
6505          "Use AddOverloadCandidate for constructors");
6506 
6507   if (!CandidateSet.isNewCandidate(Method))
6508     return;
6509 
6510   // C++11 [class.copy]p23: [DR1402]
6511   //   A defaulted move assignment operator that is defined as deleted is
6512   //   ignored by overload resolution.
6513   if (Method->isDefaulted() && Method->isDeleted() &&
6514       Method->isMoveAssignmentOperator())
6515     return;
6516 
6517   // Overload resolution is always an unevaluated context.
6518   EnterExpressionEvaluationContext Unevaluated(
6519       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6520 
6521   // Add this candidate
6522   OverloadCandidate &Candidate =
6523       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6524   Candidate.FoundDecl = FoundDecl;
6525   Candidate.Function = Method;
6526   Candidate.IsSurrogate = false;
6527   Candidate.IgnoreObjectArgument = false;
6528   Candidate.ExplicitCallArguments = Args.size();
6529 
6530   unsigned NumParams = Proto->getNumParams();
6531 
6532   // (C++ 13.3.2p2): A candidate function having fewer than m
6533   // parameters is viable only if it has an ellipsis in its parameter
6534   // list (8.3.5).
6535   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6536       !Proto->isVariadic()) {
6537     Candidate.Viable = false;
6538     Candidate.FailureKind = ovl_fail_too_many_arguments;
6539     return;
6540   }
6541 
6542   // (C++ 13.3.2p2): A candidate function having more than m parameters
6543   // is viable only if the (m+1)st parameter has a default argument
6544   // (8.3.6). For the purposes of overload resolution, the
6545   // parameter list is truncated on the right, so that there are
6546   // exactly m parameters.
6547   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6548   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6549     // Not enough arguments.
6550     Candidate.Viable = false;
6551     Candidate.FailureKind = ovl_fail_too_few_arguments;
6552     return;
6553   }
6554 
6555   Candidate.Viable = true;
6556 
6557   if (Method->isStatic() || ObjectType.isNull())
6558     // The implicit object argument is ignored.
6559     Candidate.IgnoreObjectArgument = true;
6560   else {
6561     // Determine the implicit conversion sequence for the object
6562     // parameter.
6563     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6564         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6565         Method, ActingContext);
6566     if (Candidate.Conversions[0].isBad()) {
6567       Candidate.Viable = false;
6568       Candidate.FailureKind = ovl_fail_bad_conversion;
6569       return;
6570     }
6571   }
6572 
6573   // (CUDA B.1): Check for invalid calls between targets.
6574   if (getLangOpts().CUDA)
6575     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6576       if (!IsAllowedCUDACall(Caller, Method)) {
6577         Candidate.Viable = false;
6578         Candidate.FailureKind = ovl_fail_bad_target;
6579         return;
6580       }
6581 
6582   // Determine the implicit conversion sequences for each of the
6583   // arguments.
6584   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6585     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6586       // We already formed a conversion sequence for this parameter during
6587       // template argument deduction.
6588     } else if (ArgIdx < NumParams) {
6589       // (C++ 13.3.2p3): for F to be a viable function, there shall
6590       // exist for each argument an implicit conversion sequence
6591       // (13.3.3.1) that converts that argument to the corresponding
6592       // parameter of F.
6593       QualType ParamType = Proto->getParamType(ArgIdx);
6594       Candidate.Conversions[ArgIdx + 1]
6595         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6596                                 SuppressUserConversions,
6597                                 /*InOverloadResolution=*/true,
6598                                 /*AllowObjCWritebackConversion=*/
6599                                   getLangOpts().ObjCAutoRefCount);
6600       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6601         Candidate.Viable = false;
6602         Candidate.FailureKind = ovl_fail_bad_conversion;
6603         return;
6604       }
6605     } else {
6606       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6607       // argument for which there is no corresponding parameter is
6608       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6609       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6610     }
6611   }
6612 
6613   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6614     Candidate.Viable = false;
6615     Candidate.FailureKind = ovl_fail_enable_if;
6616     Candidate.DeductionFailure.Data = FailedAttr;
6617     return;
6618   }
6619 
6620   if (Method->isMultiVersion() &&
6621       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6622     Candidate.Viable = false;
6623     Candidate.FailureKind = ovl_non_default_multiversion_function;
6624   }
6625 }
6626 
6627 /// Add a C++ member function template as a candidate to the candidate
6628 /// set, using template argument deduction to produce an appropriate member
6629 /// function template specialization.
6630 void
6631 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6632                                  DeclAccessPair FoundDecl,
6633                                  CXXRecordDecl *ActingContext,
6634                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6635                                  QualType ObjectType,
6636                                  Expr::Classification ObjectClassification,
6637                                  ArrayRef<Expr *> Args,
6638                                  OverloadCandidateSet& CandidateSet,
6639                                  bool SuppressUserConversions,
6640                                  bool PartialOverloading) {
6641   if (!CandidateSet.isNewCandidate(MethodTmpl))
6642     return;
6643 
6644   // C++ [over.match.funcs]p7:
6645   //   In each case where a candidate is a function template, candidate
6646   //   function template specializations are generated using template argument
6647   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6648   //   candidate functions in the usual way.113) A given name can refer to one
6649   //   or more function templates and also to a set of overloaded non-template
6650   //   functions. In such a case, the candidate functions generated from each
6651   //   function template are combined with the set of non-template candidate
6652   //   functions.
6653   TemplateDeductionInfo Info(CandidateSet.getLocation());
6654   FunctionDecl *Specialization = nullptr;
6655   ConversionSequenceList Conversions;
6656   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6657           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6658           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6659             return CheckNonDependentConversions(
6660                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6661                 SuppressUserConversions, ActingContext, ObjectType,
6662                 ObjectClassification);
6663           })) {
6664     OverloadCandidate &Candidate =
6665         CandidateSet.addCandidate(Conversions.size(), Conversions);
6666     Candidate.FoundDecl = FoundDecl;
6667     Candidate.Function = MethodTmpl->getTemplatedDecl();
6668     Candidate.Viable = false;
6669     Candidate.IsSurrogate = false;
6670     Candidate.IgnoreObjectArgument =
6671         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6672         ObjectType.isNull();
6673     Candidate.ExplicitCallArguments = Args.size();
6674     if (Result == TDK_NonDependentConversionFailure)
6675       Candidate.FailureKind = ovl_fail_bad_conversion;
6676     else {
6677       Candidate.FailureKind = ovl_fail_bad_deduction;
6678       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6679                                                             Info);
6680     }
6681     return;
6682   }
6683 
6684   // Add the function template specialization produced by template argument
6685   // deduction as a candidate.
6686   assert(Specialization && "Missing member function template specialization?");
6687   assert(isa<CXXMethodDecl>(Specialization) &&
6688          "Specialization is not a member function?");
6689   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6690                      ActingContext, ObjectType, ObjectClassification, Args,
6691                      CandidateSet, SuppressUserConversions, PartialOverloading,
6692                      Conversions);
6693 }
6694 
6695 /// Add a C++ function template specialization as a candidate
6696 /// in the candidate set, using template argument deduction to produce
6697 /// an appropriate function template specialization.
6698 void
6699 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6700                                    DeclAccessPair FoundDecl,
6701                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6702                                    ArrayRef<Expr *> Args,
6703                                    OverloadCandidateSet& CandidateSet,
6704                                    bool SuppressUserConversions,
6705                                    bool PartialOverloading) {
6706   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6707     return;
6708 
6709   // C++ [over.match.funcs]p7:
6710   //   In each case where a candidate is a function template, candidate
6711   //   function template specializations are generated using template argument
6712   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6713   //   candidate functions in the usual way.113) A given name can refer to one
6714   //   or more function templates and also to a set of overloaded non-template
6715   //   functions. In such a case, the candidate functions generated from each
6716   //   function template are combined with the set of non-template candidate
6717   //   functions.
6718   TemplateDeductionInfo Info(CandidateSet.getLocation());
6719   FunctionDecl *Specialization = nullptr;
6720   ConversionSequenceList Conversions;
6721   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6722           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6723           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6724             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6725                                                 Args, CandidateSet, Conversions,
6726                                                 SuppressUserConversions);
6727           })) {
6728     OverloadCandidate &Candidate =
6729         CandidateSet.addCandidate(Conversions.size(), Conversions);
6730     Candidate.FoundDecl = FoundDecl;
6731     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6732     Candidate.Viable = false;
6733     Candidate.IsSurrogate = false;
6734     // Ignore the object argument if there is one, since we don't have an object
6735     // type.
6736     Candidate.IgnoreObjectArgument =
6737         isa<CXXMethodDecl>(Candidate.Function) &&
6738         !isa<CXXConstructorDecl>(Candidate.Function);
6739     Candidate.ExplicitCallArguments = Args.size();
6740     if (Result == TDK_NonDependentConversionFailure)
6741       Candidate.FailureKind = ovl_fail_bad_conversion;
6742     else {
6743       Candidate.FailureKind = ovl_fail_bad_deduction;
6744       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6745                                                             Info);
6746     }
6747     return;
6748   }
6749 
6750   // Add the function template specialization produced by template argument
6751   // deduction as a candidate.
6752   assert(Specialization && "Missing function template specialization?");
6753   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6754                        SuppressUserConversions, PartialOverloading,
6755                        /*AllowExplicit*/false, Conversions);
6756 }
6757 
6758 /// Check that implicit conversion sequences can be formed for each argument
6759 /// whose corresponding parameter has a non-dependent type, per DR1391's
6760 /// [temp.deduct.call]p10.
6761 bool Sema::CheckNonDependentConversions(
6762     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6763     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6764     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6765     CXXRecordDecl *ActingContext, QualType ObjectType,
6766     Expr::Classification ObjectClassification) {
6767   // FIXME: The cases in which we allow explicit conversions for constructor
6768   // arguments never consider calling a constructor template. It's not clear
6769   // that is correct.
6770   const bool AllowExplicit = false;
6771 
6772   auto *FD = FunctionTemplate->getTemplatedDecl();
6773   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6774   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6775   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6776 
6777   Conversions =
6778       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6779 
6780   // Overload resolution is always an unevaluated context.
6781   EnterExpressionEvaluationContext Unevaluated(
6782       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6783 
6784   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6785   // require that, but this check should never result in a hard error, and
6786   // overload resolution is permitted to sidestep instantiations.
6787   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6788       !ObjectType.isNull()) {
6789     Conversions[0] = TryObjectArgumentInitialization(
6790         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6791         Method, ActingContext);
6792     if (Conversions[0].isBad())
6793       return true;
6794   }
6795 
6796   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6797        ++I) {
6798     QualType ParamType = ParamTypes[I];
6799     if (!ParamType->isDependentType()) {
6800       Conversions[ThisConversions + I]
6801         = TryCopyInitialization(*this, Args[I], ParamType,
6802                                 SuppressUserConversions,
6803                                 /*InOverloadResolution=*/true,
6804                                 /*AllowObjCWritebackConversion=*/
6805                                   getLangOpts().ObjCAutoRefCount,
6806                                 AllowExplicit);
6807       if (Conversions[ThisConversions + I].isBad())
6808         return true;
6809     }
6810   }
6811 
6812   return false;
6813 }
6814 
6815 /// Determine whether this is an allowable conversion from the result
6816 /// of an explicit conversion operator to the expected type, per C++
6817 /// [over.match.conv]p1 and [over.match.ref]p1.
6818 ///
6819 /// \param ConvType The return type of the conversion function.
6820 ///
6821 /// \param ToType The type we are converting to.
6822 ///
6823 /// \param AllowObjCPointerConversion Allow a conversion from one
6824 /// Objective-C pointer to another.
6825 ///
6826 /// \returns true if the conversion is allowable, false otherwise.
6827 static bool isAllowableExplicitConversion(Sema &S,
6828                                           QualType ConvType, QualType ToType,
6829                                           bool AllowObjCPointerConversion) {
6830   QualType ToNonRefType = ToType.getNonReferenceType();
6831 
6832   // Easy case: the types are the same.
6833   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6834     return true;
6835 
6836   // Allow qualification conversions.
6837   bool ObjCLifetimeConversion;
6838   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6839                                   ObjCLifetimeConversion))
6840     return true;
6841 
6842   // If we're not allowed to consider Objective-C pointer conversions,
6843   // we're done.
6844   if (!AllowObjCPointerConversion)
6845     return false;
6846 
6847   // Is this an Objective-C pointer conversion?
6848   bool IncompatibleObjC = false;
6849   QualType ConvertedType;
6850   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6851                                    IncompatibleObjC);
6852 }
6853 
6854 /// AddConversionCandidate - Add a C++ conversion function as a
6855 /// candidate in the candidate set (C++ [over.match.conv],
6856 /// C++ [over.match.copy]). From is the expression we're converting from,
6857 /// and ToType is the type that we're eventually trying to convert to
6858 /// (which may or may not be the same type as the type that the
6859 /// conversion function produces).
6860 void
6861 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6862                              DeclAccessPair FoundDecl,
6863                              CXXRecordDecl *ActingContext,
6864                              Expr *From, QualType ToType,
6865                              OverloadCandidateSet& CandidateSet,
6866                              bool AllowObjCConversionOnExplicit,
6867                              bool AllowResultConversion) {
6868   assert(!Conversion->getDescribedFunctionTemplate() &&
6869          "Conversion function templates use AddTemplateConversionCandidate");
6870   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6871   if (!CandidateSet.isNewCandidate(Conversion))
6872     return;
6873 
6874   // If the conversion function has an undeduced return type, trigger its
6875   // deduction now.
6876   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6877     if (DeduceReturnType(Conversion, From->getExprLoc()))
6878       return;
6879     ConvType = Conversion->getConversionType().getNonReferenceType();
6880   }
6881 
6882   // If we don't allow any conversion of the result type, ignore conversion
6883   // functions that don't convert to exactly (possibly cv-qualified) T.
6884   if (!AllowResultConversion &&
6885       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6886     return;
6887 
6888   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6889   // operator is only a candidate if its return type is the target type or
6890   // can be converted to the target type with a qualification conversion.
6891   if (Conversion->isExplicit() &&
6892       !isAllowableExplicitConversion(*this, ConvType, ToType,
6893                                      AllowObjCConversionOnExplicit))
6894     return;
6895 
6896   // Overload resolution is always an unevaluated context.
6897   EnterExpressionEvaluationContext Unevaluated(
6898       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6899 
6900   // Add this candidate
6901   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6902   Candidate.FoundDecl = FoundDecl;
6903   Candidate.Function = Conversion;
6904   Candidate.IsSurrogate = false;
6905   Candidate.IgnoreObjectArgument = false;
6906   Candidate.FinalConversion.setAsIdentityConversion();
6907   Candidate.FinalConversion.setFromType(ConvType);
6908   Candidate.FinalConversion.setAllToTypes(ToType);
6909   Candidate.Viable = true;
6910   Candidate.ExplicitCallArguments = 1;
6911 
6912   // C++ [over.match.funcs]p4:
6913   //   For conversion functions, the function is considered to be a member of
6914   //   the class of the implicit implied object argument for the purpose of
6915   //   defining the type of the implicit object parameter.
6916   //
6917   // Determine the implicit conversion sequence for the implicit
6918   // object parameter.
6919   QualType ImplicitParamType = From->getType();
6920   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6921     ImplicitParamType = FromPtrType->getPointeeType();
6922   CXXRecordDecl *ConversionContext
6923     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6924 
6925   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6926       *this, CandidateSet.getLocation(), From->getType(),
6927       From->Classify(Context), Conversion, ConversionContext);
6928 
6929   if (Candidate.Conversions[0].isBad()) {
6930     Candidate.Viable = false;
6931     Candidate.FailureKind = ovl_fail_bad_conversion;
6932     return;
6933   }
6934 
6935   // We won't go through a user-defined type conversion function to convert a
6936   // derived to base as such conversions are given Conversion Rank. They only
6937   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6938   QualType FromCanon
6939     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6940   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6941   if (FromCanon == ToCanon ||
6942       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6943     Candidate.Viable = false;
6944     Candidate.FailureKind = ovl_fail_trivial_conversion;
6945     return;
6946   }
6947 
6948   // To determine what the conversion from the result of calling the
6949   // conversion function to the type we're eventually trying to
6950   // convert to (ToType), we need to synthesize a call to the
6951   // conversion function and attempt copy initialization from it. This
6952   // makes sure that we get the right semantics with respect to
6953   // lvalues/rvalues and the type. Fortunately, we can allocate this
6954   // call on the stack and we don't need its arguments to be
6955   // well-formed.
6956   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6957                             VK_LValue, From->getLocStart());
6958   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6959                                 Context.getPointerType(Conversion->getType()),
6960                                 CK_FunctionToPointerDecay,
6961                                 &ConversionRef, VK_RValue);
6962 
6963   QualType ConversionType = Conversion->getConversionType();
6964   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6965     Candidate.Viable = false;
6966     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6967     return;
6968   }
6969 
6970   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6971 
6972   // Note that it is safe to allocate CallExpr on the stack here because
6973   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6974   // allocator).
6975   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6976   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6977                 From->getLocStart());
6978   ImplicitConversionSequence ICS =
6979     TryCopyInitialization(*this, &Call, ToType,
6980                           /*SuppressUserConversions=*/true,
6981                           /*InOverloadResolution=*/false,
6982                           /*AllowObjCWritebackConversion=*/false);
6983 
6984   switch (ICS.getKind()) {
6985   case ImplicitConversionSequence::StandardConversion:
6986     Candidate.FinalConversion = ICS.Standard;
6987 
6988     // C++ [over.ics.user]p3:
6989     //   If the user-defined conversion is specified by a specialization of a
6990     //   conversion function template, the second standard conversion sequence
6991     //   shall have exact match rank.
6992     if (Conversion->getPrimaryTemplate() &&
6993         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6994       Candidate.Viable = false;
6995       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6996       return;
6997     }
6998 
6999     // C++0x [dcl.init.ref]p5:
7000     //    In the second case, if the reference is an rvalue reference and
7001     //    the second standard conversion sequence of the user-defined
7002     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7003     //    program is ill-formed.
7004     if (ToType->isRValueReferenceType() &&
7005         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7006       Candidate.Viable = false;
7007       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7008       return;
7009     }
7010     break;
7011 
7012   case ImplicitConversionSequence::BadConversion:
7013     Candidate.Viable = false;
7014     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7015     return;
7016 
7017   default:
7018     llvm_unreachable(
7019            "Can only end up with a standard conversion sequence or failure");
7020   }
7021 
7022   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7023     Candidate.Viable = false;
7024     Candidate.FailureKind = ovl_fail_enable_if;
7025     Candidate.DeductionFailure.Data = FailedAttr;
7026     return;
7027   }
7028 
7029   if (Conversion->isMultiVersion() &&
7030       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7031     Candidate.Viable = false;
7032     Candidate.FailureKind = ovl_non_default_multiversion_function;
7033   }
7034 }
7035 
7036 /// Adds a conversion function template specialization
7037 /// candidate to the overload set, using template argument deduction
7038 /// to deduce the template arguments of the conversion function
7039 /// template from the type that we are converting to (C++
7040 /// [temp.deduct.conv]).
7041 void
7042 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7043                                      DeclAccessPair FoundDecl,
7044                                      CXXRecordDecl *ActingDC,
7045                                      Expr *From, QualType ToType,
7046                                      OverloadCandidateSet &CandidateSet,
7047                                      bool AllowObjCConversionOnExplicit,
7048                                      bool AllowResultConversion) {
7049   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7050          "Only conversion function templates permitted here");
7051 
7052   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7053     return;
7054 
7055   TemplateDeductionInfo Info(CandidateSet.getLocation());
7056   CXXConversionDecl *Specialization = nullptr;
7057   if (TemplateDeductionResult Result
7058         = DeduceTemplateArguments(FunctionTemplate, ToType,
7059                                   Specialization, Info)) {
7060     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7061     Candidate.FoundDecl = FoundDecl;
7062     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7063     Candidate.Viable = false;
7064     Candidate.FailureKind = ovl_fail_bad_deduction;
7065     Candidate.IsSurrogate = false;
7066     Candidate.IgnoreObjectArgument = false;
7067     Candidate.ExplicitCallArguments = 1;
7068     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7069                                                           Info);
7070     return;
7071   }
7072 
7073   // Add the conversion function template specialization produced by
7074   // template argument deduction as a candidate.
7075   assert(Specialization && "Missing function template specialization?");
7076   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7077                          CandidateSet, AllowObjCConversionOnExplicit,
7078                          AllowResultConversion);
7079 }
7080 
7081 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7082 /// converts the given @c Object to a function pointer via the
7083 /// conversion function @c Conversion, and then attempts to call it
7084 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7085 /// the type of function that we'll eventually be calling.
7086 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7087                                  DeclAccessPair FoundDecl,
7088                                  CXXRecordDecl *ActingContext,
7089                                  const FunctionProtoType *Proto,
7090                                  Expr *Object,
7091                                  ArrayRef<Expr *> Args,
7092                                  OverloadCandidateSet& CandidateSet) {
7093   if (!CandidateSet.isNewCandidate(Conversion))
7094     return;
7095 
7096   // Overload resolution is always an unevaluated context.
7097   EnterExpressionEvaluationContext Unevaluated(
7098       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7099 
7100   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7101   Candidate.FoundDecl = FoundDecl;
7102   Candidate.Function = nullptr;
7103   Candidate.Surrogate = Conversion;
7104   Candidate.Viable = true;
7105   Candidate.IsSurrogate = true;
7106   Candidate.IgnoreObjectArgument = false;
7107   Candidate.ExplicitCallArguments = Args.size();
7108 
7109   // Determine the implicit conversion sequence for the implicit
7110   // object parameter.
7111   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7112       *this, CandidateSet.getLocation(), Object->getType(),
7113       Object->Classify(Context), Conversion, ActingContext);
7114   if (ObjectInit.isBad()) {
7115     Candidate.Viable = false;
7116     Candidate.FailureKind = ovl_fail_bad_conversion;
7117     Candidate.Conversions[0] = ObjectInit;
7118     return;
7119   }
7120 
7121   // The first conversion is actually a user-defined conversion whose
7122   // first conversion is ObjectInit's standard conversion (which is
7123   // effectively a reference binding). Record it as such.
7124   Candidate.Conversions[0].setUserDefined();
7125   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7126   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7127   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7128   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7129   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7130   Candidate.Conversions[0].UserDefined.After
7131     = Candidate.Conversions[0].UserDefined.Before;
7132   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7133 
7134   // Find the
7135   unsigned NumParams = Proto->getNumParams();
7136 
7137   // (C++ 13.3.2p2): A candidate function having fewer than m
7138   // parameters is viable only if it has an ellipsis in its parameter
7139   // list (8.3.5).
7140   if (Args.size() > NumParams && !Proto->isVariadic()) {
7141     Candidate.Viable = false;
7142     Candidate.FailureKind = ovl_fail_too_many_arguments;
7143     return;
7144   }
7145 
7146   // Function types don't have any default arguments, so just check if
7147   // we have enough arguments.
7148   if (Args.size() < NumParams) {
7149     // Not enough arguments.
7150     Candidate.Viable = false;
7151     Candidate.FailureKind = ovl_fail_too_few_arguments;
7152     return;
7153   }
7154 
7155   // Determine the implicit conversion sequences for each of the
7156   // arguments.
7157   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7158     if (ArgIdx < NumParams) {
7159       // (C++ 13.3.2p3): for F to be a viable function, there shall
7160       // exist for each argument an implicit conversion sequence
7161       // (13.3.3.1) that converts that argument to the corresponding
7162       // parameter of F.
7163       QualType ParamType = Proto->getParamType(ArgIdx);
7164       Candidate.Conversions[ArgIdx + 1]
7165         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7166                                 /*SuppressUserConversions=*/false,
7167                                 /*InOverloadResolution=*/false,
7168                                 /*AllowObjCWritebackConversion=*/
7169                                   getLangOpts().ObjCAutoRefCount);
7170       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7171         Candidate.Viable = false;
7172         Candidate.FailureKind = ovl_fail_bad_conversion;
7173         return;
7174       }
7175     } else {
7176       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7177       // argument for which there is no corresponding parameter is
7178       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7179       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7180     }
7181   }
7182 
7183   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7184     Candidate.Viable = false;
7185     Candidate.FailureKind = ovl_fail_enable_if;
7186     Candidate.DeductionFailure.Data = FailedAttr;
7187     return;
7188   }
7189 }
7190 
7191 /// Add overload candidates for overloaded operators that are
7192 /// member functions.
7193 ///
7194 /// Add the overloaded operator candidates that are member functions
7195 /// for the operator Op that was used in an operator expression such
7196 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7197 /// CandidateSet will store the added overload candidates. (C++
7198 /// [over.match.oper]).
7199 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7200                                        SourceLocation OpLoc,
7201                                        ArrayRef<Expr *> Args,
7202                                        OverloadCandidateSet& CandidateSet,
7203                                        SourceRange OpRange) {
7204   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7205 
7206   // C++ [over.match.oper]p3:
7207   //   For a unary operator @ with an operand of a type whose
7208   //   cv-unqualified version is T1, and for a binary operator @ with
7209   //   a left operand of a type whose cv-unqualified version is T1 and
7210   //   a right operand of a type whose cv-unqualified version is T2,
7211   //   three sets of candidate functions, designated member
7212   //   candidates, non-member candidates and built-in candidates, are
7213   //   constructed as follows:
7214   QualType T1 = Args[0]->getType();
7215 
7216   //     -- If T1 is a complete class type or a class currently being
7217   //        defined, the set of member candidates is the result of the
7218   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7219   //        the set of member candidates is empty.
7220   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7221     // Complete the type if it can be completed.
7222     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7223       return;
7224     // If the type is neither complete nor being defined, bail out now.
7225     if (!T1Rec->getDecl()->getDefinition())
7226       return;
7227 
7228     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7229     LookupQualifiedName(Operators, T1Rec->getDecl());
7230     Operators.suppressDiagnostics();
7231 
7232     for (LookupResult::iterator Oper = Operators.begin(),
7233                              OperEnd = Operators.end();
7234          Oper != OperEnd;
7235          ++Oper)
7236       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7237                          Args[0]->Classify(Context), Args.slice(1),
7238                          CandidateSet, /*SuppressUserConversions=*/false);
7239   }
7240 }
7241 
7242 /// AddBuiltinCandidate - Add a candidate for a built-in
7243 /// operator. ResultTy and ParamTys are the result and parameter types
7244 /// of the built-in candidate, respectively. Args and NumArgs are the
7245 /// arguments being passed to the candidate. IsAssignmentOperator
7246 /// should be true when this built-in candidate is an assignment
7247 /// operator. NumContextualBoolArguments is the number of arguments
7248 /// (at the beginning of the argument list) that will be contextually
7249 /// converted to bool.
7250 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7251                                OverloadCandidateSet& CandidateSet,
7252                                bool IsAssignmentOperator,
7253                                unsigned NumContextualBoolArguments) {
7254   // Overload resolution is always an unevaluated context.
7255   EnterExpressionEvaluationContext Unevaluated(
7256       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7257 
7258   // Add this candidate
7259   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7260   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7261   Candidate.Function = nullptr;
7262   Candidate.IsSurrogate = false;
7263   Candidate.IgnoreObjectArgument = false;
7264   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7265 
7266   // Determine the implicit conversion sequences for each of the
7267   // arguments.
7268   Candidate.Viable = true;
7269   Candidate.ExplicitCallArguments = Args.size();
7270   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7271     // C++ [over.match.oper]p4:
7272     //   For the built-in assignment operators, conversions of the
7273     //   left operand are restricted as follows:
7274     //     -- no temporaries are introduced to hold the left operand, and
7275     //     -- no user-defined conversions are applied to the left
7276     //        operand to achieve a type match with the left-most
7277     //        parameter of a built-in candidate.
7278     //
7279     // We block these conversions by turning off user-defined
7280     // conversions, since that is the only way that initialization of
7281     // a reference to a non-class type can occur from something that
7282     // is not of the same type.
7283     if (ArgIdx < NumContextualBoolArguments) {
7284       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7285              "Contextual conversion to bool requires bool type");
7286       Candidate.Conversions[ArgIdx]
7287         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7288     } else {
7289       Candidate.Conversions[ArgIdx]
7290         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7291                                 ArgIdx == 0 && IsAssignmentOperator,
7292                                 /*InOverloadResolution=*/false,
7293                                 /*AllowObjCWritebackConversion=*/
7294                                   getLangOpts().ObjCAutoRefCount);
7295     }
7296     if (Candidate.Conversions[ArgIdx].isBad()) {
7297       Candidate.Viable = false;
7298       Candidate.FailureKind = ovl_fail_bad_conversion;
7299       break;
7300     }
7301   }
7302 }
7303 
7304 namespace {
7305 
7306 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7307 /// candidate operator functions for built-in operators (C++
7308 /// [over.built]). The types are separated into pointer types and
7309 /// enumeration types.
7310 class BuiltinCandidateTypeSet  {
7311   /// TypeSet - A set of types.
7312   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7313                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7314 
7315   /// PointerTypes - The set of pointer types that will be used in the
7316   /// built-in candidates.
7317   TypeSet PointerTypes;
7318 
7319   /// MemberPointerTypes - The set of member pointer types that will be
7320   /// used in the built-in candidates.
7321   TypeSet MemberPointerTypes;
7322 
7323   /// EnumerationTypes - The set of enumeration types that will be
7324   /// used in the built-in candidates.
7325   TypeSet EnumerationTypes;
7326 
7327   /// The set of vector types that will be used in the built-in
7328   /// candidates.
7329   TypeSet VectorTypes;
7330 
7331   /// A flag indicating non-record types are viable candidates
7332   bool HasNonRecordTypes;
7333 
7334   /// A flag indicating whether either arithmetic or enumeration types
7335   /// were present in the candidate set.
7336   bool HasArithmeticOrEnumeralTypes;
7337 
7338   /// A flag indicating whether the nullptr type was present in the
7339   /// candidate set.
7340   bool HasNullPtrType;
7341 
7342   /// Sema - The semantic analysis instance where we are building the
7343   /// candidate type set.
7344   Sema &SemaRef;
7345 
7346   /// Context - The AST context in which we will build the type sets.
7347   ASTContext &Context;
7348 
7349   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7350                                                const Qualifiers &VisibleQuals);
7351   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7352 
7353 public:
7354   /// iterator - Iterates through the types that are part of the set.
7355   typedef TypeSet::iterator iterator;
7356 
7357   BuiltinCandidateTypeSet(Sema &SemaRef)
7358     : HasNonRecordTypes(false),
7359       HasArithmeticOrEnumeralTypes(false),
7360       HasNullPtrType(false),
7361       SemaRef(SemaRef),
7362       Context(SemaRef.Context) { }
7363 
7364   void AddTypesConvertedFrom(QualType Ty,
7365                              SourceLocation Loc,
7366                              bool AllowUserConversions,
7367                              bool AllowExplicitConversions,
7368                              const Qualifiers &VisibleTypeConversionsQuals);
7369 
7370   /// pointer_begin - First pointer type found;
7371   iterator pointer_begin() { return PointerTypes.begin(); }
7372 
7373   /// pointer_end - Past the last pointer type found;
7374   iterator pointer_end() { return PointerTypes.end(); }
7375 
7376   /// member_pointer_begin - First member pointer type found;
7377   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7378 
7379   /// member_pointer_end - Past the last member pointer type found;
7380   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7381 
7382   /// enumeration_begin - First enumeration type found;
7383   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7384 
7385   /// enumeration_end - Past the last enumeration type found;
7386   iterator enumeration_end() { return EnumerationTypes.end(); }
7387 
7388   iterator vector_begin() { return VectorTypes.begin(); }
7389   iterator vector_end() { return VectorTypes.end(); }
7390 
7391   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7392   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7393   bool hasNullPtrType() const { return HasNullPtrType; }
7394 };
7395 
7396 } // end anonymous namespace
7397 
7398 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7399 /// the set of pointer types along with any more-qualified variants of
7400 /// that type. For example, if @p Ty is "int const *", this routine
7401 /// will add "int const *", "int const volatile *", "int const
7402 /// restrict *", and "int const volatile restrict *" to the set of
7403 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7404 /// false otherwise.
7405 ///
7406 /// FIXME: what to do about extended qualifiers?
7407 bool
7408 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7409                                              const Qualifiers &VisibleQuals) {
7410 
7411   // Insert this type.
7412   if (!PointerTypes.insert(Ty))
7413     return false;
7414 
7415   QualType PointeeTy;
7416   const PointerType *PointerTy = Ty->getAs<PointerType>();
7417   bool buildObjCPtr = false;
7418   if (!PointerTy) {
7419     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7420     PointeeTy = PTy->getPointeeType();
7421     buildObjCPtr = true;
7422   } else {
7423     PointeeTy = PointerTy->getPointeeType();
7424   }
7425 
7426   // Don't add qualified variants of arrays. For one, they're not allowed
7427   // (the qualifier would sink to the element type), and for another, the
7428   // only overload situation where it matters is subscript or pointer +- int,
7429   // and those shouldn't have qualifier variants anyway.
7430   if (PointeeTy->isArrayType())
7431     return true;
7432 
7433   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7434   bool hasVolatile = VisibleQuals.hasVolatile();
7435   bool hasRestrict = VisibleQuals.hasRestrict();
7436 
7437   // Iterate through all strict supersets of BaseCVR.
7438   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7439     if ((CVR | BaseCVR) != CVR) continue;
7440     // Skip over volatile if no volatile found anywhere in the types.
7441     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7442 
7443     // Skip over restrict if no restrict found anywhere in the types, or if
7444     // the type cannot be restrict-qualified.
7445     if ((CVR & Qualifiers::Restrict) &&
7446         (!hasRestrict ||
7447          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7448       continue;
7449 
7450     // Build qualified pointee type.
7451     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7452 
7453     // Build qualified pointer type.
7454     QualType QPointerTy;
7455     if (!buildObjCPtr)
7456       QPointerTy = Context.getPointerType(QPointeeTy);
7457     else
7458       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7459 
7460     // Insert qualified pointer type.
7461     PointerTypes.insert(QPointerTy);
7462   }
7463 
7464   return true;
7465 }
7466 
7467 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7468 /// to the set of pointer types along with any more-qualified variants of
7469 /// that type. For example, if @p Ty is "int const *", this routine
7470 /// will add "int const *", "int const volatile *", "int const
7471 /// restrict *", and "int const volatile restrict *" to the set of
7472 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7473 /// false otherwise.
7474 ///
7475 /// FIXME: what to do about extended qualifiers?
7476 bool
7477 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7478     QualType Ty) {
7479   // Insert this type.
7480   if (!MemberPointerTypes.insert(Ty))
7481     return false;
7482 
7483   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7484   assert(PointerTy && "type was not a member pointer type!");
7485 
7486   QualType PointeeTy = PointerTy->getPointeeType();
7487   // Don't add qualified variants of arrays. For one, they're not allowed
7488   // (the qualifier would sink to the element type), and for another, the
7489   // only overload situation where it matters is subscript or pointer +- int,
7490   // and those shouldn't have qualifier variants anyway.
7491   if (PointeeTy->isArrayType())
7492     return true;
7493   const Type *ClassTy = PointerTy->getClass();
7494 
7495   // Iterate through all strict supersets of the pointee type's CVR
7496   // qualifiers.
7497   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7498   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7499     if ((CVR | BaseCVR) != CVR) continue;
7500 
7501     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7502     MemberPointerTypes.insert(
7503       Context.getMemberPointerType(QPointeeTy, ClassTy));
7504   }
7505 
7506   return true;
7507 }
7508 
7509 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7510 /// Ty can be implicit converted to the given set of @p Types. We're
7511 /// primarily interested in pointer types and enumeration types. We also
7512 /// take member pointer types, for the conditional operator.
7513 /// AllowUserConversions is true if we should look at the conversion
7514 /// functions of a class type, and AllowExplicitConversions if we
7515 /// should also include the explicit conversion functions of a class
7516 /// type.
7517 void
7518 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7519                                                SourceLocation Loc,
7520                                                bool AllowUserConversions,
7521                                                bool AllowExplicitConversions,
7522                                                const Qualifiers &VisibleQuals) {
7523   // Only deal with canonical types.
7524   Ty = Context.getCanonicalType(Ty);
7525 
7526   // Look through reference types; they aren't part of the type of an
7527   // expression for the purposes of conversions.
7528   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7529     Ty = RefTy->getPointeeType();
7530 
7531   // If we're dealing with an array type, decay to the pointer.
7532   if (Ty->isArrayType())
7533     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7534 
7535   // Otherwise, we don't care about qualifiers on the type.
7536   Ty = Ty.getLocalUnqualifiedType();
7537 
7538   // Flag if we ever add a non-record type.
7539   const RecordType *TyRec = Ty->getAs<RecordType>();
7540   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7541 
7542   // Flag if we encounter an arithmetic type.
7543   HasArithmeticOrEnumeralTypes =
7544     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7545 
7546   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7547     PointerTypes.insert(Ty);
7548   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7549     // Insert our type, and its more-qualified variants, into the set
7550     // of types.
7551     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7552       return;
7553   } else if (Ty->isMemberPointerType()) {
7554     // Member pointers are far easier, since the pointee can't be converted.
7555     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7556       return;
7557   } else if (Ty->isEnumeralType()) {
7558     HasArithmeticOrEnumeralTypes = true;
7559     EnumerationTypes.insert(Ty);
7560   } else if (Ty->isVectorType()) {
7561     // We treat vector types as arithmetic types in many contexts as an
7562     // extension.
7563     HasArithmeticOrEnumeralTypes = true;
7564     VectorTypes.insert(Ty);
7565   } else if (Ty->isNullPtrType()) {
7566     HasNullPtrType = true;
7567   } else if (AllowUserConversions && TyRec) {
7568     // No conversion functions in incomplete types.
7569     if (!SemaRef.isCompleteType(Loc, Ty))
7570       return;
7571 
7572     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7573     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7574       if (isa<UsingShadowDecl>(D))
7575         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7576 
7577       // Skip conversion function templates; they don't tell us anything
7578       // about which builtin types we can convert to.
7579       if (isa<FunctionTemplateDecl>(D))
7580         continue;
7581 
7582       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7583       if (AllowExplicitConversions || !Conv->isExplicit()) {
7584         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7585                               VisibleQuals);
7586       }
7587     }
7588   }
7589 }
7590 
7591 /// Helper function for AddBuiltinOperatorCandidates() that adds
7592 /// the volatile- and non-volatile-qualified assignment operators for the
7593 /// given type to the candidate set.
7594 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7595                                                    QualType T,
7596                                                    ArrayRef<Expr *> Args,
7597                                     OverloadCandidateSet &CandidateSet) {
7598   QualType ParamTypes[2];
7599 
7600   // T& operator=(T&, T)
7601   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7602   ParamTypes[1] = T;
7603   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7604                         /*IsAssignmentOperator=*/true);
7605 
7606   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7607     // volatile T& operator=(volatile T&, T)
7608     ParamTypes[0]
7609       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7610     ParamTypes[1] = T;
7611     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7612                           /*IsAssignmentOperator=*/true);
7613   }
7614 }
7615 
7616 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7617 /// if any, found in visible type conversion functions found in ArgExpr's type.
7618 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7619     Qualifiers VRQuals;
7620     const RecordType *TyRec;
7621     if (const MemberPointerType *RHSMPType =
7622         ArgExpr->getType()->getAs<MemberPointerType>())
7623       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7624     else
7625       TyRec = ArgExpr->getType()->getAs<RecordType>();
7626     if (!TyRec) {
7627       // Just to be safe, assume the worst case.
7628       VRQuals.addVolatile();
7629       VRQuals.addRestrict();
7630       return VRQuals;
7631     }
7632 
7633     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7634     if (!ClassDecl->hasDefinition())
7635       return VRQuals;
7636 
7637     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7638       if (isa<UsingShadowDecl>(D))
7639         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7640       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7641         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7642         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7643           CanTy = ResTypeRef->getPointeeType();
7644         // Need to go down the pointer/mempointer chain and add qualifiers
7645         // as see them.
7646         bool done = false;
7647         while (!done) {
7648           if (CanTy.isRestrictQualified())
7649             VRQuals.addRestrict();
7650           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7651             CanTy = ResTypePtr->getPointeeType();
7652           else if (const MemberPointerType *ResTypeMPtr =
7653                 CanTy->getAs<MemberPointerType>())
7654             CanTy = ResTypeMPtr->getPointeeType();
7655           else
7656             done = true;
7657           if (CanTy.isVolatileQualified())
7658             VRQuals.addVolatile();
7659           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7660             return VRQuals;
7661         }
7662       }
7663     }
7664     return VRQuals;
7665 }
7666 
7667 namespace {
7668 
7669 /// Helper class to manage the addition of builtin operator overload
7670 /// candidates. It provides shared state and utility methods used throughout
7671 /// the process, as well as a helper method to add each group of builtin
7672 /// operator overloads from the standard to a candidate set.
7673 class BuiltinOperatorOverloadBuilder {
7674   // Common instance state available to all overload candidate addition methods.
7675   Sema &S;
7676   ArrayRef<Expr *> Args;
7677   Qualifiers VisibleTypeConversionsQuals;
7678   bool HasArithmeticOrEnumeralCandidateType;
7679   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7680   OverloadCandidateSet &CandidateSet;
7681 
7682   static constexpr int ArithmeticTypesCap = 24;
7683   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7684 
7685   // Define some indices used to iterate over the arithemetic types in
7686   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7687   // types are that preserved by promotion (C++ [over.built]p2).
7688   unsigned FirstIntegralType,
7689            LastIntegralType;
7690   unsigned FirstPromotedIntegralType,
7691            LastPromotedIntegralType;
7692   unsigned FirstPromotedArithmeticType,
7693            LastPromotedArithmeticType;
7694   unsigned NumArithmeticTypes;
7695 
7696   void InitArithmeticTypes() {
7697     // Start of promoted types.
7698     FirstPromotedArithmeticType = 0;
7699     ArithmeticTypes.push_back(S.Context.FloatTy);
7700     ArithmeticTypes.push_back(S.Context.DoubleTy);
7701     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7702     if (S.Context.getTargetInfo().hasFloat128Type())
7703       ArithmeticTypes.push_back(S.Context.Float128Ty);
7704 
7705     // Start of integral types.
7706     FirstIntegralType = ArithmeticTypes.size();
7707     FirstPromotedIntegralType = ArithmeticTypes.size();
7708     ArithmeticTypes.push_back(S.Context.IntTy);
7709     ArithmeticTypes.push_back(S.Context.LongTy);
7710     ArithmeticTypes.push_back(S.Context.LongLongTy);
7711     if (S.Context.getTargetInfo().hasInt128Type())
7712       ArithmeticTypes.push_back(S.Context.Int128Ty);
7713     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7714     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7715     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7716     if (S.Context.getTargetInfo().hasInt128Type())
7717       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7718     LastPromotedIntegralType = ArithmeticTypes.size();
7719     LastPromotedArithmeticType = ArithmeticTypes.size();
7720     // End of promoted types.
7721 
7722     ArithmeticTypes.push_back(S.Context.BoolTy);
7723     ArithmeticTypes.push_back(S.Context.CharTy);
7724     ArithmeticTypes.push_back(S.Context.WCharTy);
7725     if (S.Context.getLangOpts().Char8)
7726       ArithmeticTypes.push_back(S.Context.Char8Ty);
7727     ArithmeticTypes.push_back(S.Context.Char16Ty);
7728     ArithmeticTypes.push_back(S.Context.Char32Ty);
7729     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7730     ArithmeticTypes.push_back(S.Context.ShortTy);
7731     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7732     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7733     LastIntegralType = ArithmeticTypes.size();
7734     NumArithmeticTypes = ArithmeticTypes.size();
7735     // End of integral types.
7736     // FIXME: What about complex? What about half?
7737 
7738     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7739            "Enough inline storage for all arithmetic types.");
7740   }
7741 
7742   /// Helper method to factor out the common pattern of adding overloads
7743   /// for '++' and '--' builtin operators.
7744   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7745                                            bool HasVolatile,
7746                                            bool HasRestrict) {
7747     QualType ParamTypes[2] = {
7748       S.Context.getLValueReferenceType(CandidateTy),
7749       S.Context.IntTy
7750     };
7751 
7752     // Non-volatile version.
7753     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7754 
7755     // Use a heuristic to reduce number of builtin candidates in the set:
7756     // add volatile version only if there are conversions to a volatile type.
7757     if (HasVolatile) {
7758       ParamTypes[0] =
7759         S.Context.getLValueReferenceType(
7760           S.Context.getVolatileType(CandidateTy));
7761       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7762     }
7763 
7764     // Add restrict version only if there are conversions to a restrict type
7765     // and our candidate type is a non-restrict-qualified pointer.
7766     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7767         !CandidateTy.isRestrictQualified()) {
7768       ParamTypes[0]
7769         = S.Context.getLValueReferenceType(
7770             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7771       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7772 
7773       if (HasVolatile) {
7774         ParamTypes[0]
7775           = S.Context.getLValueReferenceType(
7776               S.Context.getCVRQualifiedType(CandidateTy,
7777                                             (Qualifiers::Volatile |
7778                                              Qualifiers::Restrict)));
7779         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7780       }
7781     }
7782 
7783   }
7784 
7785 public:
7786   BuiltinOperatorOverloadBuilder(
7787     Sema &S, ArrayRef<Expr *> Args,
7788     Qualifiers VisibleTypeConversionsQuals,
7789     bool HasArithmeticOrEnumeralCandidateType,
7790     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7791     OverloadCandidateSet &CandidateSet)
7792     : S(S), Args(Args),
7793       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7794       HasArithmeticOrEnumeralCandidateType(
7795         HasArithmeticOrEnumeralCandidateType),
7796       CandidateTypes(CandidateTypes),
7797       CandidateSet(CandidateSet) {
7798 
7799     InitArithmeticTypes();
7800   }
7801 
7802   // Increment is deprecated for bool since C++17.
7803   //
7804   // C++ [over.built]p3:
7805   //
7806   //   For every pair (T, VQ), where T is an arithmetic type other
7807   //   than bool, and VQ is either volatile or empty, there exist
7808   //   candidate operator functions of the form
7809   //
7810   //       VQ T&      operator++(VQ T&);
7811   //       T          operator++(VQ T&, int);
7812   //
7813   // C++ [over.built]p4:
7814   //
7815   //   For every pair (T, VQ), where T is an arithmetic type other
7816   //   than bool, and VQ is either volatile or empty, there exist
7817   //   candidate operator functions of the form
7818   //
7819   //       VQ T&      operator--(VQ T&);
7820   //       T          operator--(VQ T&, int);
7821   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7822     if (!HasArithmeticOrEnumeralCandidateType)
7823       return;
7824 
7825     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7826       const auto TypeOfT = ArithmeticTypes[Arith];
7827       if (TypeOfT == S.Context.BoolTy) {
7828         if (Op == OO_MinusMinus)
7829           continue;
7830         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7831           continue;
7832       }
7833       addPlusPlusMinusMinusStyleOverloads(
7834         TypeOfT,
7835         VisibleTypeConversionsQuals.hasVolatile(),
7836         VisibleTypeConversionsQuals.hasRestrict());
7837     }
7838   }
7839 
7840   // C++ [over.built]p5:
7841   //
7842   //   For every pair (T, VQ), where T is a cv-qualified or
7843   //   cv-unqualified object type, and VQ is either volatile or
7844   //   empty, there exist candidate operator functions of the form
7845   //
7846   //       T*VQ&      operator++(T*VQ&);
7847   //       T*VQ&      operator--(T*VQ&);
7848   //       T*         operator++(T*VQ&, int);
7849   //       T*         operator--(T*VQ&, int);
7850   void addPlusPlusMinusMinusPointerOverloads() {
7851     for (BuiltinCandidateTypeSet::iterator
7852               Ptr = CandidateTypes[0].pointer_begin(),
7853            PtrEnd = CandidateTypes[0].pointer_end();
7854          Ptr != PtrEnd; ++Ptr) {
7855       // Skip pointer types that aren't pointers to object types.
7856       if (!(*Ptr)->getPointeeType()->isObjectType())
7857         continue;
7858 
7859       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7860         (!(*Ptr).isVolatileQualified() &&
7861          VisibleTypeConversionsQuals.hasVolatile()),
7862         (!(*Ptr).isRestrictQualified() &&
7863          VisibleTypeConversionsQuals.hasRestrict()));
7864     }
7865   }
7866 
7867   // C++ [over.built]p6:
7868   //   For every cv-qualified or cv-unqualified object type T, there
7869   //   exist candidate operator functions of the form
7870   //
7871   //       T&         operator*(T*);
7872   //
7873   // C++ [over.built]p7:
7874   //   For every function type T that does not have cv-qualifiers or a
7875   //   ref-qualifier, there exist candidate operator functions of the form
7876   //       T&         operator*(T*);
7877   void addUnaryStarPointerOverloads() {
7878     for (BuiltinCandidateTypeSet::iterator
7879               Ptr = CandidateTypes[0].pointer_begin(),
7880            PtrEnd = CandidateTypes[0].pointer_end();
7881          Ptr != PtrEnd; ++Ptr) {
7882       QualType ParamTy = *Ptr;
7883       QualType PointeeTy = ParamTy->getPointeeType();
7884       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7885         continue;
7886 
7887       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7888         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7889           continue;
7890 
7891       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7892     }
7893   }
7894 
7895   // C++ [over.built]p9:
7896   //  For every promoted arithmetic type T, there exist candidate
7897   //  operator functions of the form
7898   //
7899   //       T         operator+(T);
7900   //       T         operator-(T);
7901   void addUnaryPlusOrMinusArithmeticOverloads() {
7902     if (!HasArithmeticOrEnumeralCandidateType)
7903       return;
7904 
7905     for (unsigned Arith = FirstPromotedArithmeticType;
7906          Arith < LastPromotedArithmeticType; ++Arith) {
7907       QualType ArithTy = ArithmeticTypes[Arith];
7908       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7909     }
7910 
7911     // Extension: We also add these operators for vector types.
7912     for (BuiltinCandidateTypeSet::iterator
7913               Vec = CandidateTypes[0].vector_begin(),
7914            VecEnd = CandidateTypes[0].vector_end();
7915          Vec != VecEnd; ++Vec) {
7916       QualType VecTy = *Vec;
7917       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7918     }
7919   }
7920 
7921   // C++ [over.built]p8:
7922   //   For every type T, there exist candidate operator functions of
7923   //   the form
7924   //
7925   //       T*         operator+(T*);
7926   void addUnaryPlusPointerOverloads() {
7927     for (BuiltinCandidateTypeSet::iterator
7928               Ptr = CandidateTypes[0].pointer_begin(),
7929            PtrEnd = CandidateTypes[0].pointer_end();
7930          Ptr != PtrEnd; ++Ptr) {
7931       QualType ParamTy = *Ptr;
7932       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7933     }
7934   }
7935 
7936   // C++ [over.built]p10:
7937   //   For every promoted integral type T, there exist candidate
7938   //   operator functions of the form
7939   //
7940   //        T         operator~(T);
7941   void addUnaryTildePromotedIntegralOverloads() {
7942     if (!HasArithmeticOrEnumeralCandidateType)
7943       return;
7944 
7945     for (unsigned Int = FirstPromotedIntegralType;
7946          Int < LastPromotedIntegralType; ++Int) {
7947       QualType IntTy = ArithmeticTypes[Int];
7948       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7949     }
7950 
7951     // Extension: We also add this operator for vector types.
7952     for (BuiltinCandidateTypeSet::iterator
7953               Vec = CandidateTypes[0].vector_begin(),
7954            VecEnd = CandidateTypes[0].vector_end();
7955          Vec != VecEnd; ++Vec) {
7956       QualType VecTy = *Vec;
7957       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7958     }
7959   }
7960 
7961   // C++ [over.match.oper]p16:
7962   //   For every pointer to member type T or type std::nullptr_t, there
7963   //   exist candidate operator functions of the form
7964   //
7965   //        bool operator==(T,T);
7966   //        bool operator!=(T,T);
7967   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7968     /// Set of (canonical) types that we've already handled.
7969     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7970 
7971     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7972       for (BuiltinCandidateTypeSet::iterator
7973                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7974              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7975            MemPtr != MemPtrEnd;
7976            ++MemPtr) {
7977         // Don't add the same builtin candidate twice.
7978         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7979           continue;
7980 
7981         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7982         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7983       }
7984 
7985       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7986         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7987         if (AddedTypes.insert(NullPtrTy).second) {
7988           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7989           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7990         }
7991       }
7992     }
7993   }
7994 
7995   // C++ [over.built]p15:
7996   //
7997   //   For every T, where T is an enumeration type or a pointer type,
7998   //   there exist candidate operator functions of the form
7999   //
8000   //        bool       operator<(T, T);
8001   //        bool       operator>(T, T);
8002   //        bool       operator<=(T, T);
8003   //        bool       operator>=(T, T);
8004   //        bool       operator==(T, T);
8005   //        bool       operator!=(T, T);
8006   //           R       operator<=>(T, T)
8007   void addGenericBinaryPointerOrEnumeralOverloads() {
8008     // C++ [over.match.oper]p3:
8009     //   [...]the built-in candidates include all of the candidate operator
8010     //   functions defined in 13.6 that, compared to the given operator, [...]
8011     //   do not have the same parameter-type-list as any non-template non-member
8012     //   candidate.
8013     //
8014     // Note that in practice, this only affects enumeration types because there
8015     // aren't any built-in candidates of record type, and a user-defined operator
8016     // must have an operand of record or enumeration type. Also, the only other
8017     // overloaded operator with enumeration arguments, operator=,
8018     // cannot be overloaded for enumeration types, so this is the only place
8019     // where we must suppress candidates like this.
8020     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8021       UserDefinedBinaryOperators;
8022 
8023     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8024       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8025           CandidateTypes[ArgIdx].enumeration_end()) {
8026         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8027                                          CEnd = CandidateSet.end();
8028              C != CEnd; ++C) {
8029           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8030             continue;
8031 
8032           if (C->Function->isFunctionTemplateSpecialization())
8033             continue;
8034 
8035           QualType FirstParamType =
8036             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8037           QualType SecondParamType =
8038             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8039 
8040           // Skip if either parameter isn't of enumeral type.
8041           if (!FirstParamType->isEnumeralType() ||
8042               !SecondParamType->isEnumeralType())
8043             continue;
8044 
8045           // Add this operator to the set of known user-defined operators.
8046           UserDefinedBinaryOperators.insert(
8047             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8048                            S.Context.getCanonicalType(SecondParamType)));
8049         }
8050       }
8051     }
8052 
8053     /// Set of (canonical) types that we've already handled.
8054     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8055 
8056     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8057       for (BuiltinCandidateTypeSet::iterator
8058                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8059              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8060            Ptr != PtrEnd; ++Ptr) {
8061         // Don't add the same builtin candidate twice.
8062         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8063           continue;
8064 
8065         QualType ParamTypes[2] = { *Ptr, *Ptr };
8066         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8067       }
8068       for (BuiltinCandidateTypeSet::iterator
8069                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8070              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8071            Enum != EnumEnd; ++Enum) {
8072         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8073 
8074         // Don't add the same builtin candidate twice, or if a user defined
8075         // candidate exists.
8076         if (!AddedTypes.insert(CanonType).second ||
8077             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8078                                                             CanonType)))
8079           continue;
8080         QualType ParamTypes[2] = { *Enum, *Enum };
8081         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8082       }
8083     }
8084   }
8085 
8086   // C++ [over.built]p13:
8087   //
8088   //   For every cv-qualified or cv-unqualified object type T
8089   //   there exist candidate operator functions of the form
8090   //
8091   //      T*         operator+(T*, ptrdiff_t);
8092   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8093   //      T*         operator-(T*, ptrdiff_t);
8094   //      T*         operator+(ptrdiff_t, T*);
8095   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8096   //
8097   // C++ [over.built]p14:
8098   //
8099   //   For every T, where T is a pointer to object type, there
8100   //   exist candidate operator functions of the form
8101   //
8102   //      ptrdiff_t  operator-(T, T);
8103   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8104     /// Set of (canonical) types that we've already handled.
8105     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8106 
8107     for (int Arg = 0; Arg < 2; ++Arg) {
8108       QualType AsymmetricParamTypes[2] = {
8109         S.Context.getPointerDiffType(),
8110         S.Context.getPointerDiffType(),
8111       };
8112       for (BuiltinCandidateTypeSet::iterator
8113                 Ptr = CandidateTypes[Arg].pointer_begin(),
8114              PtrEnd = CandidateTypes[Arg].pointer_end();
8115            Ptr != PtrEnd; ++Ptr) {
8116         QualType PointeeTy = (*Ptr)->getPointeeType();
8117         if (!PointeeTy->isObjectType())
8118           continue;
8119 
8120         AsymmetricParamTypes[Arg] = *Ptr;
8121         if (Arg == 0 || Op == OO_Plus) {
8122           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8123           // T* operator+(ptrdiff_t, T*);
8124           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8125         }
8126         if (Op == OO_Minus) {
8127           // ptrdiff_t operator-(T, T);
8128           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8129             continue;
8130 
8131           QualType ParamTypes[2] = { *Ptr, *Ptr };
8132           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8133         }
8134       }
8135     }
8136   }
8137 
8138   // C++ [over.built]p12:
8139   //
8140   //   For every pair of promoted arithmetic types L and R, there
8141   //   exist candidate operator functions of the form
8142   //
8143   //        LR         operator*(L, R);
8144   //        LR         operator/(L, R);
8145   //        LR         operator+(L, R);
8146   //        LR         operator-(L, R);
8147   //        bool       operator<(L, R);
8148   //        bool       operator>(L, R);
8149   //        bool       operator<=(L, R);
8150   //        bool       operator>=(L, R);
8151   //        bool       operator==(L, R);
8152   //        bool       operator!=(L, R);
8153   //
8154   //   where LR is the result of the usual arithmetic conversions
8155   //   between types L and R.
8156   //
8157   // C++ [over.built]p24:
8158   //
8159   //   For every pair of promoted arithmetic types L and R, there exist
8160   //   candidate operator functions of the form
8161   //
8162   //        LR       operator?(bool, L, R);
8163   //
8164   //   where LR is the result of the usual arithmetic conversions
8165   //   between types L and R.
8166   // Our candidates ignore the first parameter.
8167   void addGenericBinaryArithmeticOverloads() {
8168     if (!HasArithmeticOrEnumeralCandidateType)
8169       return;
8170 
8171     for (unsigned Left = FirstPromotedArithmeticType;
8172          Left < LastPromotedArithmeticType; ++Left) {
8173       for (unsigned Right = FirstPromotedArithmeticType;
8174            Right < LastPromotedArithmeticType; ++Right) {
8175         QualType LandR[2] = { ArithmeticTypes[Left],
8176                               ArithmeticTypes[Right] };
8177         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8178       }
8179     }
8180 
8181     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8182     // conditional operator for vector types.
8183     for (BuiltinCandidateTypeSet::iterator
8184               Vec1 = CandidateTypes[0].vector_begin(),
8185            Vec1End = CandidateTypes[0].vector_end();
8186          Vec1 != Vec1End; ++Vec1) {
8187       for (BuiltinCandidateTypeSet::iterator
8188                 Vec2 = CandidateTypes[1].vector_begin(),
8189              Vec2End = CandidateTypes[1].vector_end();
8190            Vec2 != Vec2End; ++Vec2) {
8191         QualType LandR[2] = { *Vec1, *Vec2 };
8192         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8193       }
8194     }
8195   }
8196 
8197   // C++2a [over.built]p14:
8198   //
8199   //   For every integral type T there exists a candidate operator function
8200   //   of the form
8201   //
8202   //        std::strong_ordering operator<=>(T, T)
8203   //
8204   // C++2a [over.built]p15:
8205   //
8206   //   For every pair of floating-point types L and R, there exists a candidate
8207   //   operator function of the form
8208   //
8209   //       std::partial_ordering operator<=>(L, R);
8210   //
8211   // FIXME: The current specification for integral types doesn't play nice with
8212   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8213   // comparisons. Under the current spec this can lead to ambiguity during
8214   // overload resolution. For example:
8215   //
8216   //   enum A : int {a};
8217   //   auto x = (a <=> (long)42);
8218   //
8219   //   error: call is ambiguous for arguments 'A' and 'long'.
8220   //   note: candidate operator<=>(int, int)
8221   //   note: candidate operator<=>(long, long)
8222   //
8223   // To avoid this error, this function deviates from the specification and adds
8224   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8225   // arithmetic types (the same as the generic relational overloads).
8226   //
8227   // For now this function acts as a placeholder.
8228   void addThreeWayArithmeticOverloads() {
8229     addGenericBinaryArithmeticOverloads();
8230   }
8231 
8232   // C++ [over.built]p17:
8233   //
8234   //   For every pair of promoted integral types L and R, there
8235   //   exist candidate operator functions of the form
8236   //
8237   //      LR         operator%(L, R);
8238   //      LR         operator&(L, R);
8239   //      LR         operator^(L, R);
8240   //      LR         operator|(L, R);
8241   //      L          operator<<(L, R);
8242   //      L          operator>>(L, R);
8243   //
8244   //   where LR is the result of the usual arithmetic conversions
8245   //   between types L and R.
8246   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8247     if (!HasArithmeticOrEnumeralCandidateType)
8248       return;
8249 
8250     for (unsigned Left = FirstPromotedIntegralType;
8251          Left < LastPromotedIntegralType; ++Left) {
8252       for (unsigned Right = FirstPromotedIntegralType;
8253            Right < LastPromotedIntegralType; ++Right) {
8254         QualType LandR[2] = { ArithmeticTypes[Left],
8255                               ArithmeticTypes[Right] };
8256         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8257       }
8258     }
8259   }
8260 
8261   // C++ [over.built]p20:
8262   //
8263   //   For every pair (T, VQ), where T is an enumeration or
8264   //   pointer to member type and VQ is either volatile or
8265   //   empty, there exist candidate operator functions of the form
8266   //
8267   //        VQ T&      operator=(VQ T&, T);
8268   void addAssignmentMemberPointerOrEnumeralOverloads() {
8269     /// Set of (canonical) types that we've already handled.
8270     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8271 
8272     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8273       for (BuiltinCandidateTypeSet::iterator
8274                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8275              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8276            Enum != EnumEnd; ++Enum) {
8277         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8278           continue;
8279 
8280         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8281       }
8282 
8283       for (BuiltinCandidateTypeSet::iterator
8284                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8285              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8286            MemPtr != MemPtrEnd; ++MemPtr) {
8287         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8288           continue;
8289 
8290         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8291       }
8292     }
8293   }
8294 
8295   // C++ [over.built]p19:
8296   //
8297   //   For every pair (T, VQ), where T is any type and VQ is either
8298   //   volatile or empty, there exist candidate operator functions
8299   //   of the form
8300   //
8301   //        T*VQ&      operator=(T*VQ&, T*);
8302   //
8303   // C++ [over.built]p21:
8304   //
8305   //   For every pair (T, VQ), where T is a cv-qualified or
8306   //   cv-unqualified object type and VQ is either volatile or
8307   //   empty, there exist candidate operator functions of the form
8308   //
8309   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8310   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8311   void addAssignmentPointerOverloads(bool isEqualOp) {
8312     /// Set of (canonical) types that we've already handled.
8313     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8314 
8315     for (BuiltinCandidateTypeSet::iterator
8316               Ptr = CandidateTypes[0].pointer_begin(),
8317            PtrEnd = CandidateTypes[0].pointer_end();
8318          Ptr != PtrEnd; ++Ptr) {
8319       // If this is operator=, keep track of the builtin candidates we added.
8320       if (isEqualOp)
8321         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8322       else if (!(*Ptr)->getPointeeType()->isObjectType())
8323         continue;
8324 
8325       // non-volatile version
8326       QualType ParamTypes[2] = {
8327         S.Context.getLValueReferenceType(*Ptr),
8328         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8329       };
8330       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8331                             /*IsAssigmentOperator=*/ isEqualOp);
8332 
8333       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8334                           VisibleTypeConversionsQuals.hasVolatile();
8335       if (NeedVolatile) {
8336         // volatile version
8337         ParamTypes[0] =
8338           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8339         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8340                               /*IsAssigmentOperator=*/isEqualOp);
8341       }
8342 
8343       if (!(*Ptr).isRestrictQualified() &&
8344           VisibleTypeConversionsQuals.hasRestrict()) {
8345         // restrict version
8346         ParamTypes[0]
8347           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8348         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8349                               /*IsAssigmentOperator=*/isEqualOp);
8350 
8351         if (NeedVolatile) {
8352           // volatile restrict version
8353           ParamTypes[0]
8354             = S.Context.getLValueReferenceType(
8355                 S.Context.getCVRQualifiedType(*Ptr,
8356                                               (Qualifiers::Volatile |
8357                                                Qualifiers::Restrict)));
8358           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8359                                 /*IsAssigmentOperator=*/isEqualOp);
8360         }
8361       }
8362     }
8363 
8364     if (isEqualOp) {
8365       for (BuiltinCandidateTypeSet::iterator
8366                 Ptr = CandidateTypes[1].pointer_begin(),
8367              PtrEnd = CandidateTypes[1].pointer_end();
8368            Ptr != PtrEnd; ++Ptr) {
8369         // Make sure we don't add the same candidate twice.
8370         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8371           continue;
8372 
8373         QualType ParamTypes[2] = {
8374           S.Context.getLValueReferenceType(*Ptr),
8375           *Ptr,
8376         };
8377 
8378         // non-volatile version
8379         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8380                               /*IsAssigmentOperator=*/true);
8381 
8382         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8383                            VisibleTypeConversionsQuals.hasVolatile();
8384         if (NeedVolatile) {
8385           // volatile version
8386           ParamTypes[0] =
8387             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8388           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8389                                 /*IsAssigmentOperator=*/true);
8390         }
8391 
8392         if (!(*Ptr).isRestrictQualified() &&
8393             VisibleTypeConversionsQuals.hasRestrict()) {
8394           // restrict version
8395           ParamTypes[0]
8396             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8397           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8398                                 /*IsAssigmentOperator=*/true);
8399 
8400           if (NeedVolatile) {
8401             // volatile restrict version
8402             ParamTypes[0]
8403               = S.Context.getLValueReferenceType(
8404                   S.Context.getCVRQualifiedType(*Ptr,
8405                                                 (Qualifiers::Volatile |
8406                                                  Qualifiers::Restrict)));
8407             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8408                                   /*IsAssigmentOperator=*/true);
8409           }
8410         }
8411       }
8412     }
8413   }
8414 
8415   // C++ [over.built]p18:
8416   //
8417   //   For every triple (L, VQ, R), where L is an arithmetic type,
8418   //   VQ is either volatile or empty, and R is a promoted
8419   //   arithmetic type, there exist candidate operator functions of
8420   //   the form
8421   //
8422   //        VQ L&      operator=(VQ L&, R);
8423   //        VQ L&      operator*=(VQ L&, R);
8424   //        VQ L&      operator/=(VQ L&, R);
8425   //        VQ L&      operator+=(VQ L&, R);
8426   //        VQ L&      operator-=(VQ L&, R);
8427   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8428     if (!HasArithmeticOrEnumeralCandidateType)
8429       return;
8430 
8431     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8432       for (unsigned Right = FirstPromotedArithmeticType;
8433            Right < LastPromotedArithmeticType; ++Right) {
8434         QualType ParamTypes[2];
8435         ParamTypes[1] = ArithmeticTypes[Right];
8436 
8437         // Add this built-in operator as a candidate (VQ is empty).
8438         ParamTypes[0] =
8439           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8440         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8441                               /*IsAssigmentOperator=*/isEqualOp);
8442 
8443         // Add this built-in operator as a candidate (VQ is 'volatile').
8444         if (VisibleTypeConversionsQuals.hasVolatile()) {
8445           ParamTypes[0] =
8446             S.Context.getVolatileType(ArithmeticTypes[Left]);
8447           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8448           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8449                                 /*IsAssigmentOperator=*/isEqualOp);
8450         }
8451       }
8452     }
8453 
8454     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8455     for (BuiltinCandidateTypeSet::iterator
8456               Vec1 = CandidateTypes[0].vector_begin(),
8457            Vec1End = CandidateTypes[0].vector_end();
8458          Vec1 != Vec1End; ++Vec1) {
8459       for (BuiltinCandidateTypeSet::iterator
8460                 Vec2 = CandidateTypes[1].vector_begin(),
8461              Vec2End = CandidateTypes[1].vector_end();
8462            Vec2 != Vec2End; ++Vec2) {
8463         QualType ParamTypes[2];
8464         ParamTypes[1] = *Vec2;
8465         // Add this built-in operator as a candidate (VQ is empty).
8466         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8467         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8468                               /*IsAssigmentOperator=*/isEqualOp);
8469 
8470         // Add this built-in operator as a candidate (VQ is 'volatile').
8471         if (VisibleTypeConversionsQuals.hasVolatile()) {
8472           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8473           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8474           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8475                                 /*IsAssigmentOperator=*/isEqualOp);
8476         }
8477       }
8478     }
8479   }
8480 
8481   // C++ [over.built]p22:
8482   //
8483   //   For every triple (L, VQ, R), where L is an integral type, VQ
8484   //   is either volatile or empty, and R is a promoted integral
8485   //   type, there exist candidate operator functions of the form
8486   //
8487   //        VQ L&       operator%=(VQ L&, R);
8488   //        VQ L&       operator<<=(VQ L&, R);
8489   //        VQ L&       operator>>=(VQ L&, R);
8490   //        VQ L&       operator&=(VQ L&, R);
8491   //        VQ L&       operator^=(VQ L&, R);
8492   //        VQ L&       operator|=(VQ L&, R);
8493   void addAssignmentIntegralOverloads() {
8494     if (!HasArithmeticOrEnumeralCandidateType)
8495       return;
8496 
8497     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8498       for (unsigned Right = FirstPromotedIntegralType;
8499            Right < LastPromotedIntegralType; ++Right) {
8500         QualType ParamTypes[2];
8501         ParamTypes[1] = ArithmeticTypes[Right];
8502 
8503         // Add this built-in operator as a candidate (VQ is empty).
8504         ParamTypes[0] =
8505           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8506         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8507         if (VisibleTypeConversionsQuals.hasVolatile()) {
8508           // Add this built-in operator as a candidate (VQ is 'volatile').
8509           ParamTypes[0] = ArithmeticTypes[Left];
8510           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8511           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8512           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8513         }
8514       }
8515     }
8516   }
8517 
8518   // C++ [over.operator]p23:
8519   //
8520   //   There also exist candidate operator functions of the form
8521   //
8522   //        bool        operator!(bool);
8523   //        bool        operator&&(bool, bool);
8524   //        bool        operator||(bool, bool);
8525   void addExclaimOverload() {
8526     QualType ParamTy = S.Context.BoolTy;
8527     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8528                           /*IsAssignmentOperator=*/false,
8529                           /*NumContextualBoolArguments=*/1);
8530   }
8531   void addAmpAmpOrPipePipeOverload() {
8532     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8533     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8534                           /*IsAssignmentOperator=*/false,
8535                           /*NumContextualBoolArguments=*/2);
8536   }
8537 
8538   // C++ [over.built]p13:
8539   //
8540   //   For every cv-qualified or cv-unqualified object type T there
8541   //   exist candidate operator functions of the form
8542   //
8543   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8544   //        T&         operator[](T*, ptrdiff_t);
8545   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8546   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8547   //        T&         operator[](ptrdiff_t, T*);
8548   void addSubscriptOverloads() {
8549     for (BuiltinCandidateTypeSet::iterator
8550               Ptr = CandidateTypes[0].pointer_begin(),
8551            PtrEnd = CandidateTypes[0].pointer_end();
8552          Ptr != PtrEnd; ++Ptr) {
8553       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8554       QualType PointeeType = (*Ptr)->getPointeeType();
8555       if (!PointeeType->isObjectType())
8556         continue;
8557 
8558       // T& operator[](T*, ptrdiff_t)
8559       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8560     }
8561 
8562     for (BuiltinCandidateTypeSet::iterator
8563               Ptr = CandidateTypes[1].pointer_begin(),
8564            PtrEnd = CandidateTypes[1].pointer_end();
8565          Ptr != PtrEnd; ++Ptr) {
8566       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8567       QualType PointeeType = (*Ptr)->getPointeeType();
8568       if (!PointeeType->isObjectType())
8569         continue;
8570 
8571       // T& operator[](ptrdiff_t, T*)
8572       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8573     }
8574   }
8575 
8576   // C++ [over.built]p11:
8577   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8578   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8579   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8580   //    there exist candidate operator functions of the form
8581   //
8582   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8583   //
8584   //    where CV12 is the union of CV1 and CV2.
8585   void addArrowStarOverloads() {
8586     for (BuiltinCandidateTypeSet::iterator
8587              Ptr = CandidateTypes[0].pointer_begin(),
8588            PtrEnd = CandidateTypes[0].pointer_end();
8589          Ptr != PtrEnd; ++Ptr) {
8590       QualType C1Ty = (*Ptr);
8591       QualType C1;
8592       QualifierCollector Q1;
8593       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8594       if (!isa<RecordType>(C1))
8595         continue;
8596       // heuristic to reduce number of builtin candidates in the set.
8597       // Add volatile/restrict version only if there are conversions to a
8598       // volatile/restrict type.
8599       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8600         continue;
8601       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8602         continue;
8603       for (BuiltinCandidateTypeSet::iterator
8604                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8605              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8606            MemPtr != MemPtrEnd; ++MemPtr) {
8607         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8608         QualType C2 = QualType(mptr->getClass(), 0);
8609         C2 = C2.getUnqualifiedType();
8610         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8611           break;
8612         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8613         // build CV12 T&
8614         QualType T = mptr->getPointeeType();
8615         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8616             T.isVolatileQualified())
8617           continue;
8618         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8619             T.isRestrictQualified())
8620           continue;
8621         T = Q1.apply(S.Context, T);
8622         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8623       }
8624     }
8625   }
8626 
8627   // Note that we don't consider the first argument, since it has been
8628   // contextually converted to bool long ago. The candidates below are
8629   // therefore added as binary.
8630   //
8631   // C++ [over.built]p25:
8632   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8633   //   enumeration type, there exist candidate operator functions of the form
8634   //
8635   //        T        operator?(bool, T, T);
8636   //
8637   void addConditionalOperatorOverloads() {
8638     /// Set of (canonical) types that we've already handled.
8639     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8640 
8641     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8642       for (BuiltinCandidateTypeSet::iterator
8643                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8644              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8645            Ptr != PtrEnd; ++Ptr) {
8646         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8647           continue;
8648 
8649         QualType ParamTypes[2] = { *Ptr, *Ptr };
8650         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8651       }
8652 
8653       for (BuiltinCandidateTypeSet::iterator
8654                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8655              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8656            MemPtr != MemPtrEnd; ++MemPtr) {
8657         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8658           continue;
8659 
8660         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8661         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8662       }
8663 
8664       if (S.getLangOpts().CPlusPlus11) {
8665         for (BuiltinCandidateTypeSet::iterator
8666                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8667                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8668              Enum != EnumEnd; ++Enum) {
8669           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8670             continue;
8671 
8672           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8673             continue;
8674 
8675           QualType ParamTypes[2] = { *Enum, *Enum };
8676           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8677         }
8678       }
8679     }
8680   }
8681 };
8682 
8683 } // end anonymous namespace
8684 
8685 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8686 /// operator overloads to the candidate set (C++ [over.built]), based
8687 /// on the operator @p Op and the arguments given. For example, if the
8688 /// operator is a binary '+', this routine might add "int
8689 /// operator+(int, int)" to cover integer addition.
8690 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8691                                         SourceLocation OpLoc,
8692                                         ArrayRef<Expr *> Args,
8693                                         OverloadCandidateSet &CandidateSet) {
8694   // Find all of the types that the arguments can convert to, but only
8695   // if the operator we're looking at has built-in operator candidates
8696   // that make use of these types. Also record whether we encounter non-record
8697   // candidate types or either arithmetic or enumeral candidate types.
8698   Qualifiers VisibleTypeConversionsQuals;
8699   VisibleTypeConversionsQuals.addConst();
8700   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8701     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8702 
8703   bool HasNonRecordCandidateType = false;
8704   bool HasArithmeticOrEnumeralCandidateType = false;
8705   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8706   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8707     CandidateTypes.emplace_back(*this);
8708     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8709                                                  OpLoc,
8710                                                  true,
8711                                                  (Op == OO_Exclaim ||
8712                                                   Op == OO_AmpAmp ||
8713                                                   Op == OO_PipePipe),
8714                                                  VisibleTypeConversionsQuals);
8715     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8716         CandidateTypes[ArgIdx].hasNonRecordTypes();
8717     HasArithmeticOrEnumeralCandidateType =
8718         HasArithmeticOrEnumeralCandidateType ||
8719         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8720   }
8721 
8722   // Exit early when no non-record types have been added to the candidate set
8723   // for any of the arguments to the operator.
8724   //
8725   // We can't exit early for !, ||, or &&, since there we have always have
8726   // 'bool' overloads.
8727   if (!HasNonRecordCandidateType &&
8728       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8729     return;
8730 
8731   // Setup an object to manage the common state for building overloads.
8732   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8733                                            VisibleTypeConversionsQuals,
8734                                            HasArithmeticOrEnumeralCandidateType,
8735                                            CandidateTypes, CandidateSet);
8736 
8737   // Dispatch over the operation to add in only those overloads which apply.
8738   switch (Op) {
8739   case OO_None:
8740   case NUM_OVERLOADED_OPERATORS:
8741     llvm_unreachable("Expected an overloaded operator");
8742 
8743   case OO_New:
8744   case OO_Delete:
8745   case OO_Array_New:
8746   case OO_Array_Delete:
8747   case OO_Call:
8748     llvm_unreachable(
8749                     "Special operators don't use AddBuiltinOperatorCandidates");
8750 
8751   case OO_Comma:
8752   case OO_Arrow:
8753   case OO_Coawait:
8754     // C++ [over.match.oper]p3:
8755     //   -- For the operator ',', the unary operator '&', the
8756     //      operator '->', or the operator 'co_await', the
8757     //      built-in candidates set is empty.
8758     break;
8759 
8760   case OO_Plus: // '+' is either unary or binary
8761     if (Args.size() == 1)
8762       OpBuilder.addUnaryPlusPointerOverloads();
8763     LLVM_FALLTHROUGH;
8764 
8765   case OO_Minus: // '-' is either unary or binary
8766     if (Args.size() == 1) {
8767       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8768     } else {
8769       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8770       OpBuilder.addGenericBinaryArithmeticOverloads();
8771     }
8772     break;
8773 
8774   case OO_Star: // '*' is either unary or binary
8775     if (Args.size() == 1)
8776       OpBuilder.addUnaryStarPointerOverloads();
8777     else
8778       OpBuilder.addGenericBinaryArithmeticOverloads();
8779     break;
8780 
8781   case OO_Slash:
8782     OpBuilder.addGenericBinaryArithmeticOverloads();
8783     break;
8784 
8785   case OO_PlusPlus:
8786   case OO_MinusMinus:
8787     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8788     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8789     break;
8790 
8791   case OO_EqualEqual:
8792   case OO_ExclaimEqual:
8793     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8794     LLVM_FALLTHROUGH;
8795 
8796   case OO_Less:
8797   case OO_Greater:
8798   case OO_LessEqual:
8799   case OO_GreaterEqual:
8800     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8801     OpBuilder.addGenericBinaryArithmeticOverloads();
8802     break;
8803 
8804   case OO_Spaceship:
8805     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8806     OpBuilder.addThreeWayArithmeticOverloads();
8807     break;
8808 
8809   case OO_Percent:
8810   case OO_Caret:
8811   case OO_Pipe:
8812   case OO_LessLess:
8813   case OO_GreaterGreater:
8814     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8815     break;
8816 
8817   case OO_Amp: // '&' is either unary or binary
8818     if (Args.size() == 1)
8819       // C++ [over.match.oper]p3:
8820       //   -- For the operator ',', the unary operator '&', or the
8821       //      operator '->', the built-in candidates set is empty.
8822       break;
8823 
8824     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8825     break;
8826 
8827   case OO_Tilde:
8828     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8829     break;
8830 
8831   case OO_Equal:
8832     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8833     LLVM_FALLTHROUGH;
8834 
8835   case OO_PlusEqual:
8836   case OO_MinusEqual:
8837     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8838     LLVM_FALLTHROUGH;
8839 
8840   case OO_StarEqual:
8841   case OO_SlashEqual:
8842     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8843     break;
8844 
8845   case OO_PercentEqual:
8846   case OO_LessLessEqual:
8847   case OO_GreaterGreaterEqual:
8848   case OO_AmpEqual:
8849   case OO_CaretEqual:
8850   case OO_PipeEqual:
8851     OpBuilder.addAssignmentIntegralOverloads();
8852     break;
8853 
8854   case OO_Exclaim:
8855     OpBuilder.addExclaimOverload();
8856     break;
8857 
8858   case OO_AmpAmp:
8859   case OO_PipePipe:
8860     OpBuilder.addAmpAmpOrPipePipeOverload();
8861     break;
8862 
8863   case OO_Subscript:
8864     OpBuilder.addSubscriptOverloads();
8865     break;
8866 
8867   case OO_ArrowStar:
8868     OpBuilder.addArrowStarOverloads();
8869     break;
8870 
8871   case OO_Conditional:
8872     OpBuilder.addConditionalOperatorOverloads();
8873     OpBuilder.addGenericBinaryArithmeticOverloads();
8874     break;
8875   }
8876 }
8877 
8878 /// Add function candidates found via argument-dependent lookup
8879 /// to the set of overloading candidates.
8880 ///
8881 /// This routine performs argument-dependent name lookup based on the
8882 /// given function name (which may also be an operator name) and adds
8883 /// all of the overload candidates found by ADL to the overload
8884 /// candidate set (C++ [basic.lookup.argdep]).
8885 void
8886 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8887                                            SourceLocation Loc,
8888                                            ArrayRef<Expr *> Args,
8889                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8890                                            OverloadCandidateSet& CandidateSet,
8891                                            bool PartialOverloading) {
8892   ADLResult Fns;
8893 
8894   // FIXME: This approach for uniquing ADL results (and removing
8895   // redundant candidates from the set) relies on pointer-equality,
8896   // which means we need to key off the canonical decl.  However,
8897   // always going back to the canonical decl might not get us the
8898   // right set of default arguments.  What default arguments are
8899   // we supposed to consider on ADL candidates, anyway?
8900 
8901   // FIXME: Pass in the explicit template arguments?
8902   ArgumentDependentLookup(Name, Loc, Args, Fns);
8903 
8904   // Erase all of the candidates we already knew about.
8905   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8906                                    CandEnd = CandidateSet.end();
8907        Cand != CandEnd; ++Cand)
8908     if (Cand->Function) {
8909       Fns.erase(Cand->Function);
8910       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8911         Fns.erase(FunTmpl);
8912     }
8913 
8914   // For each of the ADL candidates we found, add it to the overload
8915   // set.
8916   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8917     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8918     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8919       if (ExplicitTemplateArgs)
8920         continue;
8921 
8922       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8923                            PartialOverloading);
8924     } else
8925       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8926                                    FoundDecl, ExplicitTemplateArgs,
8927                                    Args, CandidateSet, PartialOverloading);
8928   }
8929 }
8930 
8931 namespace {
8932 enum class Comparison { Equal, Better, Worse };
8933 }
8934 
8935 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8936 /// overload resolution.
8937 ///
8938 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8939 /// Cand1's first N enable_if attributes have precisely the same conditions as
8940 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8941 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8942 ///
8943 /// Note that you can have a pair of candidates such that Cand1's enable_if
8944 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8945 /// worse than Cand1's.
8946 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8947                                        const FunctionDecl *Cand2) {
8948   // Common case: One (or both) decls don't have enable_if attrs.
8949   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8950   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8951   if (!Cand1Attr || !Cand2Attr) {
8952     if (Cand1Attr == Cand2Attr)
8953       return Comparison::Equal;
8954     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8955   }
8956 
8957   // FIXME: The next several lines are just
8958   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8959   // instead of reverse order which is how they're stored in the AST.
8960   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8961   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8962 
8963   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8964   // has fewer enable_if attributes than Cand2.
8965   if (Cand1Attrs.size() < Cand2Attrs.size())
8966     return Comparison::Worse;
8967 
8968   auto Cand1I = Cand1Attrs.begin();
8969   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8970   for (auto &Cand2A : Cand2Attrs) {
8971     Cand1ID.clear();
8972     Cand2ID.clear();
8973 
8974     auto &Cand1A = *Cand1I++;
8975     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8976     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8977     if (Cand1ID != Cand2ID)
8978       return Comparison::Worse;
8979   }
8980 
8981   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8982 }
8983 
8984 /// isBetterOverloadCandidate - Determines whether the first overload
8985 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8986 bool clang::isBetterOverloadCandidate(
8987     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8988     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8989   // Define viable functions to be better candidates than non-viable
8990   // functions.
8991   if (!Cand2.Viable)
8992     return Cand1.Viable;
8993   else if (!Cand1.Viable)
8994     return false;
8995 
8996   // C++ [over.match.best]p1:
8997   //
8998   //   -- if F is a static member function, ICS1(F) is defined such
8999   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9000   //      any function G, and, symmetrically, ICS1(G) is neither
9001   //      better nor worse than ICS1(F).
9002   unsigned StartArg = 0;
9003   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9004     StartArg = 1;
9005 
9006   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9007     // We don't allow incompatible pointer conversions in C++.
9008     if (!S.getLangOpts().CPlusPlus)
9009       return ICS.isStandard() &&
9010              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9011 
9012     // The only ill-formed conversion we allow in C++ is the string literal to
9013     // char* conversion, which is only considered ill-formed after C++11.
9014     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9015            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9016   };
9017 
9018   // Define functions that don't require ill-formed conversions for a given
9019   // argument to be better candidates than functions that do.
9020   unsigned NumArgs = Cand1.Conversions.size();
9021   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9022   bool HasBetterConversion = false;
9023   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9024     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9025     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9026     if (Cand1Bad != Cand2Bad) {
9027       if (Cand1Bad)
9028         return false;
9029       HasBetterConversion = true;
9030     }
9031   }
9032 
9033   if (HasBetterConversion)
9034     return true;
9035 
9036   // C++ [over.match.best]p1:
9037   //   A viable function F1 is defined to be a better function than another
9038   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9039   //   conversion sequence than ICSi(F2), and then...
9040   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9041     switch (CompareImplicitConversionSequences(S, Loc,
9042                                                Cand1.Conversions[ArgIdx],
9043                                                Cand2.Conversions[ArgIdx])) {
9044     case ImplicitConversionSequence::Better:
9045       // Cand1 has a better conversion sequence.
9046       HasBetterConversion = true;
9047       break;
9048 
9049     case ImplicitConversionSequence::Worse:
9050       // Cand1 can't be better than Cand2.
9051       return false;
9052 
9053     case ImplicitConversionSequence::Indistinguishable:
9054       // Do nothing.
9055       break;
9056     }
9057   }
9058 
9059   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9060   //       ICSj(F2), or, if not that,
9061   if (HasBetterConversion)
9062     return true;
9063 
9064   //   -- the context is an initialization by user-defined conversion
9065   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9066   //      from the return type of F1 to the destination type (i.e.,
9067   //      the type of the entity being initialized) is a better
9068   //      conversion sequence than the standard conversion sequence
9069   //      from the return type of F2 to the destination type.
9070   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9071       Cand1.Function && Cand2.Function &&
9072       isa<CXXConversionDecl>(Cand1.Function) &&
9073       isa<CXXConversionDecl>(Cand2.Function)) {
9074     // First check whether we prefer one of the conversion functions over the
9075     // other. This only distinguishes the results in non-standard, extension
9076     // cases such as the conversion from a lambda closure type to a function
9077     // pointer or block.
9078     ImplicitConversionSequence::CompareKind Result =
9079         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9080     if (Result == ImplicitConversionSequence::Indistinguishable)
9081       Result = CompareStandardConversionSequences(S, Loc,
9082                                                   Cand1.FinalConversion,
9083                                                   Cand2.FinalConversion);
9084 
9085     if (Result != ImplicitConversionSequence::Indistinguishable)
9086       return Result == ImplicitConversionSequence::Better;
9087 
9088     // FIXME: Compare kind of reference binding if conversion functions
9089     // convert to a reference type used in direct reference binding, per
9090     // C++14 [over.match.best]p1 section 2 bullet 3.
9091   }
9092 
9093   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9094   // as combined with the resolution to CWG issue 243.
9095   //
9096   // When the context is initialization by constructor ([over.match.ctor] or
9097   // either phase of [over.match.list]), a constructor is preferred over
9098   // a conversion function.
9099   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9100       Cand1.Function && Cand2.Function &&
9101       isa<CXXConstructorDecl>(Cand1.Function) !=
9102           isa<CXXConstructorDecl>(Cand2.Function))
9103     return isa<CXXConstructorDecl>(Cand1.Function);
9104 
9105   //    -- F1 is a non-template function and F2 is a function template
9106   //       specialization, or, if not that,
9107   bool Cand1IsSpecialization = Cand1.Function &&
9108                                Cand1.Function->getPrimaryTemplate();
9109   bool Cand2IsSpecialization = Cand2.Function &&
9110                                Cand2.Function->getPrimaryTemplate();
9111   if (Cand1IsSpecialization != Cand2IsSpecialization)
9112     return Cand2IsSpecialization;
9113 
9114   //   -- F1 and F2 are function template specializations, and the function
9115   //      template for F1 is more specialized than the template for F2
9116   //      according to the partial ordering rules described in 14.5.5.2, or,
9117   //      if not that,
9118   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9119     if (FunctionTemplateDecl *BetterTemplate
9120           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9121                                          Cand2.Function->getPrimaryTemplate(),
9122                                          Loc,
9123                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9124                                                              : TPOC_Call,
9125                                          Cand1.ExplicitCallArguments,
9126                                          Cand2.ExplicitCallArguments))
9127       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9128   }
9129 
9130   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9131   // A derived-class constructor beats an (inherited) base class constructor.
9132   bool Cand1IsInherited =
9133       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9134   bool Cand2IsInherited =
9135       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9136   if (Cand1IsInherited != Cand2IsInherited)
9137     return Cand2IsInherited;
9138   else if (Cand1IsInherited) {
9139     assert(Cand2IsInherited);
9140     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9141     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9142     if (Cand1Class->isDerivedFrom(Cand2Class))
9143       return true;
9144     if (Cand2Class->isDerivedFrom(Cand1Class))
9145       return false;
9146     // Inherited from sibling base classes: still ambiguous.
9147   }
9148 
9149   // Check C++17 tie-breakers for deduction guides.
9150   {
9151     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9152     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9153     if (Guide1 && Guide2) {
9154       //  -- F1 is generated from a deduction-guide and F2 is not
9155       if (Guide1->isImplicit() != Guide2->isImplicit())
9156         return Guide2->isImplicit();
9157 
9158       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9159       if (Guide1->isCopyDeductionCandidate())
9160         return true;
9161     }
9162   }
9163 
9164   // Check for enable_if value-based overload resolution.
9165   if (Cand1.Function && Cand2.Function) {
9166     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9167     if (Cmp != Comparison::Equal)
9168       return Cmp == Comparison::Better;
9169   }
9170 
9171   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9172     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9173     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9174            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9175   }
9176 
9177   bool HasPS1 = Cand1.Function != nullptr &&
9178                 functionHasPassObjectSizeParams(Cand1.Function);
9179   bool HasPS2 = Cand2.Function != nullptr &&
9180                 functionHasPassObjectSizeParams(Cand2.Function);
9181   return HasPS1 != HasPS2 && HasPS1;
9182 }
9183 
9184 /// Determine whether two declarations are "equivalent" for the purposes of
9185 /// name lookup and overload resolution. This applies when the same internal/no
9186 /// linkage entity is defined by two modules (probably by textually including
9187 /// the same header). In such a case, we don't consider the declarations to
9188 /// declare the same entity, but we also don't want lookups with both
9189 /// declarations visible to be ambiguous in some cases (this happens when using
9190 /// a modularized libstdc++).
9191 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9192                                                   const NamedDecl *B) {
9193   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9194   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9195   if (!VA || !VB)
9196     return false;
9197 
9198   // The declarations must be declaring the same name as an internal linkage
9199   // entity in different modules.
9200   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9201           VB->getDeclContext()->getRedeclContext()) ||
9202       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9203           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9204       VA->isExternallyVisible() || VB->isExternallyVisible())
9205     return false;
9206 
9207   // Check that the declarations appear to be equivalent.
9208   //
9209   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9210   // For constants and functions, we should check the initializer or body is
9211   // the same. For non-constant variables, we shouldn't allow it at all.
9212   if (Context.hasSameType(VA->getType(), VB->getType()))
9213     return true;
9214 
9215   // Enum constants within unnamed enumerations will have different types, but
9216   // may still be similar enough to be interchangeable for our purposes.
9217   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9218     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9219       // Only handle anonymous enums. If the enumerations were named and
9220       // equivalent, they would have been merged to the same type.
9221       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9222       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9223       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9224           !Context.hasSameType(EnumA->getIntegerType(),
9225                                EnumB->getIntegerType()))
9226         return false;
9227       // Allow this only if the value is the same for both enumerators.
9228       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9229     }
9230   }
9231 
9232   // Nothing else is sufficiently similar.
9233   return false;
9234 }
9235 
9236 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9237     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9238   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9239 
9240   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9241   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9242       << !M << (M ? M->getFullModuleName() : "");
9243 
9244   for (auto *E : Equiv) {
9245     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9246     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9247         << !M << (M ? M->getFullModuleName() : "");
9248   }
9249 }
9250 
9251 /// Computes the best viable function (C++ 13.3.3)
9252 /// within an overload candidate set.
9253 ///
9254 /// \param Loc The location of the function name (or operator symbol) for
9255 /// which overload resolution occurs.
9256 ///
9257 /// \param Best If overload resolution was successful or found a deleted
9258 /// function, \p Best points to the candidate function found.
9259 ///
9260 /// \returns The result of overload resolution.
9261 OverloadingResult
9262 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9263                                          iterator &Best) {
9264   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9265   std::transform(begin(), end(), std::back_inserter(Candidates),
9266                  [](OverloadCandidate &Cand) { return &Cand; });
9267 
9268   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9269   // are accepted by both clang and NVCC. However, during a particular
9270   // compilation mode only one call variant is viable. We need to
9271   // exclude non-viable overload candidates from consideration based
9272   // only on their host/device attributes. Specifically, if one
9273   // candidate call is WrongSide and the other is SameSide, we ignore
9274   // the WrongSide candidate.
9275   if (S.getLangOpts().CUDA) {
9276     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9277     bool ContainsSameSideCandidate =
9278         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9279           return Cand->Function &&
9280                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9281                      Sema::CFP_SameSide;
9282         });
9283     if (ContainsSameSideCandidate) {
9284       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9285         return Cand->Function &&
9286                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9287                    Sema::CFP_WrongSide;
9288       };
9289       llvm::erase_if(Candidates, IsWrongSideCandidate);
9290     }
9291   }
9292 
9293   // Find the best viable function.
9294   Best = end();
9295   for (auto *Cand : Candidates)
9296     if (Cand->Viable)
9297       if (Best == end() ||
9298           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9299         Best = Cand;
9300 
9301   // If we didn't find any viable functions, abort.
9302   if (Best == end())
9303     return OR_No_Viable_Function;
9304 
9305   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9306 
9307   // Make sure that this function is better than every other viable
9308   // function. If not, we have an ambiguity.
9309   for (auto *Cand : Candidates) {
9310     if (Cand->Viable && Cand != Best &&
9311         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9312       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9313                                                    Cand->Function)) {
9314         EquivalentCands.push_back(Cand->Function);
9315         continue;
9316       }
9317 
9318       Best = end();
9319       return OR_Ambiguous;
9320     }
9321   }
9322 
9323   // Best is the best viable function.
9324   if (Best->Function &&
9325       (Best->Function->isDeleted() ||
9326        S.isFunctionConsideredUnavailable(Best->Function)))
9327     return OR_Deleted;
9328 
9329   if (!EquivalentCands.empty())
9330     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9331                                                     EquivalentCands);
9332 
9333   return OR_Success;
9334 }
9335 
9336 namespace {
9337 
9338 enum OverloadCandidateKind {
9339   oc_function,
9340   oc_method,
9341   oc_constructor,
9342   oc_implicit_default_constructor,
9343   oc_implicit_copy_constructor,
9344   oc_implicit_move_constructor,
9345   oc_implicit_copy_assignment,
9346   oc_implicit_move_assignment,
9347   oc_inherited_constructor
9348 };
9349 
9350 enum OverloadCandidateSelect {
9351   ocs_non_template,
9352   ocs_template,
9353   ocs_described_template,
9354 };
9355 
9356 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9357 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9358                           std::string &Description) {
9359 
9360   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9361   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9362     isTemplate = true;
9363     Description = S.getTemplateArgumentBindingsText(
9364         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9365   }
9366 
9367   OverloadCandidateSelect Select = [&]() {
9368     if (!Description.empty())
9369       return ocs_described_template;
9370     return isTemplate ? ocs_template : ocs_non_template;
9371   }();
9372 
9373   OverloadCandidateKind Kind = [&]() {
9374     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9375       if (!Ctor->isImplicit()) {
9376         if (isa<ConstructorUsingShadowDecl>(Found))
9377           return oc_inherited_constructor;
9378         else
9379           return oc_constructor;
9380       }
9381 
9382       if (Ctor->isDefaultConstructor())
9383         return oc_implicit_default_constructor;
9384 
9385       if (Ctor->isMoveConstructor())
9386         return oc_implicit_move_constructor;
9387 
9388       assert(Ctor->isCopyConstructor() &&
9389              "unexpected sort of implicit constructor");
9390       return oc_implicit_copy_constructor;
9391     }
9392 
9393     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9394       // This actually gets spelled 'candidate function' for now, but
9395       // it doesn't hurt to split it out.
9396       if (!Meth->isImplicit())
9397         return oc_method;
9398 
9399       if (Meth->isMoveAssignmentOperator())
9400         return oc_implicit_move_assignment;
9401 
9402       if (Meth->isCopyAssignmentOperator())
9403         return oc_implicit_copy_assignment;
9404 
9405       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9406       return oc_method;
9407     }
9408 
9409     return oc_function;
9410   }();
9411 
9412   return std::make_pair(Kind, Select);
9413 }
9414 
9415 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9416   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9417   // set.
9418   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9419     S.Diag(FoundDecl->getLocation(),
9420            diag::note_ovl_candidate_inherited_constructor)
9421       << Shadow->getNominatedBaseClass();
9422 }
9423 
9424 } // end anonymous namespace
9425 
9426 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9427                                     const FunctionDecl *FD) {
9428   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9429     bool AlwaysTrue;
9430     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9431       return false;
9432     if (!AlwaysTrue)
9433       return false;
9434   }
9435   return true;
9436 }
9437 
9438 /// Returns true if we can take the address of the function.
9439 ///
9440 /// \param Complain - If true, we'll emit a diagnostic
9441 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9442 ///   we in overload resolution?
9443 /// \param Loc - The location of the statement we're complaining about. Ignored
9444 ///   if we're not complaining, or if we're in overload resolution.
9445 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9446                                               bool Complain,
9447                                               bool InOverloadResolution,
9448                                               SourceLocation Loc) {
9449   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9450     if (Complain) {
9451       if (InOverloadResolution)
9452         S.Diag(FD->getLocStart(),
9453                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9454       else
9455         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9456     }
9457     return false;
9458   }
9459 
9460   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9461     return P->hasAttr<PassObjectSizeAttr>();
9462   });
9463   if (I == FD->param_end())
9464     return true;
9465 
9466   if (Complain) {
9467     // Add one to ParamNo because it's user-facing
9468     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9469     if (InOverloadResolution)
9470       S.Diag(FD->getLocation(),
9471              diag::note_ovl_candidate_has_pass_object_size_params)
9472           << ParamNo;
9473     else
9474       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9475           << FD << ParamNo;
9476   }
9477   return false;
9478 }
9479 
9480 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9481                                                const FunctionDecl *FD) {
9482   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9483                                            /*InOverloadResolution=*/true,
9484                                            /*Loc=*/SourceLocation());
9485 }
9486 
9487 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9488                                              bool Complain,
9489                                              SourceLocation Loc) {
9490   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9491                                              /*InOverloadResolution=*/false,
9492                                              Loc);
9493 }
9494 
9495 // Notes the location of an overload candidate.
9496 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9497                                  QualType DestType, bool TakingAddress) {
9498   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9499     return;
9500   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9501     return;
9502 
9503   std::string FnDesc;
9504   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9505       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9506   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9507                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9508                          << Fn << FnDesc;
9509 
9510   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9511   Diag(Fn->getLocation(), PD);
9512   MaybeEmitInheritedConstructorNote(*this, Found);
9513 }
9514 
9515 // Notes the location of all overload candidates designated through
9516 // OverloadedExpr
9517 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9518                                      bool TakingAddress) {
9519   assert(OverloadedExpr->getType() == Context.OverloadTy);
9520 
9521   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9522   OverloadExpr *OvlExpr = Ovl.Expression;
9523 
9524   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9525                             IEnd = OvlExpr->decls_end();
9526        I != IEnd; ++I) {
9527     if (FunctionTemplateDecl *FunTmpl =
9528                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9529       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9530                             TakingAddress);
9531     } else if (FunctionDecl *Fun
9532                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9533       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9534     }
9535   }
9536 }
9537 
9538 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9539 /// "lead" diagnostic; it will be given two arguments, the source and
9540 /// target types of the conversion.
9541 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9542                                  Sema &S,
9543                                  SourceLocation CaretLoc,
9544                                  const PartialDiagnostic &PDiag) const {
9545   S.Diag(CaretLoc, PDiag)
9546     << Ambiguous.getFromType() << Ambiguous.getToType();
9547   // FIXME: The note limiting machinery is borrowed from
9548   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9549   // refactoring here.
9550   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9551   unsigned CandsShown = 0;
9552   AmbiguousConversionSequence::const_iterator I, E;
9553   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9554     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9555       break;
9556     ++CandsShown;
9557     S.NoteOverloadCandidate(I->first, I->second);
9558   }
9559   if (I != E)
9560     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9561 }
9562 
9563 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9564                                   unsigned I, bool TakingCandidateAddress) {
9565   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9566   assert(Conv.isBad());
9567   assert(Cand->Function && "for now, candidate must be a function");
9568   FunctionDecl *Fn = Cand->Function;
9569 
9570   // There's a conversion slot for the object argument if this is a
9571   // non-constructor method.  Note that 'I' corresponds the
9572   // conversion-slot index.
9573   bool isObjectArgument = false;
9574   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9575     if (I == 0)
9576       isObjectArgument = true;
9577     else
9578       I--;
9579   }
9580 
9581   std::string FnDesc;
9582   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9583       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9584 
9585   Expr *FromExpr = Conv.Bad.FromExpr;
9586   QualType FromTy = Conv.Bad.getFromType();
9587   QualType ToTy = Conv.Bad.getToType();
9588 
9589   if (FromTy == S.Context.OverloadTy) {
9590     assert(FromExpr && "overload set argument came from implicit argument?");
9591     Expr *E = FromExpr->IgnoreParens();
9592     if (isa<UnaryOperator>(E))
9593       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9594     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9595 
9596     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9597         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9598         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9599         << Name << I + 1;
9600     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9601     return;
9602   }
9603 
9604   // Do some hand-waving analysis to see if the non-viability is due
9605   // to a qualifier mismatch.
9606   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9607   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9608   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9609     CToTy = RT->getPointeeType();
9610   else {
9611     // TODO: detect and diagnose the full richness of const mismatches.
9612     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9613       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9614         CFromTy = FromPT->getPointeeType();
9615         CToTy = ToPT->getPointeeType();
9616       }
9617   }
9618 
9619   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9620       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9621     Qualifiers FromQs = CFromTy.getQualifiers();
9622     Qualifiers ToQs = CToTy.getQualifiers();
9623 
9624     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9625       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9626           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9627           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9628           << ToTy << (unsigned)isObjectArgument << I + 1;
9629       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9630       return;
9631     }
9632 
9633     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9634       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9635           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9636           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9637           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9638           << (unsigned)isObjectArgument << I + 1;
9639       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9640       return;
9641     }
9642 
9643     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9644       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9645           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9646           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9647           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9648           << (unsigned)isObjectArgument << I + 1;
9649       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9650       return;
9651     }
9652 
9653     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9654       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9655           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9656           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9657           << FromQs.hasUnaligned() << I + 1;
9658       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9659       return;
9660     }
9661 
9662     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9663     assert(CVR && "unexpected qualifiers mismatch");
9664 
9665     if (isObjectArgument) {
9666       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9667           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9668           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9669           << (CVR - 1);
9670     } else {
9671       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9672           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9673           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9674           << (CVR - 1) << I + 1;
9675     }
9676     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9677     return;
9678   }
9679 
9680   // Special diagnostic for failure to convert an initializer list, since
9681   // telling the user that it has type void is not useful.
9682   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9683     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9684         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9685         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9686         << ToTy << (unsigned)isObjectArgument << I + 1;
9687     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9688     return;
9689   }
9690 
9691   // Diagnose references or pointers to incomplete types differently,
9692   // since it's far from impossible that the incompleteness triggered
9693   // the failure.
9694   QualType TempFromTy = FromTy.getNonReferenceType();
9695   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9696     TempFromTy = PTy->getPointeeType();
9697   if (TempFromTy->isIncompleteType()) {
9698     // Emit the generic diagnostic and, optionally, add the hints to it.
9699     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9700         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9701         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9702         << ToTy << (unsigned)isObjectArgument << I + 1
9703         << (unsigned)(Cand->Fix.Kind);
9704 
9705     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9706     return;
9707   }
9708 
9709   // Diagnose base -> derived pointer conversions.
9710   unsigned BaseToDerivedConversion = 0;
9711   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9712     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9713       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9714                                                FromPtrTy->getPointeeType()) &&
9715           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9716           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9717           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9718                           FromPtrTy->getPointeeType()))
9719         BaseToDerivedConversion = 1;
9720     }
9721   } else if (const ObjCObjectPointerType *FromPtrTy
9722                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9723     if (const ObjCObjectPointerType *ToPtrTy
9724                                         = ToTy->getAs<ObjCObjectPointerType>())
9725       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9726         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9727           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9728                                                 FromPtrTy->getPointeeType()) &&
9729               FromIface->isSuperClassOf(ToIface))
9730             BaseToDerivedConversion = 2;
9731   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9732     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9733         !FromTy->isIncompleteType() &&
9734         !ToRefTy->getPointeeType()->isIncompleteType() &&
9735         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9736       BaseToDerivedConversion = 3;
9737     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9738                ToTy.getNonReferenceType().getCanonicalType() ==
9739                FromTy.getNonReferenceType().getCanonicalType()) {
9740       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9741           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9742           << (unsigned)isObjectArgument << I + 1
9743           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9744       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9745       return;
9746     }
9747   }
9748 
9749   if (BaseToDerivedConversion) {
9750     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9751         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9752         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9753         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9754     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9755     return;
9756   }
9757 
9758   if (isa<ObjCObjectPointerType>(CFromTy) &&
9759       isa<PointerType>(CToTy)) {
9760       Qualifiers FromQs = CFromTy.getQualifiers();
9761       Qualifiers ToQs = CToTy.getQualifiers();
9762       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9763         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9764             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9765             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9766             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9767         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9768         return;
9769       }
9770   }
9771 
9772   if (TakingCandidateAddress &&
9773       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9774     return;
9775 
9776   // Emit the generic diagnostic and, optionally, add the hints to it.
9777   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9778   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9779         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9780         << ToTy << (unsigned)isObjectArgument << I + 1
9781         << (unsigned)(Cand->Fix.Kind);
9782 
9783   // If we can fix the conversion, suggest the FixIts.
9784   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9785        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9786     FDiag << *HI;
9787   S.Diag(Fn->getLocation(), FDiag);
9788 
9789   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9790 }
9791 
9792 /// Additional arity mismatch diagnosis specific to a function overload
9793 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9794 /// over a candidate in any candidate set.
9795 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9796                                unsigned NumArgs) {
9797   FunctionDecl *Fn = Cand->Function;
9798   unsigned MinParams = Fn->getMinRequiredArguments();
9799 
9800   // With invalid overloaded operators, it's possible that we think we
9801   // have an arity mismatch when in fact it looks like we have the
9802   // right number of arguments, because only overloaded operators have
9803   // the weird behavior of overloading member and non-member functions.
9804   // Just don't report anything.
9805   if (Fn->isInvalidDecl() &&
9806       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9807     return true;
9808 
9809   if (NumArgs < MinParams) {
9810     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9811            (Cand->FailureKind == ovl_fail_bad_deduction &&
9812             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9813   } else {
9814     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9815            (Cand->FailureKind == ovl_fail_bad_deduction &&
9816             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9817   }
9818 
9819   return false;
9820 }
9821 
9822 /// General arity mismatch diagnosis over a candidate in a candidate set.
9823 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9824                                   unsigned NumFormalArgs) {
9825   assert(isa<FunctionDecl>(D) &&
9826       "The templated declaration should at least be a function"
9827       " when diagnosing bad template argument deduction due to too many"
9828       " or too few arguments");
9829 
9830   FunctionDecl *Fn = cast<FunctionDecl>(D);
9831 
9832   // TODO: treat calls to a missing default constructor as a special case
9833   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9834   unsigned MinParams = Fn->getMinRequiredArguments();
9835 
9836   // at least / at most / exactly
9837   unsigned mode, modeCount;
9838   if (NumFormalArgs < MinParams) {
9839     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9840         FnTy->isTemplateVariadic())
9841       mode = 0; // "at least"
9842     else
9843       mode = 2; // "exactly"
9844     modeCount = MinParams;
9845   } else {
9846     if (MinParams != FnTy->getNumParams())
9847       mode = 1; // "at most"
9848     else
9849       mode = 2; // "exactly"
9850     modeCount = FnTy->getNumParams();
9851   }
9852 
9853   std::string Description;
9854   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9855       ClassifyOverloadCandidate(S, Found, Fn, Description);
9856 
9857   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9858     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9859         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9860         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9861   else
9862     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9863         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9864         << Description << mode << modeCount << NumFormalArgs;
9865 
9866   MaybeEmitInheritedConstructorNote(S, Found);
9867 }
9868 
9869 /// Arity mismatch diagnosis specific to a function overload candidate.
9870 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9871                                   unsigned NumFormalArgs) {
9872   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9873     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9874 }
9875 
9876 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9877   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9878     return TD;
9879   llvm_unreachable("Unsupported: Getting the described template declaration"
9880                    " for bad deduction diagnosis");
9881 }
9882 
9883 /// Diagnose a failed template-argument deduction.
9884 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9885                                  DeductionFailureInfo &DeductionFailure,
9886                                  unsigned NumArgs,
9887                                  bool TakingCandidateAddress) {
9888   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9889   NamedDecl *ParamD;
9890   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9891   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9892   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9893   switch (DeductionFailure.Result) {
9894   case Sema::TDK_Success:
9895     llvm_unreachable("TDK_success while diagnosing bad deduction");
9896 
9897   case Sema::TDK_Incomplete: {
9898     assert(ParamD && "no parameter found for incomplete deduction result");
9899     S.Diag(Templated->getLocation(),
9900            diag::note_ovl_candidate_incomplete_deduction)
9901         << ParamD->getDeclName();
9902     MaybeEmitInheritedConstructorNote(S, Found);
9903     return;
9904   }
9905 
9906   case Sema::TDK_Underqualified: {
9907     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9908     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9909 
9910     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9911 
9912     // Param will have been canonicalized, but it should just be a
9913     // qualified version of ParamD, so move the qualifiers to that.
9914     QualifierCollector Qs;
9915     Qs.strip(Param);
9916     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9917     assert(S.Context.hasSameType(Param, NonCanonParam));
9918 
9919     // Arg has also been canonicalized, but there's nothing we can do
9920     // about that.  It also doesn't matter as much, because it won't
9921     // have any template parameters in it (because deduction isn't
9922     // done on dependent types).
9923     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9924 
9925     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9926         << ParamD->getDeclName() << Arg << NonCanonParam;
9927     MaybeEmitInheritedConstructorNote(S, Found);
9928     return;
9929   }
9930 
9931   case Sema::TDK_Inconsistent: {
9932     assert(ParamD && "no parameter found for inconsistent deduction result");
9933     int which = 0;
9934     if (isa<TemplateTypeParmDecl>(ParamD))
9935       which = 0;
9936     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9937       // Deduction might have failed because we deduced arguments of two
9938       // different types for a non-type template parameter.
9939       // FIXME: Use a different TDK value for this.
9940       QualType T1 =
9941           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9942       QualType T2 =
9943           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9944       if (!S.Context.hasSameType(T1, T2)) {
9945         S.Diag(Templated->getLocation(),
9946                diag::note_ovl_candidate_inconsistent_deduction_types)
9947           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9948           << *DeductionFailure.getSecondArg() << T2;
9949         MaybeEmitInheritedConstructorNote(S, Found);
9950         return;
9951       }
9952 
9953       which = 1;
9954     } else {
9955       which = 2;
9956     }
9957 
9958     S.Diag(Templated->getLocation(),
9959            diag::note_ovl_candidate_inconsistent_deduction)
9960         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9961         << *DeductionFailure.getSecondArg();
9962     MaybeEmitInheritedConstructorNote(S, Found);
9963     return;
9964   }
9965 
9966   case Sema::TDK_InvalidExplicitArguments:
9967     assert(ParamD && "no parameter found for invalid explicit arguments");
9968     if (ParamD->getDeclName())
9969       S.Diag(Templated->getLocation(),
9970              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9971           << ParamD->getDeclName();
9972     else {
9973       int index = 0;
9974       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9975         index = TTP->getIndex();
9976       else if (NonTypeTemplateParmDecl *NTTP
9977                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9978         index = NTTP->getIndex();
9979       else
9980         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9981       S.Diag(Templated->getLocation(),
9982              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9983           << (index + 1);
9984     }
9985     MaybeEmitInheritedConstructorNote(S, Found);
9986     return;
9987 
9988   case Sema::TDK_TooManyArguments:
9989   case Sema::TDK_TooFewArguments:
9990     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9991     return;
9992 
9993   case Sema::TDK_InstantiationDepth:
9994     S.Diag(Templated->getLocation(),
9995            diag::note_ovl_candidate_instantiation_depth);
9996     MaybeEmitInheritedConstructorNote(S, Found);
9997     return;
9998 
9999   case Sema::TDK_SubstitutionFailure: {
10000     // Format the template argument list into the argument string.
10001     SmallString<128> TemplateArgString;
10002     if (TemplateArgumentList *Args =
10003             DeductionFailure.getTemplateArgumentList()) {
10004       TemplateArgString = " ";
10005       TemplateArgString += S.getTemplateArgumentBindingsText(
10006           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10007     }
10008 
10009     // If this candidate was disabled by enable_if, say so.
10010     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10011     if (PDiag && PDiag->second.getDiagID() ==
10012           diag::err_typename_nested_not_found_enable_if) {
10013       // FIXME: Use the source range of the condition, and the fully-qualified
10014       //        name of the enable_if template. These are both present in PDiag.
10015       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10016         << "'enable_if'" << TemplateArgString;
10017       return;
10018     }
10019 
10020     // We found a specific requirement that disabled the enable_if.
10021     if (PDiag && PDiag->second.getDiagID() ==
10022         diag::err_typename_nested_not_found_requirement) {
10023       S.Diag(Templated->getLocation(),
10024              diag::note_ovl_candidate_disabled_by_requirement)
10025         << PDiag->second.getStringArg(0) << TemplateArgString;
10026       return;
10027     }
10028 
10029     // Format the SFINAE diagnostic into the argument string.
10030     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10031     //        formatted message in another diagnostic.
10032     SmallString<128> SFINAEArgString;
10033     SourceRange R;
10034     if (PDiag) {
10035       SFINAEArgString = ": ";
10036       R = SourceRange(PDiag->first, PDiag->first);
10037       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10038     }
10039 
10040     S.Diag(Templated->getLocation(),
10041            diag::note_ovl_candidate_substitution_failure)
10042         << TemplateArgString << SFINAEArgString << R;
10043     MaybeEmitInheritedConstructorNote(S, Found);
10044     return;
10045   }
10046 
10047   case Sema::TDK_DeducedMismatch:
10048   case Sema::TDK_DeducedMismatchNested: {
10049     // Format the template argument list into the argument string.
10050     SmallString<128> TemplateArgString;
10051     if (TemplateArgumentList *Args =
10052             DeductionFailure.getTemplateArgumentList()) {
10053       TemplateArgString = " ";
10054       TemplateArgString += S.getTemplateArgumentBindingsText(
10055           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10056     }
10057 
10058     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10059         << (*DeductionFailure.getCallArgIndex() + 1)
10060         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10061         << TemplateArgString
10062         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10063     break;
10064   }
10065 
10066   case Sema::TDK_NonDeducedMismatch: {
10067     // FIXME: Provide a source location to indicate what we couldn't match.
10068     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10069     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10070     if (FirstTA.getKind() == TemplateArgument::Template &&
10071         SecondTA.getKind() == TemplateArgument::Template) {
10072       TemplateName FirstTN = FirstTA.getAsTemplate();
10073       TemplateName SecondTN = SecondTA.getAsTemplate();
10074       if (FirstTN.getKind() == TemplateName::Template &&
10075           SecondTN.getKind() == TemplateName::Template) {
10076         if (FirstTN.getAsTemplateDecl()->getName() ==
10077             SecondTN.getAsTemplateDecl()->getName()) {
10078           // FIXME: This fixes a bad diagnostic where both templates are named
10079           // the same.  This particular case is a bit difficult since:
10080           // 1) It is passed as a string to the diagnostic printer.
10081           // 2) The diagnostic printer only attempts to find a better
10082           //    name for types, not decls.
10083           // Ideally, this should folded into the diagnostic printer.
10084           S.Diag(Templated->getLocation(),
10085                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10086               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10087           return;
10088         }
10089       }
10090     }
10091 
10092     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10093         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10094       return;
10095 
10096     // FIXME: For generic lambda parameters, check if the function is a lambda
10097     // call operator, and if so, emit a prettier and more informative
10098     // diagnostic that mentions 'auto' and lambda in addition to
10099     // (or instead of?) the canonical template type parameters.
10100     S.Diag(Templated->getLocation(),
10101            diag::note_ovl_candidate_non_deduced_mismatch)
10102         << FirstTA << SecondTA;
10103     return;
10104   }
10105   // TODO: diagnose these individually, then kill off
10106   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10107   case Sema::TDK_MiscellaneousDeductionFailure:
10108     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10109     MaybeEmitInheritedConstructorNote(S, Found);
10110     return;
10111   case Sema::TDK_CUDATargetMismatch:
10112     S.Diag(Templated->getLocation(),
10113            diag::note_cuda_ovl_candidate_target_mismatch);
10114     return;
10115   }
10116 }
10117 
10118 /// Diagnose a failed template-argument deduction, for function calls.
10119 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10120                                  unsigned NumArgs,
10121                                  bool TakingCandidateAddress) {
10122   unsigned TDK = Cand->DeductionFailure.Result;
10123   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10124     if (CheckArityMismatch(S, Cand, NumArgs))
10125       return;
10126   }
10127   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10128                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10129 }
10130 
10131 /// CUDA: diagnose an invalid call across targets.
10132 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10133   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10134   FunctionDecl *Callee = Cand->Function;
10135 
10136   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10137                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10138 
10139   std::string FnDesc;
10140   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10141       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10142 
10143   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10144       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10145       << FnDesc /* Ignored */
10146       << CalleeTarget << CallerTarget;
10147 
10148   // This could be an implicit constructor for which we could not infer the
10149   // target due to a collsion. Diagnose that case.
10150   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10151   if (Meth != nullptr && Meth->isImplicit()) {
10152     CXXRecordDecl *ParentClass = Meth->getParent();
10153     Sema::CXXSpecialMember CSM;
10154 
10155     switch (FnKindPair.first) {
10156     default:
10157       return;
10158     case oc_implicit_default_constructor:
10159       CSM = Sema::CXXDefaultConstructor;
10160       break;
10161     case oc_implicit_copy_constructor:
10162       CSM = Sema::CXXCopyConstructor;
10163       break;
10164     case oc_implicit_move_constructor:
10165       CSM = Sema::CXXMoveConstructor;
10166       break;
10167     case oc_implicit_copy_assignment:
10168       CSM = Sema::CXXCopyAssignment;
10169       break;
10170     case oc_implicit_move_assignment:
10171       CSM = Sema::CXXMoveAssignment;
10172       break;
10173     };
10174 
10175     bool ConstRHS = false;
10176     if (Meth->getNumParams()) {
10177       if (const ReferenceType *RT =
10178               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10179         ConstRHS = RT->getPointeeType().isConstQualified();
10180       }
10181     }
10182 
10183     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10184                                               /* ConstRHS */ ConstRHS,
10185                                               /* Diagnose */ true);
10186   }
10187 }
10188 
10189 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10190   FunctionDecl *Callee = Cand->Function;
10191   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10192 
10193   S.Diag(Callee->getLocation(),
10194          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10195       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10196 }
10197 
10198 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10199   FunctionDecl *Callee = Cand->Function;
10200 
10201   S.Diag(Callee->getLocation(),
10202          diag::note_ovl_candidate_disabled_by_extension);
10203 }
10204 
10205 /// Generates a 'note' diagnostic for an overload candidate.  We've
10206 /// already generated a primary error at the call site.
10207 ///
10208 /// It really does need to be a single diagnostic with its caret
10209 /// pointed at the candidate declaration.  Yes, this creates some
10210 /// major challenges of technical writing.  Yes, this makes pointing
10211 /// out problems with specific arguments quite awkward.  It's still
10212 /// better than generating twenty screens of text for every failed
10213 /// overload.
10214 ///
10215 /// It would be great to be able to express per-candidate problems
10216 /// more richly for those diagnostic clients that cared, but we'd
10217 /// still have to be just as careful with the default diagnostics.
10218 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10219                                   unsigned NumArgs,
10220                                   bool TakingCandidateAddress) {
10221   FunctionDecl *Fn = Cand->Function;
10222 
10223   // Note deleted candidates, but only if they're viable.
10224   if (Cand->Viable) {
10225     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10226       std::string FnDesc;
10227       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10228           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10229 
10230       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10231           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10232           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10233       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10234       return;
10235     }
10236 
10237     // We don't really have anything else to say about viable candidates.
10238     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10239     return;
10240   }
10241 
10242   switch (Cand->FailureKind) {
10243   case ovl_fail_too_many_arguments:
10244   case ovl_fail_too_few_arguments:
10245     return DiagnoseArityMismatch(S, Cand, NumArgs);
10246 
10247   case ovl_fail_bad_deduction:
10248     return DiagnoseBadDeduction(S, Cand, NumArgs,
10249                                 TakingCandidateAddress);
10250 
10251   case ovl_fail_illegal_constructor: {
10252     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10253       << (Fn->getPrimaryTemplate() ? 1 : 0);
10254     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10255     return;
10256   }
10257 
10258   case ovl_fail_trivial_conversion:
10259   case ovl_fail_bad_final_conversion:
10260   case ovl_fail_final_conversion_not_exact:
10261     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10262 
10263   case ovl_fail_bad_conversion: {
10264     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10265     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10266       if (Cand->Conversions[I].isBad())
10267         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10268 
10269     // FIXME: this currently happens when we're called from SemaInit
10270     // when user-conversion overload fails.  Figure out how to handle
10271     // those conditions and diagnose them well.
10272     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10273   }
10274 
10275   case ovl_fail_bad_target:
10276     return DiagnoseBadTarget(S, Cand);
10277 
10278   case ovl_fail_enable_if:
10279     return DiagnoseFailedEnableIfAttr(S, Cand);
10280 
10281   case ovl_fail_ext_disabled:
10282     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10283 
10284   case ovl_fail_inhctor_slice:
10285     // It's generally not interesting to note copy/move constructors here.
10286     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10287       return;
10288     S.Diag(Fn->getLocation(),
10289            diag::note_ovl_candidate_inherited_constructor_slice)
10290       << (Fn->getPrimaryTemplate() ? 1 : 0)
10291       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10292     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10293     return;
10294 
10295   case ovl_fail_addr_not_available: {
10296     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10297     (void)Available;
10298     assert(!Available);
10299     break;
10300   }
10301   case ovl_non_default_multiversion_function:
10302     // Do nothing, these should simply be ignored.
10303     break;
10304   }
10305 }
10306 
10307 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10308   // Desugar the type of the surrogate down to a function type,
10309   // retaining as many typedefs as possible while still showing
10310   // the function type (and, therefore, its parameter types).
10311   QualType FnType = Cand->Surrogate->getConversionType();
10312   bool isLValueReference = false;
10313   bool isRValueReference = false;
10314   bool isPointer = false;
10315   if (const LValueReferenceType *FnTypeRef =
10316         FnType->getAs<LValueReferenceType>()) {
10317     FnType = FnTypeRef->getPointeeType();
10318     isLValueReference = true;
10319   } else if (const RValueReferenceType *FnTypeRef =
10320                FnType->getAs<RValueReferenceType>()) {
10321     FnType = FnTypeRef->getPointeeType();
10322     isRValueReference = true;
10323   }
10324   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10325     FnType = FnTypePtr->getPointeeType();
10326     isPointer = true;
10327   }
10328   // Desugar down to a function type.
10329   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10330   // Reconstruct the pointer/reference as appropriate.
10331   if (isPointer) FnType = S.Context.getPointerType(FnType);
10332   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10333   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10334 
10335   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10336     << FnType;
10337 }
10338 
10339 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10340                                          SourceLocation OpLoc,
10341                                          OverloadCandidate *Cand) {
10342   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10343   std::string TypeStr("operator");
10344   TypeStr += Opc;
10345   TypeStr += "(";
10346   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10347   if (Cand->Conversions.size() == 1) {
10348     TypeStr += ")";
10349     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10350   } else {
10351     TypeStr += ", ";
10352     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10353     TypeStr += ")";
10354     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10355   }
10356 }
10357 
10358 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10359                                          OverloadCandidate *Cand) {
10360   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10361     if (ICS.isBad()) break; // all meaningless after first invalid
10362     if (!ICS.isAmbiguous()) continue;
10363 
10364     ICS.DiagnoseAmbiguousConversion(
10365         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10366   }
10367 }
10368 
10369 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10370   if (Cand->Function)
10371     return Cand->Function->getLocation();
10372   if (Cand->IsSurrogate)
10373     return Cand->Surrogate->getLocation();
10374   return SourceLocation();
10375 }
10376 
10377 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10378   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10379   case Sema::TDK_Success:
10380   case Sema::TDK_NonDependentConversionFailure:
10381     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10382 
10383   case Sema::TDK_Invalid:
10384   case Sema::TDK_Incomplete:
10385     return 1;
10386 
10387   case Sema::TDK_Underqualified:
10388   case Sema::TDK_Inconsistent:
10389     return 2;
10390 
10391   case Sema::TDK_SubstitutionFailure:
10392   case Sema::TDK_DeducedMismatch:
10393   case Sema::TDK_DeducedMismatchNested:
10394   case Sema::TDK_NonDeducedMismatch:
10395   case Sema::TDK_MiscellaneousDeductionFailure:
10396   case Sema::TDK_CUDATargetMismatch:
10397     return 3;
10398 
10399   case Sema::TDK_InstantiationDepth:
10400     return 4;
10401 
10402   case Sema::TDK_InvalidExplicitArguments:
10403     return 5;
10404 
10405   case Sema::TDK_TooManyArguments:
10406   case Sema::TDK_TooFewArguments:
10407     return 6;
10408   }
10409   llvm_unreachable("Unhandled deduction result");
10410 }
10411 
10412 namespace {
10413 struct CompareOverloadCandidatesForDisplay {
10414   Sema &S;
10415   SourceLocation Loc;
10416   size_t NumArgs;
10417   OverloadCandidateSet::CandidateSetKind CSK;
10418 
10419   CompareOverloadCandidatesForDisplay(
10420       Sema &S, SourceLocation Loc, size_t NArgs,
10421       OverloadCandidateSet::CandidateSetKind CSK)
10422       : S(S), NumArgs(NArgs), CSK(CSK) {}
10423 
10424   bool operator()(const OverloadCandidate *L,
10425                   const OverloadCandidate *R) {
10426     // Fast-path this check.
10427     if (L == R) return false;
10428 
10429     // Order first by viability.
10430     if (L->Viable) {
10431       if (!R->Viable) return true;
10432 
10433       // TODO: introduce a tri-valued comparison for overload
10434       // candidates.  Would be more worthwhile if we had a sort
10435       // that could exploit it.
10436       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10437         return true;
10438       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10439         return false;
10440     } else if (R->Viable)
10441       return false;
10442 
10443     assert(L->Viable == R->Viable);
10444 
10445     // Criteria by which we can sort non-viable candidates:
10446     if (!L->Viable) {
10447       // 1. Arity mismatches come after other candidates.
10448       if (L->FailureKind == ovl_fail_too_many_arguments ||
10449           L->FailureKind == ovl_fail_too_few_arguments) {
10450         if (R->FailureKind == ovl_fail_too_many_arguments ||
10451             R->FailureKind == ovl_fail_too_few_arguments) {
10452           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10453           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10454           if (LDist == RDist) {
10455             if (L->FailureKind == R->FailureKind)
10456               // Sort non-surrogates before surrogates.
10457               return !L->IsSurrogate && R->IsSurrogate;
10458             // Sort candidates requiring fewer parameters than there were
10459             // arguments given after candidates requiring more parameters
10460             // than there were arguments given.
10461             return L->FailureKind == ovl_fail_too_many_arguments;
10462           }
10463           return LDist < RDist;
10464         }
10465         return false;
10466       }
10467       if (R->FailureKind == ovl_fail_too_many_arguments ||
10468           R->FailureKind == ovl_fail_too_few_arguments)
10469         return true;
10470 
10471       // 2. Bad conversions come first and are ordered by the number
10472       // of bad conversions and quality of good conversions.
10473       if (L->FailureKind == ovl_fail_bad_conversion) {
10474         if (R->FailureKind != ovl_fail_bad_conversion)
10475           return true;
10476 
10477         // The conversion that can be fixed with a smaller number of changes,
10478         // comes first.
10479         unsigned numLFixes = L->Fix.NumConversionsFixed;
10480         unsigned numRFixes = R->Fix.NumConversionsFixed;
10481         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10482         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10483         if (numLFixes != numRFixes) {
10484           return numLFixes < numRFixes;
10485         }
10486 
10487         // If there's any ordering between the defined conversions...
10488         // FIXME: this might not be transitive.
10489         assert(L->Conversions.size() == R->Conversions.size());
10490 
10491         int leftBetter = 0;
10492         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10493         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10494           switch (CompareImplicitConversionSequences(S, Loc,
10495                                                      L->Conversions[I],
10496                                                      R->Conversions[I])) {
10497           case ImplicitConversionSequence::Better:
10498             leftBetter++;
10499             break;
10500 
10501           case ImplicitConversionSequence::Worse:
10502             leftBetter--;
10503             break;
10504 
10505           case ImplicitConversionSequence::Indistinguishable:
10506             break;
10507           }
10508         }
10509         if (leftBetter > 0) return true;
10510         if (leftBetter < 0) return false;
10511 
10512       } else if (R->FailureKind == ovl_fail_bad_conversion)
10513         return false;
10514 
10515       if (L->FailureKind == ovl_fail_bad_deduction) {
10516         if (R->FailureKind != ovl_fail_bad_deduction)
10517           return true;
10518 
10519         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10520           return RankDeductionFailure(L->DeductionFailure)
10521                < RankDeductionFailure(R->DeductionFailure);
10522       } else if (R->FailureKind == ovl_fail_bad_deduction)
10523         return false;
10524 
10525       // TODO: others?
10526     }
10527 
10528     // Sort everything else by location.
10529     SourceLocation LLoc = GetLocationForCandidate(L);
10530     SourceLocation RLoc = GetLocationForCandidate(R);
10531 
10532     // Put candidates without locations (e.g. builtins) at the end.
10533     if (LLoc.isInvalid()) return false;
10534     if (RLoc.isInvalid()) return true;
10535 
10536     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10537   }
10538 };
10539 }
10540 
10541 /// CompleteNonViableCandidate - Normally, overload resolution only
10542 /// computes up to the first bad conversion. Produces the FixIt set if
10543 /// possible.
10544 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10545                                        ArrayRef<Expr *> Args) {
10546   assert(!Cand->Viable);
10547 
10548   // Don't do anything on failures other than bad conversion.
10549   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10550 
10551   // We only want the FixIts if all the arguments can be corrected.
10552   bool Unfixable = false;
10553   // Use a implicit copy initialization to check conversion fixes.
10554   Cand->Fix.setConversionChecker(TryCopyInitialization);
10555 
10556   // Attempt to fix the bad conversion.
10557   unsigned ConvCount = Cand->Conversions.size();
10558   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10559        ++ConvIdx) {
10560     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10561     if (Cand->Conversions[ConvIdx].isInitialized() &&
10562         Cand->Conversions[ConvIdx].isBad()) {
10563       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10564       break;
10565     }
10566   }
10567 
10568   // FIXME: this should probably be preserved from the overload
10569   // operation somehow.
10570   bool SuppressUserConversions = false;
10571 
10572   unsigned ConvIdx = 0;
10573   ArrayRef<QualType> ParamTypes;
10574 
10575   if (Cand->IsSurrogate) {
10576     QualType ConvType
10577       = Cand->Surrogate->getConversionType().getNonReferenceType();
10578     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10579       ConvType = ConvPtrType->getPointeeType();
10580     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10581     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10582     ConvIdx = 1;
10583   } else if (Cand->Function) {
10584     ParamTypes =
10585         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10586     if (isa<CXXMethodDecl>(Cand->Function) &&
10587         !isa<CXXConstructorDecl>(Cand->Function)) {
10588       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10589       ConvIdx = 1;
10590     }
10591   } else {
10592     // Builtin operator.
10593     assert(ConvCount <= 3);
10594     ParamTypes = Cand->BuiltinParamTypes;
10595   }
10596 
10597   // Fill in the rest of the conversions.
10598   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10599     if (Cand->Conversions[ConvIdx].isInitialized()) {
10600       // We've already checked this conversion.
10601     } else if (ArgIdx < ParamTypes.size()) {
10602       if (ParamTypes[ArgIdx]->isDependentType())
10603         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10604             Args[ArgIdx]->getType());
10605       else {
10606         Cand->Conversions[ConvIdx] =
10607             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10608                                   SuppressUserConversions,
10609                                   /*InOverloadResolution=*/true,
10610                                   /*AllowObjCWritebackConversion=*/
10611                                   S.getLangOpts().ObjCAutoRefCount);
10612         // Store the FixIt in the candidate if it exists.
10613         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10614           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10615       }
10616     } else
10617       Cand->Conversions[ConvIdx].setEllipsis();
10618   }
10619 }
10620 
10621 /// When overload resolution fails, prints diagnostic messages containing the
10622 /// candidates in the candidate set.
10623 void OverloadCandidateSet::NoteCandidates(
10624     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10625     StringRef Opc, SourceLocation OpLoc,
10626     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10627   // Sort the candidates by viability and position.  Sorting directly would
10628   // be prohibitive, so we make a set of pointers and sort those.
10629   SmallVector<OverloadCandidate*, 32> Cands;
10630   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10631   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10632     if (!Filter(*Cand))
10633       continue;
10634     if (Cand->Viable)
10635       Cands.push_back(Cand);
10636     else if (OCD == OCD_AllCandidates) {
10637       CompleteNonViableCandidate(S, Cand, Args);
10638       if (Cand->Function || Cand->IsSurrogate)
10639         Cands.push_back(Cand);
10640       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10641       // want to list every possible builtin candidate.
10642     }
10643   }
10644 
10645   std::stable_sort(Cands.begin(), Cands.end(),
10646             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10647 
10648   bool ReportedAmbiguousConversions = false;
10649 
10650   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10651   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10652   unsigned CandsShown = 0;
10653   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10654     OverloadCandidate *Cand = *I;
10655 
10656     // Set an arbitrary limit on the number of candidate functions we'll spam
10657     // the user with.  FIXME: This limit should depend on details of the
10658     // candidate list.
10659     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10660       break;
10661     }
10662     ++CandsShown;
10663 
10664     if (Cand->Function)
10665       NoteFunctionCandidate(S, Cand, Args.size(),
10666                             /*TakingCandidateAddress=*/false);
10667     else if (Cand->IsSurrogate)
10668       NoteSurrogateCandidate(S, Cand);
10669     else {
10670       assert(Cand->Viable &&
10671              "Non-viable built-in candidates are not added to Cands.");
10672       // Generally we only see ambiguities including viable builtin
10673       // operators if overload resolution got screwed up by an
10674       // ambiguous user-defined conversion.
10675       //
10676       // FIXME: It's quite possible for different conversions to see
10677       // different ambiguities, though.
10678       if (!ReportedAmbiguousConversions) {
10679         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10680         ReportedAmbiguousConversions = true;
10681       }
10682 
10683       // If this is a viable builtin, print it.
10684       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10685     }
10686   }
10687 
10688   if (I != E)
10689     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10690 }
10691 
10692 static SourceLocation
10693 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10694   return Cand->Specialization ? Cand->Specialization->getLocation()
10695                               : SourceLocation();
10696 }
10697 
10698 namespace {
10699 struct CompareTemplateSpecCandidatesForDisplay {
10700   Sema &S;
10701   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10702 
10703   bool operator()(const TemplateSpecCandidate *L,
10704                   const TemplateSpecCandidate *R) {
10705     // Fast-path this check.
10706     if (L == R)
10707       return false;
10708 
10709     // Assuming that both candidates are not matches...
10710 
10711     // Sort by the ranking of deduction failures.
10712     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10713       return RankDeductionFailure(L->DeductionFailure) <
10714              RankDeductionFailure(R->DeductionFailure);
10715 
10716     // Sort everything else by location.
10717     SourceLocation LLoc = GetLocationForCandidate(L);
10718     SourceLocation RLoc = GetLocationForCandidate(R);
10719 
10720     // Put candidates without locations (e.g. builtins) at the end.
10721     if (LLoc.isInvalid())
10722       return false;
10723     if (RLoc.isInvalid())
10724       return true;
10725 
10726     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10727   }
10728 };
10729 }
10730 
10731 /// Diagnose a template argument deduction failure.
10732 /// We are treating these failures as overload failures due to bad
10733 /// deductions.
10734 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10735                                                  bool ForTakingAddress) {
10736   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10737                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10738 }
10739 
10740 void TemplateSpecCandidateSet::destroyCandidates() {
10741   for (iterator i = begin(), e = end(); i != e; ++i) {
10742     i->DeductionFailure.Destroy();
10743   }
10744 }
10745 
10746 void TemplateSpecCandidateSet::clear() {
10747   destroyCandidates();
10748   Candidates.clear();
10749 }
10750 
10751 /// NoteCandidates - When no template specialization match is found, prints
10752 /// diagnostic messages containing the non-matching specializations that form
10753 /// the candidate set.
10754 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10755 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10756 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10757   // Sort the candidates by position (assuming no candidate is a match).
10758   // Sorting directly would be prohibitive, so we make a set of pointers
10759   // and sort those.
10760   SmallVector<TemplateSpecCandidate *, 32> Cands;
10761   Cands.reserve(size());
10762   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10763     if (Cand->Specialization)
10764       Cands.push_back(Cand);
10765     // Otherwise, this is a non-matching builtin candidate.  We do not,
10766     // in general, want to list every possible builtin candidate.
10767   }
10768 
10769   llvm::sort(Cands.begin(), Cands.end(),
10770              CompareTemplateSpecCandidatesForDisplay(S));
10771 
10772   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10773   // for generalization purposes (?).
10774   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10775 
10776   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10777   unsigned CandsShown = 0;
10778   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10779     TemplateSpecCandidate *Cand = *I;
10780 
10781     // Set an arbitrary limit on the number of candidates we'll spam
10782     // the user with.  FIXME: This limit should depend on details of the
10783     // candidate list.
10784     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10785       break;
10786     ++CandsShown;
10787 
10788     assert(Cand->Specialization &&
10789            "Non-matching built-in candidates are not added to Cands.");
10790     Cand->NoteDeductionFailure(S, ForTakingAddress);
10791   }
10792 
10793   if (I != E)
10794     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10795 }
10796 
10797 // [PossiblyAFunctionType]  -->   [Return]
10798 // NonFunctionType --> NonFunctionType
10799 // R (A) --> R(A)
10800 // R (*)(A) --> R (A)
10801 // R (&)(A) --> R (A)
10802 // R (S::*)(A) --> R (A)
10803 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10804   QualType Ret = PossiblyAFunctionType;
10805   if (const PointerType *ToTypePtr =
10806     PossiblyAFunctionType->getAs<PointerType>())
10807     Ret = ToTypePtr->getPointeeType();
10808   else if (const ReferenceType *ToTypeRef =
10809     PossiblyAFunctionType->getAs<ReferenceType>())
10810     Ret = ToTypeRef->getPointeeType();
10811   else if (const MemberPointerType *MemTypePtr =
10812     PossiblyAFunctionType->getAs<MemberPointerType>())
10813     Ret = MemTypePtr->getPointeeType();
10814   Ret =
10815     Context.getCanonicalType(Ret).getUnqualifiedType();
10816   return Ret;
10817 }
10818 
10819 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10820                                  bool Complain = true) {
10821   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10822       S.DeduceReturnType(FD, Loc, Complain))
10823     return true;
10824 
10825   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10826   if (S.getLangOpts().CPlusPlus17 &&
10827       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10828       !S.ResolveExceptionSpec(Loc, FPT))
10829     return true;
10830 
10831   return false;
10832 }
10833 
10834 namespace {
10835 // A helper class to help with address of function resolution
10836 // - allows us to avoid passing around all those ugly parameters
10837 class AddressOfFunctionResolver {
10838   Sema& S;
10839   Expr* SourceExpr;
10840   const QualType& TargetType;
10841   QualType TargetFunctionType; // Extracted function type from target type
10842 
10843   bool Complain;
10844   //DeclAccessPair& ResultFunctionAccessPair;
10845   ASTContext& Context;
10846 
10847   bool TargetTypeIsNonStaticMemberFunction;
10848   bool FoundNonTemplateFunction;
10849   bool StaticMemberFunctionFromBoundPointer;
10850   bool HasComplained;
10851 
10852   OverloadExpr::FindResult OvlExprInfo;
10853   OverloadExpr *OvlExpr;
10854   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10855   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10856   TemplateSpecCandidateSet FailedCandidates;
10857 
10858 public:
10859   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10860                             const QualType &TargetType, bool Complain)
10861       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10862         Complain(Complain), Context(S.getASTContext()),
10863         TargetTypeIsNonStaticMemberFunction(
10864             !!TargetType->getAs<MemberPointerType>()),
10865         FoundNonTemplateFunction(false),
10866         StaticMemberFunctionFromBoundPointer(false),
10867         HasComplained(false),
10868         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10869         OvlExpr(OvlExprInfo.Expression),
10870         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10871     ExtractUnqualifiedFunctionTypeFromTargetType();
10872 
10873     if (TargetFunctionType->isFunctionType()) {
10874       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10875         if (!UME->isImplicitAccess() &&
10876             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10877           StaticMemberFunctionFromBoundPointer = true;
10878     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10879       DeclAccessPair dap;
10880       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10881               OvlExpr, false, &dap)) {
10882         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10883           if (!Method->isStatic()) {
10884             // If the target type is a non-function type and the function found
10885             // is a non-static member function, pretend as if that was the
10886             // target, it's the only possible type to end up with.
10887             TargetTypeIsNonStaticMemberFunction = true;
10888 
10889             // And skip adding the function if its not in the proper form.
10890             // We'll diagnose this due to an empty set of functions.
10891             if (!OvlExprInfo.HasFormOfMemberPointer)
10892               return;
10893           }
10894 
10895         Matches.push_back(std::make_pair(dap, Fn));
10896       }
10897       return;
10898     }
10899 
10900     if (OvlExpr->hasExplicitTemplateArgs())
10901       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10902 
10903     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10904       // C++ [over.over]p4:
10905       //   If more than one function is selected, [...]
10906       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10907         if (FoundNonTemplateFunction)
10908           EliminateAllTemplateMatches();
10909         else
10910           EliminateAllExceptMostSpecializedTemplate();
10911       }
10912     }
10913 
10914     if (S.getLangOpts().CUDA && Matches.size() > 1)
10915       EliminateSuboptimalCudaMatches();
10916   }
10917 
10918   bool hasComplained() const { return HasComplained; }
10919 
10920 private:
10921   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10922     QualType Discard;
10923     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10924            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10925   }
10926 
10927   /// \return true if A is considered a better overload candidate for the
10928   /// desired type than B.
10929   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10930     // If A doesn't have exactly the correct type, we don't want to classify it
10931     // as "better" than anything else. This way, the user is required to
10932     // disambiguate for us if there are multiple candidates and no exact match.
10933     return candidateHasExactlyCorrectType(A) &&
10934            (!candidateHasExactlyCorrectType(B) ||
10935             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10936   }
10937 
10938   /// \return true if we were able to eliminate all but one overload candidate,
10939   /// false otherwise.
10940   bool eliminiateSuboptimalOverloadCandidates() {
10941     // Same algorithm as overload resolution -- one pass to pick the "best",
10942     // another pass to be sure that nothing is better than the best.
10943     auto Best = Matches.begin();
10944     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10945       if (isBetterCandidate(I->second, Best->second))
10946         Best = I;
10947 
10948     const FunctionDecl *BestFn = Best->second;
10949     auto IsBestOrInferiorToBest = [this, BestFn](
10950         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10951       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10952     };
10953 
10954     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10955     // option, so we can potentially give the user a better error
10956     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10957       return false;
10958     Matches[0] = *Best;
10959     Matches.resize(1);
10960     return true;
10961   }
10962 
10963   bool isTargetTypeAFunction() const {
10964     return TargetFunctionType->isFunctionType();
10965   }
10966 
10967   // [ToType]     [Return]
10968 
10969   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10970   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10971   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10972   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10973     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10974   }
10975 
10976   // return true if any matching specializations were found
10977   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10978                                    const DeclAccessPair& CurAccessFunPair) {
10979     if (CXXMethodDecl *Method
10980               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10981       // Skip non-static function templates when converting to pointer, and
10982       // static when converting to member pointer.
10983       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10984         return false;
10985     }
10986     else if (TargetTypeIsNonStaticMemberFunction)
10987       return false;
10988 
10989     // C++ [over.over]p2:
10990     //   If the name is a function template, template argument deduction is
10991     //   done (14.8.2.2), and if the argument deduction succeeds, the
10992     //   resulting template argument list is used to generate a single
10993     //   function template specialization, which is added to the set of
10994     //   overloaded functions considered.
10995     FunctionDecl *Specialization = nullptr;
10996     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10997     if (Sema::TemplateDeductionResult Result
10998           = S.DeduceTemplateArguments(FunctionTemplate,
10999                                       &OvlExplicitTemplateArgs,
11000                                       TargetFunctionType, Specialization,
11001                                       Info, /*IsAddressOfFunction*/true)) {
11002       // Make a note of the failed deduction for diagnostics.
11003       FailedCandidates.addCandidate()
11004           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11005                MakeDeductionFailureInfo(Context, Result, Info));
11006       return false;
11007     }
11008 
11009     // Template argument deduction ensures that we have an exact match or
11010     // compatible pointer-to-function arguments that would be adjusted by ICS.
11011     // This function template specicalization works.
11012     assert(S.isSameOrCompatibleFunctionType(
11013               Context.getCanonicalType(Specialization->getType()),
11014               Context.getCanonicalType(TargetFunctionType)));
11015 
11016     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11017       return false;
11018 
11019     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11020     return true;
11021   }
11022 
11023   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11024                                       const DeclAccessPair& CurAccessFunPair) {
11025     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11026       // Skip non-static functions when converting to pointer, and static
11027       // when converting to member pointer.
11028       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11029         return false;
11030     }
11031     else if (TargetTypeIsNonStaticMemberFunction)
11032       return false;
11033 
11034     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11035       if (S.getLangOpts().CUDA)
11036         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11037           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11038             return false;
11039       if (FunDecl->isMultiVersion()) {
11040         const auto *TA = FunDecl->getAttr<TargetAttr>();
11041         assert(TA && "Multiversioned functions require a target attribute");
11042         if (!TA->isDefaultVersion())
11043           return false;
11044       }
11045 
11046       // If any candidate has a placeholder return type, trigger its deduction
11047       // now.
11048       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11049                                Complain)) {
11050         HasComplained |= Complain;
11051         return false;
11052       }
11053 
11054       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11055         return false;
11056 
11057       // If we're in C, we need to support types that aren't exactly identical.
11058       if (!S.getLangOpts().CPlusPlus ||
11059           candidateHasExactlyCorrectType(FunDecl)) {
11060         Matches.push_back(std::make_pair(
11061             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11062         FoundNonTemplateFunction = true;
11063         return true;
11064       }
11065     }
11066 
11067     return false;
11068   }
11069 
11070   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11071     bool Ret = false;
11072 
11073     // If the overload expression doesn't have the form of a pointer to
11074     // member, don't try to convert it to a pointer-to-member type.
11075     if (IsInvalidFormOfPointerToMemberFunction())
11076       return false;
11077 
11078     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11079                                E = OvlExpr->decls_end();
11080          I != E; ++I) {
11081       // Look through any using declarations to find the underlying function.
11082       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11083 
11084       // C++ [over.over]p3:
11085       //   Non-member functions and static member functions match
11086       //   targets of type "pointer-to-function" or "reference-to-function."
11087       //   Nonstatic member functions match targets of
11088       //   type "pointer-to-member-function."
11089       // Note that according to DR 247, the containing class does not matter.
11090       if (FunctionTemplateDecl *FunctionTemplate
11091                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11092         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11093           Ret = true;
11094       }
11095       // If we have explicit template arguments supplied, skip non-templates.
11096       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11097                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11098         Ret = true;
11099     }
11100     assert(Ret || Matches.empty());
11101     return Ret;
11102   }
11103 
11104   void EliminateAllExceptMostSpecializedTemplate() {
11105     //   [...] and any given function template specialization F1 is
11106     //   eliminated if the set contains a second function template
11107     //   specialization whose function template is more specialized
11108     //   than the function template of F1 according to the partial
11109     //   ordering rules of 14.5.5.2.
11110 
11111     // The algorithm specified above is quadratic. We instead use a
11112     // two-pass algorithm (similar to the one used to identify the
11113     // best viable function in an overload set) that identifies the
11114     // best function template (if it exists).
11115 
11116     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11117     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11118       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11119 
11120     // TODO: It looks like FailedCandidates does not serve much purpose
11121     // here, since the no_viable diagnostic has index 0.
11122     UnresolvedSetIterator Result = S.getMostSpecialized(
11123         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11124         SourceExpr->getLocStart(), S.PDiag(),
11125         S.PDiag(diag::err_addr_ovl_ambiguous)
11126             << Matches[0].second->getDeclName(),
11127         S.PDiag(diag::note_ovl_candidate)
11128             << (unsigned)oc_function << (unsigned)ocs_described_template,
11129         Complain, TargetFunctionType);
11130 
11131     if (Result != MatchesCopy.end()) {
11132       // Make it the first and only element
11133       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11134       Matches[0].second = cast<FunctionDecl>(*Result);
11135       Matches.resize(1);
11136     } else
11137       HasComplained |= Complain;
11138   }
11139 
11140   void EliminateAllTemplateMatches() {
11141     //   [...] any function template specializations in the set are
11142     //   eliminated if the set also contains a non-template function, [...]
11143     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11144       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11145         ++I;
11146       else {
11147         Matches[I] = Matches[--N];
11148         Matches.resize(N);
11149       }
11150     }
11151   }
11152 
11153   void EliminateSuboptimalCudaMatches() {
11154     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11155   }
11156 
11157 public:
11158   void ComplainNoMatchesFound() const {
11159     assert(Matches.empty());
11160     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11161         << OvlExpr->getName() << TargetFunctionType
11162         << OvlExpr->getSourceRange();
11163     if (FailedCandidates.empty())
11164       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11165                                   /*TakingAddress=*/true);
11166     else {
11167       // We have some deduction failure messages. Use them to diagnose
11168       // the function templates, and diagnose the non-template candidates
11169       // normally.
11170       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11171                                  IEnd = OvlExpr->decls_end();
11172            I != IEnd; ++I)
11173         if (FunctionDecl *Fun =
11174                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11175           if (!functionHasPassObjectSizeParams(Fun))
11176             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11177                                     /*TakingAddress=*/true);
11178       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11179     }
11180   }
11181 
11182   bool IsInvalidFormOfPointerToMemberFunction() const {
11183     return TargetTypeIsNonStaticMemberFunction &&
11184       !OvlExprInfo.HasFormOfMemberPointer;
11185   }
11186 
11187   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11188       // TODO: Should we condition this on whether any functions might
11189       // have matched, or is it more appropriate to do that in callers?
11190       // TODO: a fixit wouldn't hurt.
11191       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11192         << TargetType << OvlExpr->getSourceRange();
11193   }
11194 
11195   bool IsStaticMemberFunctionFromBoundPointer() const {
11196     return StaticMemberFunctionFromBoundPointer;
11197   }
11198 
11199   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11200     S.Diag(OvlExpr->getLocStart(),
11201            diag::err_invalid_form_pointer_member_function)
11202       << OvlExpr->getSourceRange();
11203   }
11204 
11205   void ComplainOfInvalidConversion() const {
11206     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11207       << OvlExpr->getName() << TargetType;
11208   }
11209 
11210   void ComplainMultipleMatchesFound() const {
11211     assert(Matches.size() > 1);
11212     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11213       << OvlExpr->getName()
11214       << OvlExpr->getSourceRange();
11215     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11216                                 /*TakingAddress=*/true);
11217   }
11218 
11219   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11220 
11221   int getNumMatches() const { return Matches.size(); }
11222 
11223   FunctionDecl* getMatchingFunctionDecl() const {
11224     if (Matches.size() != 1) return nullptr;
11225     return Matches[0].second;
11226   }
11227 
11228   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11229     if (Matches.size() != 1) return nullptr;
11230     return &Matches[0].first;
11231   }
11232 };
11233 }
11234 
11235 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11236 /// an overloaded function (C++ [over.over]), where @p From is an
11237 /// expression with overloaded function type and @p ToType is the type
11238 /// we're trying to resolve to. For example:
11239 ///
11240 /// @code
11241 /// int f(double);
11242 /// int f(int);
11243 ///
11244 /// int (*pfd)(double) = f; // selects f(double)
11245 /// @endcode
11246 ///
11247 /// This routine returns the resulting FunctionDecl if it could be
11248 /// resolved, and NULL otherwise. When @p Complain is true, this
11249 /// routine will emit diagnostics if there is an error.
11250 FunctionDecl *
11251 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11252                                          QualType TargetType,
11253                                          bool Complain,
11254                                          DeclAccessPair &FoundResult,
11255                                          bool *pHadMultipleCandidates) {
11256   assert(AddressOfExpr->getType() == Context.OverloadTy);
11257 
11258   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11259                                      Complain);
11260   int NumMatches = Resolver.getNumMatches();
11261   FunctionDecl *Fn = nullptr;
11262   bool ShouldComplain = Complain && !Resolver.hasComplained();
11263   if (NumMatches == 0 && ShouldComplain) {
11264     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11265       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11266     else
11267       Resolver.ComplainNoMatchesFound();
11268   }
11269   else if (NumMatches > 1 && ShouldComplain)
11270     Resolver.ComplainMultipleMatchesFound();
11271   else if (NumMatches == 1) {
11272     Fn = Resolver.getMatchingFunctionDecl();
11273     assert(Fn);
11274     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11275       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11276     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11277     if (Complain) {
11278       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11279         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11280       else
11281         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11282     }
11283   }
11284 
11285   if (pHadMultipleCandidates)
11286     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11287   return Fn;
11288 }
11289 
11290 /// Given an expression that refers to an overloaded function, try to
11291 /// resolve that function to a single function that can have its address taken.
11292 /// This will modify `Pair` iff it returns non-null.
11293 ///
11294 /// This routine can only realistically succeed if all but one candidates in the
11295 /// overload set for SrcExpr cannot have their addresses taken.
11296 FunctionDecl *
11297 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11298                                                   DeclAccessPair &Pair) {
11299   OverloadExpr::FindResult R = OverloadExpr::find(E);
11300   OverloadExpr *Ovl = R.Expression;
11301   FunctionDecl *Result = nullptr;
11302   DeclAccessPair DAP;
11303   // Don't use the AddressOfResolver because we're specifically looking for
11304   // cases where we have one overload candidate that lacks
11305   // enable_if/pass_object_size/...
11306   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11307     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11308     if (!FD)
11309       return nullptr;
11310 
11311     if (!checkAddressOfFunctionIsAvailable(FD))
11312       continue;
11313 
11314     // We have more than one result; quit.
11315     if (Result)
11316       return nullptr;
11317     DAP = I.getPair();
11318     Result = FD;
11319   }
11320 
11321   if (Result)
11322     Pair = DAP;
11323   return Result;
11324 }
11325 
11326 /// Given an overloaded function, tries to turn it into a non-overloaded
11327 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11328 /// will perform access checks, diagnose the use of the resultant decl, and, if
11329 /// requested, potentially perform a function-to-pointer decay.
11330 ///
11331 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11332 /// Otherwise, returns true. This may emit diagnostics and return true.
11333 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11334     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11335   Expr *E = SrcExpr.get();
11336   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11337 
11338   DeclAccessPair DAP;
11339   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11340   if (!Found)
11341     return false;
11342 
11343   // Emitting multiple diagnostics for a function that is both inaccessible and
11344   // unavailable is consistent with our behavior elsewhere. So, always check
11345   // for both.
11346   DiagnoseUseOfDecl(Found, E->getExprLoc());
11347   CheckAddressOfMemberAccess(E, DAP);
11348   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11349   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11350     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11351   else
11352     SrcExpr = Fixed;
11353   return true;
11354 }
11355 
11356 /// Given an expression that refers to an overloaded function, try to
11357 /// resolve that overloaded function expression down to a single function.
11358 ///
11359 /// This routine can only resolve template-ids that refer to a single function
11360 /// template, where that template-id refers to a single template whose template
11361 /// arguments are either provided by the template-id or have defaults,
11362 /// as described in C++0x [temp.arg.explicit]p3.
11363 ///
11364 /// If no template-ids are found, no diagnostics are emitted and NULL is
11365 /// returned.
11366 FunctionDecl *
11367 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11368                                                   bool Complain,
11369                                                   DeclAccessPair *FoundResult) {
11370   // C++ [over.over]p1:
11371   //   [...] [Note: any redundant set of parentheses surrounding the
11372   //   overloaded function name is ignored (5.1). ]
11373   // C++ [over.over]p1:
11374   //   [...] The overloaded function name can be preceded by the &
11375   //   operator.
11376 
11377   // If we didn't actually find any template-ids, we're done.
11378   if (!ovl->hasExplicitTemplateArgs())
11379     return nullptr;
11380 
11381   TemplateArgumentListInfo ExplicitTemplateArgs;
11382   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11383   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11384 
11385   // Look through all of the overloaded functions, searching for one
11386   // whose type matches exactly.
11387   FunctionDecl *Matched = nullptr;
11388   for (UnresolvedSetIterator I = ovl->decls_begin(),
11389          E = ovl->decls_end(); I != E; ++I) {
11390     // C++0x [temp.arg.explicit]p3:
11391     //   [...] In contexts where deduction is done and fails, or in contexts
11392     //   where deduction is not done, if a template argument list is
11393     //   specified and it, along with any default template arguments,
11394     //   identifies a single function template specialization, then the
11395     //   template-id is an lvalue for the function template specialization.
11396     FunctionTemplateDecl *FunctionTemplate
11397       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11398 
11399     // C++ [over.over]p2:
11400     //   If the name is a function template, template argument deduction is
11401     //   done (14.8.2.2), and if the argument deduction succeeds, the
11402     //   resulting template argument list is used to generate a single
11403     //   function template specialization, which is added to the set of
11404     //   overloaded functions considered.
11405     FunctionDecl *Specialization = nullptr;
11406     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11407     if (TemplateDeductionResult Result
11408           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11409                                     Specialization, Info,
11410                                     /*IsAddressOfFunction*/true)) {
11411       // Make a note of the failed deduction for diagnostics.
11412       // TODO: Actually use the failed-deduction info?
11413       FailedCandidates.addCandidate()
11414           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11415                MakeDeductionFailureInfo(Context, Result, Info));
11416       continue;
11417     }
11418 
11419     assert(Specialization && "no specialization and no error?");
11420 
11421     // Multiple matches; we can't resolve to a single declaration.
11422     if (Matched) {
11423       if (Complain) {
11424         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11425           << ovl->getName();
11426         NoteAllOverloadCandidates(ovl);
11427       }
11428       return nullptr;
11429     }
11430 
11431     Matched = Specialization;
11432     if (FoundResult) *FoundResult = I.getPair();
11433   }
11434 
11435   if (Matched &&
11436       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11437     return nullptr;
11438 
11439   return Matched;
11440 }
11441 
11442 // Resolve and fix an overloaded expression that can be resolved
11443 // because it identifies a single function template specialization.
11444 //
11445 // Last three arguments should only be supplied if Complain = true
11446 //
11447 // Return true if it was logically possible to so resolve the
11448 // expression, regardless of whether or not it succeeded.  Always
11449 // returns true if 'complain' is set.
11450 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11451                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11452                       bool complain, SourceRange OpRangeForComplaining,
11453                                            QualType DestTypeForComplaining,
11454                                             unsigned DiagIDForComplaining) {
11455   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11456 
11457   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11458 
11459   DeclAccessPair found;
11460   ExprResult SingleFunctionExpression;
11461   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11462                            ovl.Expression, /*complain*/ false, &found)) {
11463     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11464       SrcExpr = ExprError();
11465       return true;
11466     }
11467 
11468     // It is only correct to resolve to an instance method if we're
11469     // resolving a form that's permitted to be a pointer to member.
11470     // Otherwise we'll end up making a bound member expression, which
11471     // is illegal in all the contexts we resolve like this.
11472     if (!ovl.HasFormOfMemberPointer &&
11473         isa<CXXMethodDecl>(fn) &&
11474         cast<CXXMethodDecl>(fn)->isInstance()) {
11475       if (!complain) return false;
11476 
11477       Diag(ovl.Expression->getExprLoc(),
11478            diag::err_bound_member_function)
11479         << 0 << ovl.Expression->getSourceRange();
11480 
11481       // TODO: I believe we only end up here if there's a mix of
11482       // static and non-static candidates (otherwise the expression
11483       // would have 'bound member' type, not 'overload' type).
11484       // Ideally we would note which candidate was chosen and why
11485       // the static candidates were rejected.
11486       SrcExpr = ExprError();
11487       return true;
11488     }
11489 
11490     // Fix the expression to refer to 'fn'.
11491     SingleFunctionExpression =
11492         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11493 
11494     // If desired, do function-to-pointer decay.
11495     if (doFunctionPointerConverion) {
11496       SingleFunctionExpression =
11497         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11498       if (SingleFunctionExpression.isInvalid()) {
11499         SrcExpr = ExprError();
11500         return true;
11501       }
11502     }
11503   }
11504 
11505   if (!SingleFunctionExpression.isUsable()) {
11506     if (complain) {
11507       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11508         << ovl.Expression->getName()
11509         << DestTypeForComplaining
11510         << OpRangeForComplaining
11511         << ovl.Expression->getQualifierLoc().getSourceRange();
11512       NoteAllOverloadCandidates(SrcExpr.get());
11513 
11514       SrcExpr = ExprError();
11515       return true;
11516     }
11517 
11518     return false;
11519   }
11520 
11521   SrcExpr = SingleFunctionExpression;
11522   return true;
11523 }
11524 
11525 /// Add a single candidate to the overload set.
11526 static void AddOverloadedCallCandidate(Sema &S,
11527                                        DeclAccessPair FoundDecl,
11528                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11529                                        ArrayRef<Expr *> Args,
11530                                        OverloadCandidateSet &CandidateSet,
11531                                        bool PartialOverloading,
11532                                        bool KnownValid) {
11533   NamedDecl *Callee = FoundDecl.getDecl();
11534   if (isa<UsingShadowDecl>(Callee))
11535     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11536 
11537   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11538     if (ExplicitTemplateArgs) {
11539       assert(!KnownValid && "Explicit template arguments?");
11540       return;
11541     }
11542     // Prevent ill-formed function decls to be added as overload candidates.
11543     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11544       return;
11545 
11546     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11547                            /*SuppressUsedConversions=*/false,
11548                            PartialOverloading);
11549     return;
11550   }
11551 
11552   if (FunctionTemplateDecl *FuncTemplate
11553       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11554     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11555                                    ExplicitTemplateArgs, Args, CandidateSet,
11556                                    /*SuppressUsedConversions=*/false,
11557                                    PartialOverloading);
11558     return;
11559   }
11560 
11561   assert(!KnownValid && "unhandled case in overloaded call candidate");
11562 }
11563 
11564 /// Add the overload candidates named by callee and/or found by argument
11565 /// dependent lookup to the given overload set.
11566 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11567                                        ArrayRef<Expr *> Args,
11568                                        OverloadCandidateSet &CandidateSet,
11569                                        bool PartialOverloading) {
11570 
11571 #ifndef NDEBUG
11572   // Verify that ArgumentDependentLookup is consistent with the rules
11573   // in C++0x [basic.lookup.argdep]p3:
11574   //
11575   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11576   //   and let Y be the lookup set produced by argument dependent
11577   //   lookup (defined as follows). If X contains
11578   //
11579   //     -- a declaration of a class member, or
11580   //
11581   //     -- a block-scope function declaration that is not a
11582   //        using-declaration, or
11583   //
11584   //     -- a declaration that is neither a function or a function
11585   //        template
11586   //
11587   //   then Y is empty.
11588 
11589   if (ULE->requiresADL()) {
11590     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11591            E = ULE->decls_end(); I != E; ++I) {
11592       assert(!(*I)->getDeclContext()->isRecord());
11593       assert(isa<UsingShadowDecl>(*I) ||
11594              !(*I)->getDeclContext()->isFunctionOrMethod());
11595       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11596     }
11597   }
11598 #endif
11599 
11600   // It would be nice to avoid this copy.
11601   TemplateArgumentListInfo TABuffer;
11602   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11603   if (ULE->hasExplicitTemplateArgs()) {
11604     ULE->copyTemplateArgumentsInto(TABuffer);
11605     ExplicitTemplateArgs = &TABuffer;
11606   }
11607 
11608   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11609          E = ULE->decls_end(); I != E; ++I)
11610     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11611                                CandidateSet, PartialOverloading,
11612                                /*KnownValid*/ true);
11613 
11614   if (ULE->requiresADL())
11615     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11616                                          Args, ExplicitTemplateArgs,
11617                                          CandidateSet, PartialOverloading);
11618 }
11619 
11620 /// Determine whether a declaration with the specified name could be moved into
11621 /// a different namespace.
11622 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11623   switch (Name.getCXXOverloadedOperator()) {
11624   case OO_New: case OO_Array_New:
11625   case OO_Delete: case OO_Array_Delete:
11626     return false;
11627 
11628   default:
11629     return true;
11630   }
11631 }
11632 
11633 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11634 /// template, where the non-dependent name was declared after the template
11635 /// was defined. This is common in code written for a compilers which do not
11636 /// correctly implement two-stage name lookup.
11637 ///
11638 /// Returns true if a viable candidate was found and a diagnostic was issued.
11639 static bool
11640 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11641                        const CXXScopeSpec &SS, LookupResult &R,
11642                        OverloadCandidateSet::CandidateSetKind CSK,
11643                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11644                        ArrayRef<Expr *> Args,
11645                        bool *DoDiagnoseEmptyLookup = nullptr) {
11646   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11647     return false;
11648 
11649   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11650     if (DC->isTransparentContext())
11651       continue;
11652 
11653     SemaRef.LookupQualifiedName(R, DC);
11654 
11655     if (!R.empty()) {
11656       R.suppressDiagnostics();
11657 
11658       if (isa<CXXRecordDecl>(DC)) {
11659         // Don't diagnose names we find in classes; we get much better
11660         // diagnostics for these from DiagnoseEmptyLookup.
11661         R.clear();
11662         if (DoDiagnoseEmptyLookup)
11663           *DoDiagnoseEmptyLookup = true;
11664         return false;
11665       }
11666 
11667       OverloadCandidateSet Candidates(FnLoc, CSK);
11668       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11669         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11670                                    ExplicitTemplateArgs, Args,
11671                                    Candidates, false, /*KnownValid*/ false);
11672 
11673       OverloadCandidateSet::iterator Best;
11674       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11675         // No viable functions. Don't bother the user with notes for functions
11676         // which don't work and shouldn't be found anyway.
11677         R.clear();
11678         return false;
11679       }
11680 
11681       // Find the namespaces where ADL would have looked, and suggest
11682       // declaring the function there instead.
11683       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11684       Sema::AssociatedClassSet AssociatedClasses;
11685       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11686                                                  AssociatedNamespaces,
11687                                                  AssociatedClasses);
11688       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11689       if (canBeDeclaredInNamespace(R.getLookupName())) {
11690         DeclContext *Std = SemaRef.getStdNamespace();
11691         for (Sema::AssociatedNamespaceSet::iterator
11692                it = AssociatedNamespaces.begin(),
11693                end = AssociatedNamespaces.end(); it != end; ++it) {
11694           // Never suggest declaring a function within namespace 'std'.
11695           if (Std && Std->Encloses(*it))
11696             continue;
11697 
11698           // Never suggest declaring a function within a namespace with a
11699           // reserved name, like __gnu_cxx.
11700           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11701           if (NS &&
11702               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11703             continue;
11704 
11705           SuggestedNamespaces.insert(*it);
11706         }
11707       }
11708 
11709       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11710         << R.getLookupName();
11711       if (SuggestedNamespaces.empty()) {
11712         SemaRef.Diag(Best->Function->getLocation(),
11713                      diag::note_not_found_by_two_phase_lookup)
11714           << R.getLookupName() << 0;
11715       } else if (SuggestedNamespaces.size() == 1) {
11716         SemaRef.Diag(Best->Function->getLocation(),
11717                      diag::note_not_found_by_two_phase_lookup)
11718           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11719       } else {
11720         // FIXME: It would be useful to list the associated namespaces here,
11721         // but the diagnostics infrastructure doesn't provide a way to produce
11722         // a localized representation of a list of items.
11723         SemaRef.Diag(Best->Function->getLocation(),
11724                      diag::note_not_found_by_two_phase_lookup)
11725           << R.getLookupName() << 2;
11726       }
11727 
11728       // Try to recover by calling this function.
11729       return true;
11730     }
11731 
11732     R.clear();
11733   }
11734 
11735   return false;
11736 }
11737 
11738 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11739 /// template, where the non-dependent operator was declared after the template
11740 /// was defined.
11741 ///
11742 /// Returns true if a viable candidate was found and a diagnostic was issued.
11743 static bool
11744 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11745                                SourceLocation OpLoc,
11746                                ArrayRef<Expr *> Args) {
11747   DeclarationName OpName =
11748     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11749   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11750   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11751                                 OverloadCandidateSet::CSK_Operator,
11752                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11753 }
11754 
11755 namespace {
11756 class BuildRecoveryCallExprRAII {
11757   Sema &SemaRef;
11758 public:
11759   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11760     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11761     SemaRef.IsBuildingRecoveryCallExpr = true;
11762   }
11763 
11764   ~BuildRecoveryCallExprRAII() {
11765     SemaRef.IsBuildingRecoveryCallExpr = false;
11766   }
11767 };
11768 
11769 }
11770 
11771 static std::unique_ptr<CorrectionCandidateCallback>
11772 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11773               bool HasTemplateArgs, bool AllowTypoCorrection) {
11774   if (!AllowTypoCorrection)
11775     return llvm::make_unique<NoTypoCorrectionCCC>();
11776   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11777                                                   HasTemplateArgs, ME);
11778 }
11779 
11780 /// Attempts to recover from a call where no functions were found.
11781 ///
11782 /// Returns true if new candidates were found.
11783 static ExprResult
11784 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11785                       UnresolvedLookupExpr *ULE,
11786                       SourceLocation LParenLoc,
11787                       MutableArrayRef<Expr *> Args,
11788                       SourceLocation RParenLoc,
11789                       bool EmptyLookup, bool AllowTypoCorrection) {
11790   // Do not try to recover if it is already building a recovery call.
11791   // This stops infinite loops for template instantiations like
11792   //
11793   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11794   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11795   //
11796   if (SemaRef.IsBuildingRecoveryCallExpr)
11797     return ExprError();
11798   BuildRecoveryCallExprRAII RCE(SemaRef);
11799 
11800   CXXScopeSpec SS;
11801   SS.Adopt(ULE->getQualifierLoc());
11802   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11803 
11804   TemplateArgumentListInfo TABuffer;
11805   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11806   if (ULE->hasExplicitTemplateArgs()) {
11807     ULE->copyTemplateArgumentsInto(TABuffer);
11808     ExplicitTemplateArgs = &TABuffer;
11809   }
11810 
11811   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11812                  Sema::LookupOrdinaryName);
11813   bool DoDiagnoseEmptyLookup = EmptyLookup;
11814   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11815                               OverloadCandidateSet::CSK_Normal,
11816                               ExplicitTemplateArgs, Args,
11817                               &DoDiagnoseEmptyLookup) &&
11818     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11819         S, SS, R,
11820         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11821                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11822         ExplicitTemplateArgs, Args)))
11823     return ExprError();
11824 
11825   assert(!R.empty() && "lookup results empty despite recovery");
11826 
11827   // If recovery created an ambiguity, just bail out.
11828   if (R.isAmbiguous()) {
11829     R.suppressDiagnostics();
11830     return ExprError();
11831   }
11832 
11833   // Build an implicit member call if appropriate.  Just drop the
11834   // casts and such from the call, we don't really care.
11835   ExprResult NewFn = ExprError();
11836   if ((*R.begin())->isCXXClassMember())
11837     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11838                                                     ExplicitTemplateArgs, S);
11839   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11840     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11841                                         ExplicitTemplateArgs);
11842   else
11843     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11844 
11845   if (NewFn.isInvalid())
11846     return ExprError();
11847 
11848   // This shouldn't cause an infinite loop because we're giving it
11849   // an expression with viable lookup results, which should never
11850   // end up here.
11851   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11852                                MultiExprArg(Args.data(), Args.size()),
11853                                RParenLoc);
11854 }
11855 
11856 /// Constructs and populates an OverloadedCandidateSet from
11857 /// the given function.
11858 /// \returns true when an the ExprResult output parameter has been set.
11859 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11860                                   UnresolvedLookupExpr *ULE,
11861                                   MultiExprArg Args,
11862                                   SourceLocation RParenLoc,
11863                                   OverloadCandidateSet *CandidateSet,
11864                                   ExprResult *Result) {
11865 #ifndef NDEBUG
11866   if (ULE->requiresADL()) {
11867     // To do ADL, we must have found an unqualified name.
11868     assert(!ULE->getQualifier() && "qualified name with ADL");
11869 
11870     // We don't perform ADL for implicit declarations of builtins.
11871     // Verify that this was correctly set up.
11872     FunctionDecl *F;
11873     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11874         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11875         F->getBuiltinID() && F->isImplicit())
11876       llvm_unreachable("performing ADL for builtin");
11877 
11878     // We don't perform ADL in C.
11879     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11880   }
11881 #endif
11882 
11883   UnbridgedCastsSet UnbridgedCasts;
11884   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11885     *Result = ExprError();
11886     return true;
11887   }
11888 
11889   // Add the functions denoted by the callee to the set of candidate
11890   // functions, including those from argument-dependent lookup.
11891   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11892 
11893   if (getLangOpts().MSVCCompat &&
11894       CurContext->isDependentContext() && !isSFINAEContext() &&
11895       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11896 
11897     OverloadCandidateSet::iterator Best;
11898     if (CandidateSet->empty() ||
11899         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11900             OR_No_Viable_Function) {
11901       // In Microsoft mode, if we are inside a template class member function then
11902       // create a type dependent CallExpr. The goal is to postpone name lookup
11903       // to instantiation time to be able to search into type dependent base
11904       // classes.
11905       CallExpr *CE = new (Context) CallExpr(
11906           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11907       CE->setTypeDependent(true);
11908       CE->setValueDependent(true);
11909       CE->setInstantiationDependent(true);
11910       *Result = CE;
11911       return true;
11912     }
11913   }
11914 
11915   if (CandidateSet->empty())
11916     return false;
11917 
11918   UnbridgedCasts.restore();
11919   return false;
11920 }
11921 
11922 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11923 /// the completed call expression. If overload resolution fails, emits
11924 /// diagnostics and returns ExprError()
11925 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11926                                            UnresolvedLookupExpr *ULE,
11927                                            SourceLocation LParenLoc,
11928                                            MultiExprArg Args,
11929                                            SourceLocation RParenLoc,
11930                                            Expr *ExecConfig,
11931                                            OverloadCandidateSet *CandidateSet,
11932                                            OverloadCandidateSet::iterator *Best,
11933                                            OverloadingResult OverloadResult,
11934                                            bool AllowTypoCorrection) {
11935   if (CandidateSet->empty())
11936     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11937                                  RParenLoc, /*EmptyLookup=*/true,
11938                                  AllowTypoCorrection);
11939 
11940   switch (OverloadResult) {
11941   case OR_Success: {
11942     FunctionDecl *FDecl = (*Best)->Function;
11943     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11944     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11945       return ExprError();
11946     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11947     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11948                                          ExecConfig);
11949   }
11950 
11951   case OR_No_Viable_Function: {
11952     // Try to recover by looking for viable functions which the user might
11953     // have meant to call.
11954     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11955                                                 Args, RParenLoc,
11956                                                 /*EmptyLookup=*/false,
11957                                                 AllowTypoCorrection);
11958     if (!Recovery.isInvalid())
11959       return Recovery;
11960 
11961     // If the user passes in a function that we can't take the address of, we
11962     // generally end up emitting really bad error messages. Here, we attempt to
11963     // emit better ones.
11964     for (const Expr *Arg : Args) {
11965       if (!Arg->getType()->isFunctionType())
11966         continue;
11967       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11968         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11969         if (FD &&
11970             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11971                                                        Arg->getExprLoc()))
11972           return ExprError();
11973       }
11974     }
11975 
11976     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11977         << ULE->getName() << Fn->getSourceRange();
11978     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11979     break;
11980   }
11981 
11982   case OR_Ambiguous:
11983     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11984       << ULE->getName() << Fn->getSourceRange();
11985     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11986     break;
11987 
11988   case OR_Deleted: {
11989     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11990       << (*Best)->Function->isDeleted()
11991       << ULE->getName()
11992       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11993       << Fn->getSourceRange();
11994     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11995 
11996     // We emitted an error for the unavailable/deleted function call but keep
11997     // the call in the AST.
11998     FunctionDecl *FDecl = (*Best)->Function;
11999     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12000     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12001                                          ExecConfig);
12002   }
12003   }
12004 
12005   // Overload resolution failed.
12006   return ExprError();
12007 }
12008 
12009 static void markUnaddressableCandidatesUnviable(Sema &S,
12010                                                 OverloadCandidateSet &CS) {
12011   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12012     if (I->Viable &&
12013         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12014       I->Viable = false;
12015       I->FailureKind = ovl_fail_addr_not_available;
12016     }
12017   }
12018 }
12019 
12020 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12021 /// (which eventually refers to the declaration Func) and the call
12022 /// arguments Args/NumArgs, attempt to resolve the function call down
12023 /// to a specific function. If overload resolution succeeds, returns
12024 /// the call expression produced by overload resolution.
12025 /// Otherwise, emits diagnostics and returns ExprError.
12026 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12027                                          UnresolvedLookupExpr *ULE,
12028                                          SourceLocation LParenLoc,
12029                                          MultiExprArg Args,
12030                                          SourceLocation RParenLoc,
12031                                          Expr *ExecConfig,
12032                                          bool AllowTypoCorrection,
12033                                          bool CalleesAddressIsTaken) {
12034   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12035                                     OverloadCandidateSet::CSK_Normal);
12036   ExprResult result;
12037 
12038   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12039                              &result))
12040     return result;
12041 
12042   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12043   // functions that aren't addressible are considered unviable.
12044   if (CalleesAddressIsTaken)
12045     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12046 
12047   OverloadCandidateSet::iterator Best;
12048   OverloadingResult OverloadResult =
12049       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12050 
12051   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12052                                   RParenLoc, ExecConfig, &CandidateSet,
12053                                   &Best, OverloadResult,
12054                                   AllowTypoCorrection);
12055 }
12056 
12057 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12058   return Functions.size() > 1 ||
12059     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12060 }
12061 
12062 /// Create a unary operation that may resolve to an overloaded
12063 /// operator.
12064 ///
12065 /// \param OpLoc The location of the operator itself (e.g., '*').
12066 ///
12067 /// \param Opc The UnaryOperatorKind that describes this operator.
12068 ///
12069 /// \param Fns The set of non-member functions that will be
12070 /// considered by overload resolution. The caller needs to build this
12071 /// set based on the context using, e.g.,
12072 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12073 /// set should not contain any member functions; those will be added
12074 /// by CreateOverloadedUnaryOp().
12075 ///
12076 /// \param Input The input argument.
12077 ExprResult
12078 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12079                               const UnresolvedSetImpl &Fns,
12080                               Expr *Input, bool PerformADL) {
12081   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12082   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12083   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12084   // TODO: provide better source location info.
12085   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12086 
12087   if (checkPlaceholderForOverload(*this, Input))
12088     return ExprError();
12089 
12090   Expr *Args[2] = { Input, nullptr };
12091   unsigned NumArgs = 1;
12092 
12093   // For post-increment and post-decrement, add the implicit '0' as
12094   // the second argument, so that we know this is a post-increment or
12095   // post-decrement.
12096   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12097     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12098     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12099                                      SourceLocation());
12100     NumArgs = 2;
12101   }
12102 
12103   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12104 
12105   if (Input->isTypeDependent()) {
12106     if (Fns.empty())
12107       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12108                                          VK_RValue, OK_Ordinary, OpLoc, false);
12109 
12110     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12111     UnresolvedLookupExpr *Fn
12112       = UnresolvedLookupExpr::Create(Context, NamingClass,
12113                                      NestedNameSpecifierLoc(), OpNameInfo,
12114                                      /*ADL*/ true, IsOverloaded(Fns),
12115                                      Fns.begin(), Fns.end());
12116     return new (Context)
12117         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12118                             VK_RValue, OpLoc, FPOptions());
12119   }
12120 
12121   // Build an empty overload set.
12122   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12123 
12124   // Add the candidates from the given function set.
12125   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12126 
12127   // Add operator candidates that are member functions.
12128   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12129 
12130   // Add candidates from ADL.
12131   if (PerformADL) {
12132     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12133                                          /*ExplicitTemplateArgs*/nullptr,
12134                                          CandidateSet);
12135   }
12136 
12137   // Add builtin operator candidates.
12138   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12139 
12140   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12141 
12142   // Perform overload resolution.
12143   OverloadCandidateSet::iterator Best;
12144   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12145   case OR_Success: {
12146     // We found a built-in operator or an overloaded operator.
12147     FunctionDecl *FnDecl = Best->Function;
12148 
12149     if (FnDecl) {
12150       Expr *Base = nullptr;
12151       // We matched an overloaded operator. Build a call to that
12152       // operator.
12153 
12154       // Convert the arguments.
12155       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12156         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12157 
12158         ExprResult InputRes =
12159           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12160                                               Best->FoundDecl, Method);
12161         if (InputRes.isInvalid())
12162           return ExprError();
12163         Base = Input = InputRes.get();
12164       } else {
12165         // Convert the arguments.
12166         ExprResult InputInit
12167           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12168                                                       Context,
12169                                                       FnDecl->getParamDecl(0)),
12170                                       SourceLocation(),
12171                                       Input);
12172         if (InputInit.isInvalid())
12173           return ExprError();
12174         Input = InputInit.get();
12175       }
12176 
12177       // Build the actual expression node.
12178       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12179                                                 Base, HadMultipleCandidates,
12180                                                 OpLoc);
12181       if (FnExpr.isInvalid())
12182         return ExprError();
12183 
12184       // Determine the result type.
12185       QualType ResultTy = FnDecl->getReturnType();
12186       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12187       ResultTy = ResultTy.getNonLValueExprType(Context);
12188 
12189       Args[0] = Input;
12190       CallExpr *TheCall =
12191         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12192                                           ResultTy, VK, OpLoc, FPOptions());
12193 
12194       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12195         return ExprError();
12196 
12197       if (CheckFunctionCall(FnDecl, TheCall,
12198                             FnDecl->getType()->castAs<FunctionProtoType>()))
12199         return ExprError();
12200 
12201       return MaybeBindToTemporary(TheCall);
12202     } else {
12203       // We matched a built-in operator. Convert the arguments, then
12204       // break out so that we will build the appropriate built-in
12205       // operator node.
12206       ExprResult InputRes = PerformImplicitConversion(
12207           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12208           CCK_ForBuiltinOverloadedOp);
12209       if (InputRes.isInvalid())
12210         return ExprError();
12211       Input = InputRes.get();
12212       break;
12213     }
12214   }
12215 
12216   case OR_No_Viable_Function:
12217     // This is an erroneous use of an operator which can be overloaded by
12218     // a non-member function. Check for non-member operators which were
12219     // defined too late to be candidates.
12220     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12221       // FIXME: Recover by calling the found function.
12222       return ExprError();
12223 
12224     // No viable function; fall through to handling this as a
12225     // built-in operator, which will produce an error message for us.
12226     break;
12227 
12228   case OR_Ambiguous:
12229     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12230         << UnaryOperator::getOpcodeStr(Opc)
12231         << Input->getType()
12232         << Input->getSourceRange();
12233     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12234                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12235     return ExprError();
12236 
12237   case OR_Deleted:
12238     Diag(OpLoc, diag::err_ovl_deleted_oper)
12239       << Best->Function->isDeleted()
12240       << UnaryOperator::getOpcodeStr(Opc)
12241       << getDeletedOrUnavailableSuffix(Best->Function)
12242       << Input->getSourceRange();
12243     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12244                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12245     return ExprError();
12246   }
12247 
12248   // Either we found no viable overloaded operator or we matched a
12249   // built-in operator. In either case, fall through to trying to
12250   // build a built-in operation.
12251   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12252 }
12253 
12254 /// Create a binary operation that may resolve to an overloaded
12255 /// operator.
12256 ///
12257 /// \param OpLoc The location of the operator itself (e.g., '+').
12258 ///
12259 /// \param Opc The BinaryOperatorKind that describes this operator.
12260 ///
12261 /// \param Fns The set of non-member functions that will be
12262 /// considered by overload resolution. The caller needs to build this
12263 /// set based on the context using, e.g.,
12264 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12265 /// set should not contain any member functions; those will be added
12266 /// by CreateOverloadedBinOp().
12267 ///
12268 /// \param LHS Left-hand argument.
12269 /// \param RHS Right-hand argument.
12270 ExprResult
12271 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12272                             BinaryOperatorKind Opc,
12273                             const UnresolvedSetImpl &Fns,
12274                             Expr *LHS, Expr *RHS, bool PerformADL) {
12275   Expr *Args[2] = { LHS, RHS };
12276   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12277 
12278   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12279   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12280 
12281   // If either side is type-dependent, create an appropriate dependent
12282   // expression.
12283   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12284     if (Fns.empty()) {
12285       // If there are no functions to store, just build a dependent
12286       // BinaryOperator or CompoundAssignment.
12287       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12288         return new (Context) BinaryOperator(
12289             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12290             OpLoc, FPFeatures);
12291 
12292       return new (Context) CompoundAssignOperator(
12293           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12294           Context.DependentTy, Context.DependentTy, OpLoc,
12295           FPFeatures);
12296     }
12297 
12298     // FIXME: save results of ADL from here?
12299     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12300     // TODO: provide better source location info in DNLoc component.
12301     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12302     UnresolvedLookupExpr *Fn
12303       = UnresolvedLookupExpr::Create(Context, NamingClass,
12304                                      NestedNameSpecifierLoc(), OpNameInfo,
12305                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12306                                      Fns.begin(), Fns.end());
12307     return new (Context)
12308         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12309                             VK_RValue, OpLoc, FPFeatures);
12310   }
12311 
12312   // Always do placeholder-like conversions on the RHS.
12313   if (checkPlaceholderForOverload(*this, Args[1]))
12314     return ExprError();
12315 
12316   // Do placeholder-like conversion on the LHS; note that we should
12317   // not get here with a PseudoObject LHS.
12318   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12319   if (checkPlaceholderForOverload(*this, Args[0]))
12320     return ExprError();
12321 
12322   // If this is the assignment operator, we only perform overload resolution
12323   // if the left-hand side is a class or enumeration type. This is actually
12324   // a hack. The standard requires that we do overload resolution between the
12325   // various built-in candidates, but as DR507 points out, this can lead to
12326   // problems. So we do it this way, which pretty much follows what GCC does.
12327   // Note that we go the traditional code path for compound assignment forms.
12328   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12329     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12330 
12331   // If this is the .* operator, which is not overloadable, just
12332   // create a built-in binary operator.
12333   if (Opc == BO_PtrMemD)
12334     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12335 
12336   // Build an empty overload set.
12337   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12338 
12339   // Add the candidates from the given function set.
12340   AddFunctionCandidates(Fns, Args, CandidateSet);
12341 
12342   // Add operator candidates that are member functions.
12343   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12344 
12345   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12346   // performed for an assignment operator (nor for operator[] nor operator->,
12347   // which don't get here).
12348   if (Opc != BO_Assign && PerformADL)
12349     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12350                                          /*ExplicitTemplateArgs*/ nullptr,
12351                                          CandidateSet);
12352 
12353   // Add builtin operator candidates.
12354   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12355 
12356   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12357 
12358   // Perform overload resolution.
12359   OverloadCandidateSet::iterator Best;
12360   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12361     case OR_Success: {
12362       // We found a built-in operator or an overloaded operator.
12363       FunctionDecl *FnDecl = Best->Function;
12364 
12365       if (FnDecl) {
12366         Expr *Base = nullptr;
12367         // We matched an overloaded operator. Build a call to that
12368         // operator.
12369 
12370         // Convert the arguments.
12371         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12372           // Best->Access is only meaningful for class members.
12373           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12374 
12375           ExprResult Arg1 =
12376             PerformCopyInitialization(
12377               InitializedEntity::InitializeParameter(Context,
12378                                                      FnDecl->getParamDecl(0)),
12379               SourceLocation(), Args[1]);
12380           if (Arg1.isInvalid())
12381             return ExprError();
12382 
12383           ExprResult Arg0 =
12384             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12385                                                 Best->FoundDecl, Method);
12386           if (Arg0.isInvalid())
12387             return ExprError();
12388           Base = Args[0] = Arg0.getAs<Expr>();
12389           Args[1] = RHS = Arg1.getAs<Expr>();
12390         } else {
12391           // Convert the arguments.
12392           ExprResult Arg0 = PerformCopyInitialization(
12393             InitializedEntity::InitializeParameter(Context,
12394                                                    FnDecl->getParamDecl(0)),
12395             SourceLocation(), Args[0]);
12396           if (Arg0.isInvalid())
12397             return ExprError();
12398 
12399           ExprResult Arg1 =
12400             PerformCopyInitialization(
12401               InitializedEntity::InitializeParameter(Context,
12402                                                      FnDecl->getParamDecl(1)),
12403               SourceLocation(), Args[1]);
12404           if (Arg1.isInvalid())
12405             return ExprError();
12406           Args[0] = LHS = Arg0.getAs<Expr>();
12407           Args[1] = RHS = Arg1.getAs<Expr>();
12408         }
12409 
12410         // Build the actual expression node.
12411         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12412                                                   Best->FoundDecl, Base,
12413                                                   HadMultipleCandidates, OpLoc);
12414         if (FnExpr.isInvalid())
12415           return ExprError();
12416 
12417         // Determine the result type.
12418         QualType ResultTy = FnDecl->getReturnType();
12419         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12420         ResultTy = ResultTy.getNonLValueExprType(Context);
12421 
12422         CXXOperatorCallExpr *TheCall =
12423           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12424                                             Args, ResultTy, VK, OpLoc,
12425                                             FPFeatures);
12426 
12427         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12428                                 FnDecl))
12429           return ExprError();
12430 
12431         ArrayRef<const Expr *> ArgsArray(Args, 2);
12432         const Expr *ImplicitThis = nullptr;
12433         // Cut off the implicit 'this'.
12434         if (isa<CXXMethodDecl>(FnDecl)) {
12435           ImplicitThis = ArgsArray[0];
12436           ArgsArray = ArgsArray.slice(1);
12437         }
12438 
12439         // Check for a self move.
12440         if (Op == OO_Equal)
12441           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12442 
12443         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12444                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12445                   VariadicDoesNotApply);
12446 
12447         return MaybeBindToTemporary(TheCall);
12448       } else {
12449         // We matched a built-in operator. Convert the arguments, then
12450         // break out so that we will build the appropriate built-in
12451         // operator node.
12452         ExprResult ArgsRes0 = PerformImplicitConversion(
12453             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12454             AA_Passing, CCK_ForBuiltinOverloadedOp);
12455         if (ArgsRes0.isInvalid())
12456           return ExprError();
12457         Args[0] = ArgsRes0.get();
12458 
12459         ExprResult ArgsRes1 = PerformImplicitConversion(
12460             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12461             AA_Passing, CCK_ForBuiltinOverloadedOp);
12462         if (ArgsRes1.isInvalid())
12463           return ExprError();
12464         Args[1] = ArgsRes1.get();
12465         break;
12466       }
12467     }
12468 
12469     case OR_No_Viable_Function: {
12470       // C++ [over.match.oper]p9:
12471       //   If the operator is the operator , [...] and there are no
12472       //   viable functions, then the operator is assumed to be the
12473       //   built-in operator and interpreted according to clause 5.
12474       if (Opc == BO_Comma)
12475         break;
12476 
12477       // For class as left operand for assignment or compound assignment
12478       // operator do not fall through to handling in built-in, but report that
12479       // no overloaded assignment operator found
12480       ExprResult Result = ExprError();
12481       if (Args[0]->getType()->isRecordType() &&
12482           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12483         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12484              << BinaryOperator::getOpcodeStr(Opc)
12485              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12486         if (Args[0]->getType()->isIncompleteType()) {
12487           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12488             << Args[0]->getType()
12489             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12490         }
12491       } else {
12492         // This is an erroneous use of an operator which can be overloaded by
12493         // a non-member function. Check for non-member operators which were
12494         // defined too late to be candidates.
12495         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12496           // FIXME: Recover by calling the found function.
12497           return ExprError();
12498 
12499         // No viable function; try to create a built-in operation, which will
12500         // produce an error. Then, show the non-viable candidates.
12501         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12502       }
12503       assert(Result.isInvalid() &&
12504              "C++ binary operator overloading is missing candidates!");
12505       if (Result.isInvalid())
12506         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12507                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12508       return Result;
12509     }
12510 
12511     case OR_Ambiguous:
12512       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12513           << BinaryOperator::getOpcodeStr(Opc)
12514           << Args[0]->getType() << Args[1]->getType()
12515           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12516       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12517                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12518       return ExprError();
12519 
12520     case OR_Deleted:
12521       if (isImplicitlyDeleted(Best->Function)) {
12522         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12523         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12524           << Context.getRecordType(Method->getParent())
12525           << getSpecialMember(Method);
12526 
12527         // The user probably meant to call this special member. Just
12528         // explain why it's deleted.
12529         NoteDeletedFunction(Method);
12530         return ExprError();
12531       } else {
12532         Diag(OpLoc, diag::err_ovl_deleted_oper)
12533           << Best->Function->isDeleted()
12534           << BinaryOperator::getOpcodeStr(Opc)
12535           << getDeletedOrUnavailableSuffix(Best->Function)
12536           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12537       }
12538       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12539                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12540       return ExprError();
12541   }
12542 
12543   // We matched a built-in operator; build it.
12544   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12545 }
12546 
12547 ExprResult
12548 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12549                                          SourceLocation RLoc,
12550                                          Expr *Base, Expr *Idx) {
12551   Expr *Args[2] = { Base, Idx };
12552   DeclarationName OpName =
12553       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12554 
12555   // If either side is type-dependent, create an appropriate dependent
12556   // expression.
12557   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12558 
12559     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12560     // CHECKME: no 'operator' keyword?
12561     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12562     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12563     UnresolvedLookupExpr *Fn
12564       = UnresolvedLookupExpr::Create(Context, NamingClass,
12565                                      NestedNameSpecifierLoc(), OpNameInfo,
12566                                      /*ADL*/ true, /*Overloaded*/ false,
12567                                      UnresolvedSetIterator(),
12568                                      UnresolvedSetIterator());
12569     // Can't add any actual overloads yet
12570 
12571     return new (Context)
12572         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12573                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12574   }
12575 
12576   // Handle placeholders on both operands.
12577   if (checkPlaceholderForOverload(*this, Args[0]))
12578     return ExprError();
12579   if (checkPlaceholderForOverload(*this, Args[1]))
12580     return ExprError();
12581 
12582   // Build an empty overload set.
12583   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12584 
12585   // Subscript can only be overloaded as a member function.
12586 
12587   // Add operator candidates that are member functions.
12588   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12589 
12590   // Add builtin operator candidates.
12591   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12592 
12593   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12594 
12595   // Perform overload resolution.
12596   OverloadCandidateSet::iterator Best;
12597   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12598     case OR_Success: {
12599       // We found a built-in operator or an overloaded operator.
12600       FunctionDecl *FnDecl = Best->Function;
12601 
12602       if (FnDecl) {
12603         // We matched an overloaded operator. Build a call to that
12604         // operator.
12605 
12606         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12607 
12608         // Convert the arguments.
12609         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12610         ExprResult Arg0 =
12611           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12612                                               Best->FoundDecl, Method);
12613         if (Arg0.isInvalid())
12614           return ExprError();
12615         Args[0] = Arg0.get();
12616 
12617         // Convert the arguments.
12618         ExprResult InputInit
12619           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12620                                                       Context,
12621                                                       FnDecl->getParamDecl(0)),
12622                                       SourceLocation(),
12623                                       Args[1]);
12624         if (InputInit.isInvalid())
12625           return ExprError();
12626 
12627         Args[1] = InputInit.getAs<Expr>();
12628 
12629         // Build the actual expression node.
12630         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12631         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12632         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12633                                                   Best->FoundDecl,
12634                                                   Base,
12635                                                   HadMultipleCandidates,
12636                                                   OpLocInfo.getLoc(),
12637                                                   OpLocInfo.getInfo());
12638         if (FnExpr.isInvalid())
12639           return ExprError();
12640 
12641         // Determine the result type
12642         QualType ResultTy = FnDecl->getReturnType();
12643         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12644         ResultTy = ResultTy.getNonLValueExprType(Context);
12645 
12646         CXXOperatorCallExpr *TheCall =
12647           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12648                                             FnExpr.get(), Args,
12649                                             ResultTy, VK, RLoc,
12650                                             FPOptions());
12651 
12652         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12653           return ExprError();
12654 
12655         if (CheckFunctionCall(Method, TheCall,
12656                               Method->getType()->castAs<FunctionProtoType>()))
12657           return ExprError();
12658 
12659         return MaybeBindToTemporary(TheCall);
12660       } else {
12661         // We matched a built-in operator. Convert the arguments, then
12662         // break out so that we will build the appropriate built-in
12663         // operator node.
12664         ExprResult ArgsRes0 = PerformImplicitConversion(
12665             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12666             AA_Passing, CCK_ForBuiltinOverloadedOp);
12667         if (ArgsRes0.isInvalid())
12668           return ExprError();
12669         Args[0] = ArgsRes0.get();
12670 
12671         ExprResult ArgsRes1 = PerformImplicitConversion(
12672             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12673             AA_Passing, CCK_ForBuiltinOverloadedOp);
12674         if (ArgsRes1.isInvalid())
12675           return ExprError();
12676         Args[1] = ArgsRes1.get();
12677 
12678         break;
12679       }
12680     }
12681 
12682     case OR_No_Viable_Function: {
12683       if (CandidateSet.empty())
12684         Diag(LLoc, diag::err_ovl_no_oper)
12685           << Args[0]->getType() << /*subscript*/ 0
12686           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12687       else
12688         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12689           << Args[0]->getType()
12690           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12691       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12692                                   "[]", LLoc);
12693       return ExprError();
12694     }
12695 
12696     case OR_Ambiguous:
12697       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12698           << "[]"
12699           << Args[0]->getType() << Args[1]->getType()
12700           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12701       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12702                                   "[]", LLoc);
12703       return ExprError();
12704 
12705     case OR_Deleted:
12706       Diag(LLoc, diag::err_ovl_deleted_oper)
12707         << Best->Function->isDeleted() << "[]"
12708         << getDeletedOrUnavailableSuffix(Best->Function)
12709         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12710       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12711                                   "[]", LLoc);
12712       return ExprError();
12713     }
12714 
12715   // We matched a built-in operator; build it.
12716   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12717 }
12718 
12719 /// BuildCallToMemberFunction - Build a call to a member
12720 /// function. MemExpr is the expression that refers to the member
12721 /// function (and includes the object parameter), Args/NumArgs are the
12722 /// arguments to the function call (not including the object
12723 /// parameter). The caller needs to validate that the member
12724 /// expression refers to a non-static member function or an overloaded
12725 /// member function.
12726 ExprResult
12727 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12728                                 SourceLocation LParenLoc,
12729                                 MultiExprArg Args,
12730                                 SourceLocation RParenLoc) {
12731   assert(MemExprE->getType() == Context.BoundMemberTy ||
12732          MemExprE->getType() == Context.OverloadTy);
12733 
12734   // Dig out the member expression. This holds both the object
12735   // argument and the member function we're referring to.
12736   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12737 
12738   // Determine whether this is a call to a pointer-to-member function.
12739   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12740     assert(op->getType() == Context.BoundMemberTy);
12741     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12742 
12743     QualType fnType =
12744       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12745 
12746     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12747     QualType resultType = proto->getCallResultType(Context);
12748     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12749 
12750     // Check that the object type isn't more qualified than the
12751     // member function we're calling.
12752     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12753 
12754     QualType objectType = op->getLHS()->getType();
12755     if (op->getOpcode() == BO_PtrMemI)
12756       objectType = objectType->castAs<PointerType>()->getPointeeType();
12757     Qualifiers objectQuals = objectType.getQualifiers();
12758 
12759     Qualifiers difference = objectQuals - funcQuals;
12760     difference.removeObjCGCAttr();
12761     difference.removeAddressSpace();
12762     if (difference) {
12763       std::string qualsString = difference.getAsString();
12764       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12765         << fnType.getUnqualifiedType()
12766         << qualsString
12767         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12768     }
12769 
12770     CXXMemberCallExpr *call
12771       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12772                                         resultType, valueKind, RParenLoc);
12773 
12774     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12775                             call, nullptr))
12776       return ExprError();
12777 
12778     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12779       return ExprError();
12780 
12781     if (CheckOtherCall(call, proto))
12782       return ExprError();
12783 
12784     return MaybeBindToTemporary(call);
12785   }
12786 
12787   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12788     return new (Context)
12789         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12790 
12791   UnbridgedCastsSet UnbridgedCasts;
12792   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12793     return ExprError();
12794 
12795   MemberExpr *MemExpr;
12796   CXXMethodDecl *Method = nullptr;
12797   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12798   NestedNameSpecifier *Qualifier = nullptr;
12799   if (isa<MemberExpr>(NakedMemExpr)) {
12800     MemExpr = cast<MemberExpr>(NakedMemExpr);
12801     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12802     FoundDecl = MemExpr->getFoundDecl();
12803     Qualifier = MemExpr->getQualifier();
12804     UnbridgedCasts.restore();
12805   } else {
12806     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12807     Qualifier = UnresExpr->getQualifier();
12808 
12809     QualType ObjectType = UnresExpr->getBaseType();
12810     Expr::Classification ObjectClassification
12811       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12812                             : UnresExpr->getBase()->Classify(Context);
12813 
12814     // Add overload candidates
12815     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12816                                       OverloadCandidateSet::CSK_Normal);
12817 
12818     // FIXME: avoid copy.
12819     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12820     if (UnresExpr->hasExplicitTemplateArgs()) {
12821       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12822       TemplateArgs = &TemplateArgsBuffer;
12823     }
12824 
12825     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12826            E = UnresExpr->decls_end(); I != E; ++I) {
12827 
12828       NamedDecl *Func = *I;
12829       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12830       if (isa<UsingShadowDecl>(Func))
12831         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12832 
12833 
12834       // Microsoft supports direct constructor calls.
12835       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12836         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12837                              Args, CandidateSet);
12838       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12839         // If explicit template arguments were provided, we can't call a
12840         // non-template member function.
12841         if (TemplateArgs)
12842           continue;
12843 
12844         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12845                            ObjectClassification, Args, CandidateSet,
12846                            /*SuppressUserConversions=*/false);
12847       } else {
12848         AddMethodTemplateCandidate(
12849             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12850             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12851             /*SuppressUsedConversions=*/false);
12852       }
12853     }
12854 
12855     DeclarationName DeclName = UnresExpr->getMemberName();
12856 
12857     UnbridgedCasts.restore();
12858 
12859     OverloadCandidateSet::iterator Best;
12860     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12861                                             Best)) {
12862     case OR_Success:
12863       Method = cast<CXXMethodDecl>(Best->Function);
12864       FoundDecl = Best->FoundDecl;
12865       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12866       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12867         return ExprError();
12868       // If FoundDecl is different from Method (such as if one is a template
12869       // and the other a specialization), make sure DiagnoseUseOfDecl is
12870       // called on both.
12871       // FIXME: This would be more comprehensively addressed by modifying
12872       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12873       // being used.
12874       if (Method != FoundDecl.getDecl() &&
12875                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12876         return ExprError();
12877       break;
12878 
12879     case OR_No_Viable_Function:
12880       Diag(UnresExpr->getMemberLoc(),
12881            diag::err_ovl_no_viable_member_function_in_call)
12882         << DeclName << MemExprE->getSourceRange();
12883       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12884       // FIXME: Leaking incoming expressions!
12885       return ExprError();
12886 
12887     case OR_Ambiguous:
12888       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12889         << DeclName << MemExprE->getSourceRange();
12890       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12891       // FIXME: Leaking incoming expressions!
12892       return ExprError();
12893 
12894     case OR_Deleted:
12895       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12896         << Best->Function->isDeleted()
12897         << DeclName
12898         << getDeletedOrUnavailableSuffix(Best->Function)
12899         << MemExprE->getSourceRange();
12900       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12901       // FIXME: Leaking incoming expressions!
12902       return ExprError();
12903     }
12904 
12905     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12906 
12907     // If overload resolution picked a static member, build a
12908     // non-member call based on that function.
12909     if (Method->isStatic()) {
12910       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12911                                    RParenLoc);
12912     }
12913 
12914     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12915   }
12916 
12917   QualType ResultType = Method->getReturnType();
12918   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12919   ResultType = ResultType.getNonLValueExprType(Context);
12920 
12921   assert(Method && "Member call to something that isn't a method?");
12922   CXXMemberCallExpr *TheCall =
12923     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12924                                     ResultType, VK, RParenLoc);
12925 
12926   // Check for a valid return type.
12927   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12928                           TheCall, Method))
12929     return ExprError();
12930 
12931   // Convert the object argument (for a non-static member function call).
12932   // We only need to do this if there was actually an overload; otherwise
12933   // it was done at lookup.
12934   if (!Method->isStatic()) {
12935     ExprResult ObjectArg =
12936       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12937                                           FoundDecl, Method);
12938     if (ObjectArg.isInvalid())
12939       return ExprError();
12940     MemExpr->setBase(ObjectArg.get());
12941   }
12942 
12943   // Convert the rest of the arguments
12944   const FunctionProtoType *Proto =
12945     Method->getType()->getAs<FunctionProtoType>();
12946   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12947                               RParenLoc))
12948     return ExprError();
12949 
12950   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12951 
12952   if (CheckFunctionCall(Method, TheCall, Proto))
12953     return ExprError();
12954 
12955   // In the case the method to call was not selected by the overloading
12956   // resolution process, we still need to handle the enable_if attribute. Do
12957   // that here, so it will not hide previous -- and more relevant -- errors.
12958   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12959     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12960       Diag(MemE->getMemberLoc(),
12961            diag::err_ovl_no_viable_member_function_in_call)
12962           << Method << Method->getSourceRange();
12963       Diag(Method->getLocation(),
12964            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12965           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12966       return ExprError();
12967     }
12968   }
12969 
12970   if ((isa<CXXConstructorDecl>(CurContext) ||
12971        isa<CXXDestructorDecl>(CurContext)) &&
12972       TheCall->getMethodDecl()->isPure()) {
12973     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12974 
12975     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12976         MemExpr->performsVirtualDispatch(getLangOpts())) {
12977       Diag(MemExpr->getLocStart(),
12978            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12979         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12980         << MD->getParent()->getDeclName();
12981 
12982       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12983       if (getLangOpts().AppleKext)
12984         Diag(MemExpr->getLocStart(),
12985              diag::note_pure_qualified_call_kext)
12986              << MD->getParent()->getDeclName()
12987              << MD->getDeclName();
12988     }
12989   }
12990 
12991   if (CXXDestructorDecl *DD =
12992           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12993     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12994     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12995     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12996                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12997                          MemExpr->getMemberLoc());
12998   }
12999 
13000   return MaybeBindToTemporary(TheCall);
13001 }
13002 
13003 /// BuildCallToObjectOfClassType - Build a call to an object of class
13004 /// type (C++ [over.call.object]), which can end up invoking an
13005 /// overloaded function call operator (@c operator()) or performing a
13006 /// user-defined conversion on the object argument.
13007 ExprResult
13008 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13009                                    SourceLocation LParenLoc,
13010                                    MultiExprArg Args,
13011                                    SourceLocation RParenLoc) {
13012   if (checkPlaceholderForOverload(*this, Obj))
13013     return ExprError();
13014   ExprResult Object = Obj;
13015 
13016   UnbridgedCastsSet UnbridgedCasts;
13017   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13018     return ExprError();
13019 
13020   assert(Object.get()->getType()->isRecordType() &&
13021          "Requires object type argument");
13022   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13023 
13024   // C++ [over.call.object]p1:
13025   //  If the primary-expression E in the function call syntax
13026   //  evaluates to a class object of type "cv T", then the set of
13027   //  candidate functions includes at least the function call
13028   //  operators of T. The function call operators of T are obtained by
13029   //  ordinary lookup of the name operator() in the context of
13030   //  (E).operator().
13031   OverloadCandidateSet CandidateSet(LParenLoc,
13032                                     OverloadCandidateSet::CSK_Operator);
13033   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13034 
13035   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13036                           diag::err_incomplete_object_call, Object.get()))
13037     return true;
13038 
13039   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13040   LookupQualifiedName(R, Record->getDecl());
13041   R.suppressDiagnostics();
13042 
13043   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13044        Oper != OperEnd; ++Oper) {
13045     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13046                        Object.get()->Classify(Context), Args, CandidateSet,
13047                        /*SuppressUserConversions=*/false);
13048   }
13049 
13050   // C++ [over.call.object]p2:
13051   //   In addition, for each (non-explicit in C++0x) conversion function
13052   //   declared in T of the form
13053   //
13054   //        operator conversion-type-id () cv-qualifier;
13055   //
13056   //   where cv-qualifier is the same cv-qualification as, or a
13057   //   greater cv-qualification than, cv, and where conversion-type-id
13058   //   denotes the type "pointer to function of (P1,...,Pn) returning
13059   //   R", or the type "reference to pointer to function of
13060   //   (P1,...,Pn) returning R", or the type "reference to function
13061   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13062   //   is also considered as a candidate function. Similarly,
13063   //   surrogate call functions are added to the set of candidate
13064   //   functions for each conversion function declared in an
13065   //   accessible base class provided the function is not hidden
13066   //   within T by another intervening declaration.
13067   const auto &Conversions =
13068       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13069   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13070     NamedDecl *D = *I;
13071     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13072     if (isa<UsingShadowDecl>(D))
13073       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13074 
13075     // Skip over templated conversion functions; they aren't
13076     // surrogates.
13077     if (isa<FunctionTemplateDecl>(D))
13078       continue;
13079 
13080     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13081     if (!Conv->isExplicit()) {
13082       // Strip the reference type (if any) and then the pointer type (if
13083       // any) to get down to what might be a function type.
13084       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13085       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13086         ConvType = ConvPtrType->getPointeeType();
13087 
13088       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13089       {
13090         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13091                               Object.get(), Args, CandidateSet);
13092       }
13093     }
13094   }
13095 
13096   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13097 
13098   // Perform overload resolution.
13099   OverloadCandidateSet::iterator Best;
13100   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13101                                           Best)) {
13102   case OR_Success:
13103     // Overload resolution succeeded; we'll build the appropriate call
13104     // below.
13105     break;
13106 
13107   case OR_No_Viable_Function:
13108     if (CandidateSet.empty())
13109       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13110         << Object.get()->getType() << /*call*/ 1
13111         << Object.get()->getSourceRange();
13112     else
13113       Diag(Object.get()->getLocStart(),
13114            diag::err_ovl_no_viable_object_call)
13115         << Object.get()->getType() << Object.get()->getSourceRange();
13116     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13117     break;
13118 
13119   case OR_Ambiguous:
13120     Diag(Object.get()->getLocStart(),
13121          diag::err_ovl_ambiguous_object_call)
13122       << Object.get()->getType() << Object.get()->getSourceRange();
13123     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13124     break;
13125 
13126   case OR_Deleted:
13127     Diag(Object.get()->getLocStart(),
13128          diag::err_ovl_deleted_object_call)
13129       << Best->Function->isDeleted()
13130       << Object.get()->getType()
13131       << getDeletedOrUnavailableSuffix(Best->Function)
13132       << Object.get()->getSourceRange();
13133     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13134     break;
13135   }
13136 
13137   if (Best == CandidateSet.end())
13138     return true;
13139 
13140   UnbridgedCasts.restore();
13141 
13142   if (Best->Function == nullptr) {
13143     // Since there is no function declaration, this is one of the
13144     // surrogate candidates. Dig out the conversion function.
13145     CXXConversionDecl *Conv
13146       = cast<CXXConversionDecl>(
13147                          Best->Conversions[0].UserDefined.ConversionFunction);
13148 
13149     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13150                               Best->FoundDecl);
13151     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13152       return ExprError();
13153     assert(Conv == Best->FoundDecl.getDecl() &&
13154              "Found Decl & conversion-to-functionptr should be same, right?!");
13155     // We selected one of the surrogate functions that converts the
13156     // object parameter to a function pointer. Perform the conversion
13157     // on the object argument, then let ActOnCallExpr finish the job.
13158 
13159     // Create an implicit member expr to refer to the conversion operator.
13160     // and then call it.
13161     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13162                                              Conv, HadMultipleCandidates);
13163     if (Call.isInvalid())
13164       return ExprError();
13165     // Record usage of conversion in an implicit cast.
13166     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13167                                     CK_UserDefinedConversion, Call.get(),
13168                                     nullptr, VK_RValue);
13169 
13170     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13171   }
13172 
13173   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13174 
13175   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13176   // that calls this method, using Object for the implicit object
13177   // parameter and passing along the remaining arguments.
13178   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13179 
13180   // An error diagnostic has already been printed when parsing the declaration.
13181   if (Method->isInvalidDecl())
13182     return ExprError();
13183 
13184   const FunctionProtoType *Proto =
13185     Method->getType()->getAs<FunctionProtoType>();
13186 
13187   unsigned NumParams = Proto->getNumParams();
13188 
13189   DeclarationNameInfo OpLocInfo(
13190                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13191   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13192   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13193                                            Obj, HadMultipleCandidates,
13194                                            OpLocInfo.getLoc(),
13195                                            OpLocInfo.getInfo());
13196   if (NewFn.isInvalid())
13197     return true;
13198 
13199   // Build the full argument list for the method call (the implicit object
13200   // parameter is placed at the beginning of the list).
13201   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13202   MethodArgs[0] = Object.get();
13203   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13204 
13205   // Once we've built TheCall, all of the expressions are properly
13206   // owned.
13207   QualType ResultTy = Method->getReturnType();
13208   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13209   ResultTy = ResultTy.getNonLValueExprType(Context);
13210 
13211   CXXOperatorCallExpr *TheCall = new (Context)
13212       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13213                           VK, RParenLoc, FPOptions());
13214 
13215   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13216     return true;
13217 
13218   // We may have default arguments. If so, we need to allocate more
13219   // slots in the call for them.
13220   if (Args.size() < NumParams)
13221     TheCall->setNumArgs(Context, NumParams + 1);
13222 
13223   bool IsError = false;
13224 
13225   // Initialize the implicit object parameter.
13226   ExprResult ObjRes =
13227     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13228                                         Best->FoundDecl, Method);
13229   if (ObjRes.isInvalid())
13230     IsError = true;
13231   else
13232     Object = ObjRes;
13233   TheCall->setArg(0, Object.get());
13234 
13235   // Check the argument types.
13236   for (unsigned i = 0; i != NumParams; i++) {
13237     Expr *Arg;
13238     if (i < Args.size()) {
13239       Arg = Args[i];
13240 
13241       // Pass the argument.
13242 
13243       ExprResult InputInit
13244         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13245                                                     Context,
13246                                                     Method->getParamDecl(i)),
13247                                     SourceLocation(), Arg);
13248 
13249       IsError |= InputInit.isInvalid();
13250       Arg = InputInit.getAs<Expr>();
13251     } else {
13252       ExprResult DefArg
13253         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13254       if (DefArg.isInvalid()) {
13255         IsError = true;
13256         break;
13257       }
13258 
13259       Arg = DefArg.getAs<Expr>();
13260     }
13261 
13262     TheCall->setArg(i + 1, Arg);
13263   }
13264 
13265   // If this is a variadic call, handle args passed through "...".
13266   if (Proto->isVariadic()) {
13267     // Promote the arguments (C99 6.5.2.2p7).
13268     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13269       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13270                                                         nullptr);
13271       IsError |= Arg.isInvalid();
13272       TheCall->setArg(i + 1, Arg.get());
13273     }
13274   }
13275 
13276   if (IsError) return true;
13277 
13278   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13279 
13280   if (CheckFunctionCall(Method, TheCall, Proto))
13281     return true;
13282 
13283   return MaybeBindToTemporary(TheCall);
13284 }
13285 
13286 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13287 ///  (if one exists), where @c Base is an expression of class type and
13288 /// @c Member is the name of the member we're trying to find.
13289 ExprResult
13290 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13291                                bool *NoArrowOperatorFound) {
13292   assert(Base->getType()->isRecordType() &&
13293          "left-hand side must have class type");
13294 
13295   if (checkPlaceholderForOverload(*this, Base))
13296     return ExprError();
13297 
13298   SourceLocation Loc = Base->getExprLoc();
13299 
13300   // C++ [over.ref]p1:
13301   //
13302   //   [...] An expression x->m is interpreted as (x.operator->())->m
13303   //   for a class object x of type T if T::operator->() exists and if
13304   //   the operator is selected as the best match function by the
13305   //   overload resolution mechanism (13.3).
13306   DeclarationName OpName =
13307     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13308   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13309   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13310 
13311   if (RequireCompleteType(Loc, Base->getType(),
13312                           diag::err_typecheck_incomplete_tag, Base))
13313     return ExprError();
13314 
13315   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13316   LookupQualifiedName(R, BaseRecord->getDecl());
13317   R.suppressDiagnostics();
13318 
13319   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13320        Oper != OperEnd; ++Oper) {
13321     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13322                        None, CandidateSet, /*SuppressUserConversions=*/false);
13323   }
13324 
13325   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13326 
13327   // Perform overload resolution.
13328   OverloadCandidateSet::iterator Best;
13329   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13330   case OR_Success:
13331     // Overload resolution succeeded; we'll build the call below.
13332     break;
13333 
13334   case OR_No_Viable_Function:
13335     if (CandidateSet.empty()) {
13336       QualType BaseType = Base->getType();
13337       if (NoArrowOperatorFound) {
13338         // Report this specific error to the caller instead of emitting a
13339         // diagnostic, as requested.
13340         *NoArrowOperatorFound = true;
13341         return ExprError();
13342       }
13343       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13344         << BaseType << Base->getSourceRange();
13345       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13346         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13347           << FixItHint::CreateReplacement(OpLoc, ".");
13348       }
13349     } else
13350       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13351         << "operator->" << Base->getSourceRange();
13352     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13353     return ExprError();
13354 
13355   case OR_Ambiguous:
13356     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13357       << "->" << Base->getType() << Base->getSourceRange();
13358     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13359     return ExprError();
13360 
13361   case OR_Deleted:
13362     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13363       << Best->Function->isDeleted()
13364       << "->"
13365       << getDeletedOrUnavailableSuffix(Best->Function)
13366       << Base->getSourceRange();
13367     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13368     return ExprError();
13369   }
13370 
13371   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13372 
13373   // Convert the object parameter.
13374   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13375   ExprResult BaseResult =
13376     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13377                                         Best->FoundDecl, Method);
13378   if (BaseResult.isInvalid())
13379     return ExprError();
13380   Base = BaseResult.get();
13381 
13382   // Build the operator call.
13383   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13384                                             Base, HadMultipleCandidates, OpLoc);
13385   if (FnExpr.isInvalid())
13386     return ExprError();
13387 
13388   QualType ResultTy = Method->getReturnType();
13389   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13390   ResultTy = ResultTy.getNonLValueExprType(Context);
13391   CXXOperatorCallExpr *TheCall =
13392     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13393                                       Base, ResultTy, VK, OpLoc, FPOptions());
13394 
13395   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13396     return ExprError();
13397 
13398   if (CheckFunctionCall(Method, TheCall,
13399                         Method->getType()->castAs<FunctionProtoType>()))
13400     return ExprError();
13401 
13402   return MaybeBindToTemporary(TheCall);
13403 }
13404 
13405 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13406 /// a literal operator described by the provided lookup results.
13407 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13408                                           DeclarationNameInfo &SuffixInfo,
13409                                           ArrayRef<Expr*> Args,
13410                                           SourceLocation LitEndLoc,
13411                                        TemplateArgumentListInfo *TemplateArgs) {
13412   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13413 
13414   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13415                                     OverloadCandidateSet::CSK_Normal);
13416   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13417                         /*SuppressUserConversions=*/true);
13418 
13419   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13420 
13421   // Perform overload resolution. This will usually be trivial, but might need
13422   // to perform substitutions for a literal operator template.
13423   OverloadCandidateSet::iterator Best;
13424   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13425   case OR_Success:
13426   case OR_Deleted:
13427     break;
13428 
13429   case OR_No_Viable_Function:
13430     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13431       << R.getLookupName();
13432     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13433     return ExprError();
13434 
13435   case OR_Ambiguous:
13436     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13437     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13438     return ExprError();
13439   }
13440 
13441   FunctionDecl *FD = Best->Function;
13442   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13443                                         nullptr, HadMultipleCandidates,
13444                                         SuffixInfo.getLoc(),
13445                                         SuffixInfo.getInfo());
13446   if (Fn.isInvalid())
13447     return true;
13448 
13449   // Check the argument types. This should almost always be a no-op, except
13450   // that array-to-pointer decay is applied to string literals.
13451   Expr *ConvArgs[2];
13452   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13453     ExprResult InputInit = PerformCopyInitialization(
13454       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13455       SourceLocation(), Args[ArgIdx]);
13456     if (InputInit.isInvalid())
13457       return true;
13458     ConvArgs[ArgIdx] = InputInit.get();
13459   }
13460 
13461   QualType ResultTy = FD->getReturnType();
13462   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13463   ResultTy = ResultTy.getNonLValueExprType(Context);
13464 
13465   UserDefinedLiteral *UDL =
13466     new (Context) UserDefinedLiteral(Context, Fn.get(),
13467                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13468                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13469 
13470   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13471     return ExprError();
13472 
13473   if (CheckFunctionCall(FD, UDL, nullptr))
13474     return ExprError();
13475 
13476   return MaybeBindToTemporary(UDL);
13477 }
13478 
13479 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13480 /// given LookupResult is non-empty, it is assumed to describe a member which
13481 /// will be invoked. Otherwise, the function will be found via argument
13482 /// dependent lookup.
13483 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13484 /// otherwise CallExpr is set to ExprError() and some non-success value
13485 /// is returned.
13486 Sema::ForRangeStatus
13487 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13488                                 SourceLocation RangeLoc,
13489                                 const DeclarationNameInfo &NameInfo,
13490                                 LookupResult &MemberLookup,
13491                                 OverloadCandidateSet *CandidateSet,
13492                                 Expr *Range, ExprResult *CallExpr) {
13493   Scope *S = nullptr;
13494 
13495   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13496   if (!MemberLookup.empty()) {
13497     ExprResult MemberRef =
13498         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13499                                  /*IsPtr=*/false, CXXScopeSpec(),
13500                                  /*TemplateKWLoc=*/SourceLocation(),
13501                                  /*FirstQualifierInScope=*/nullptr,
13502                                  MemberLookup,
13503                                  /*TemplateArgs=*/nullptr, S);
13504     if (MemberRef.isInvalid()) {
13505       *CallExpr = ExprError();
13506       return FRS_DiagnosticIssued;
13507     }
13508     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13509     if (CallExpr->isInvalid()) {
13510       *CallExpr = ExprError();
13511       return FRS_DiagnosticIssued;
13512     }
13513   } else {
13514     UnresolvedSet<0> FoundNames;
13515     UnresolvedLookupExpr *Fn =
13516       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13517                                    NestedNameSpecifierLoc(), NameInfo,
13518                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13519                                    FoundNames.begin(), FoundNames.end());
13520 
13521     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13522                                                     CandidateSet, CallExpr);
13523     if (CandidateSet->empty() || CandidateSetError) {
13524       *CallExpr = ExprError();
13525       return FRS_NoViableFunction;
13526     }
13527     OverloadCandidateSet::iterator Best;
13528     OverloadingResult OverloadResult =
13529         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13530 
13531     if (OverloadResult == OR_No_Viable_Function) {
13532       *CallExpr = ExprError();
13533       return FRS_NoViableFunction;
13534     }
13535     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13536                                          Loc, nullptr, CandidateSet, &Best,
13537                                          OverloadResult,
13538                                          /*AllowTypoCorrection=*/false);
13539     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13540       *CallExpr = ExprError();
13541       return FRS_DiagnosticIssued;
13542     }
13543   }
13544   return FRS_Success;
13545 }
13546 
13547 
13548 /// FixOverloadedFunctionReference - E is an expression that refers to
13549 /// a C++ overloaded function (possibly with some parentheses and
13550 /// perhaps a '&' around it). We have resolved the overloaded function
13551 /// to the function declaration Fn, so patch up the expression E to
13552 /// refer (possibly indirectly) to Fn. Returns the new expr.
13553 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13554                                            FunctionDecl *Fn) {
13555   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13556     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13557                                                    Found, Fn);
13558     if (SubExpr == PE->getSubExpr())
13559       return PE;
13560 
13561     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13562   }
13563 
13564   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13565     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13566                                                    Found, Fn);
13567     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13568                                SubExpr->getType()) &&
13569            "Implicit cast type cannot be determined from overload");
13570     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13571     if (SubExpr == ICE->getSubExpr())
13572       return ICE;
13573 
13574     return ImplicitCastExpr::Create(Context, ICE->getType(),
13575                                     ICE->getCastKind(),
13576                                     SubExpr, nullptr,
13577                                     ICE->getValueKind());
13578   }
13579 
13580   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13581     if (!GSE->isResultDependent()) {
13582       Expr *SubExpr =
13583           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13584       if (SubExpr == GSE->getResultExpr())
13585         return GSE;
13586 
13587       // Replace the resulting type information before rebuilding the generic
13588       // selection expression.
13589       ArrayRef<Expr *> A = GSE->getAssocExprs();
13590       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13591       unsigned ResultIdx = GSE->getResultIndex();
13592       AssocExprs[ResultIdx] = SubExpr;
13593 
13594       return new (Context) GenericSelectionExpr(
13595           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13596           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13597           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13598           ResultIdx);
13599     }
13600     // Rather than fall through to the unreachable, return the original generic
13601     // selection expression.
13602     return GSE;
13603   }
13604 
13605   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13606     assert(UnOp->getOpcode() == UO_AddrOf &&
13607            "Can only take the address of an overloaded function");
13608     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13609       if (Method->isStatic()) {
13610         // Do nothing: static member functions aren't any different
13611         // from non-member functions.
13612       } else {
13613         // Fix the subexpression, which really has to be an
13614         // UnresolvedLookupExpr holding an overloaded member function
13615         // or template.
13616         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13617                                                        Found, Fn);
13618         if (SubExpr == UnOp->getSubExpr())
13619           return UnOp;
13620 
13621         assert(isa<DeclRefExpr>(SubExpr)
13622                && "fixed to something other than a decl ref");
13623         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13624                && "fixed to a member ref with no nested name qualifier");
13625 
13626         // We have taken the address of a pointer to member
13627         // function. Perform the computation here so that we get the
13628         // appropriate pointer to member type.
13629         QualType ClassType
13630           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13631         QualType MemPtrType
13632           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13633         // Under the MS ABI, lock down the inheritance model now.
13634         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13635           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13636 
13637         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13638                                            VK_RValue, OK_Ordinary,
13639                                            UnOp->getOperatorLoc(), false);
13640       }
13641     }
13642     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13643                                                    Found, Fn);
13644     if (SubExpr == UnOp->getSubExpr())
13645       return UnOp;
13646 
13647     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13648                                      Context.getPointerType(SubExpr->getType()),
13649                                        VK_RValue, OK_Ordinary,
13650                                        UnOp->getOperatorLoc(), false);
13651   }
13652 
13653   // C++ [except.spec]p17:
13654   //   An exception-specification is considered to be needed when:
13655   //   - in an expression the function is the unique lookup result or the
13656   //     selected member of a set of overloaded functions
13657   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13658     ResolveExceptionSpec(E->getExprLoc(), FPT);
13659 
13660   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13661     // FIXME: avoid copy.
13662     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13663     if (ULE->hasExplicitTemplateArgs()) {
13664       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13665       TemplateArgs = &TemplateArgsBuffer;
13666     }
13667 
13668     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13669                                            ULE->getQualifierLoc(),
13670                                            ULE->getTemplateKeywordLoc(),
13671                                            Fn,
13672                                            /*enclosing*/ false, // FIXME?
13673                                            ULE->getNameLoc(),
13674                                            Fn->getType(),
13675                                            VK_LValue,
13676                                            Found.getDecl(),
13677                                            TemplateArgs);
13678     MarkDeclRefReferenced(DRE);
13679     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13680     return DRE;
13681   }
13682 
13683   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13684     // FIXME: avoid copy.
13685     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13686     if (MemExpr->hasExplicitTemplateArgs()) {
13687       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13688       TemplateArgs = &TemplateArgsBuffer;
13689     }
13690 
13691     Expr *Base;
13692 
13693     // If we're filling in a static method where we used to have an
13694     // implicit member access, rewrite to a simple decl ref.
13695     if (MemExpr->isImplicitAccess()) {
13696       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13697         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13698                                                MemExpr->getQualifierLoc(),
13699                                                MemExpr->getTemplateKeywordLoc(),
13700                                                Fn,
13701                                                /*enclosing*/ false,
13702                                                MemExpr->getMemberLoc(),
13703                                                Fn->getType(),
13704                                                VK_LValue,
13705                                                Found.getDecl(),
13706                                                TemplateArgs);
13707         MarkDeclRefReferenced(DRE);
13708         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13709         return DRE;
13710       } else {
13711         SourceLocation Loc = MemExpr->getMemberLoc();
13712         if (MemExpr->getQualifier())
13713           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13714         CheckCXXThisCapture(Loc);
13715         Base = new (Context) CXXThisExpr(Loc,
13716                                          MemExpr->getBaseType(),
13717                                          /*isImplicit=*/true);
13718       }
13719     } else
13720       Base = MemExpr->getBase();
13721 
13722     ExprValueKind valueKind;
13723     QualType type;
13724     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13725       valueKind = VK_LValue;
13726       type = Fn->getType();
13727     } else {
13728       valueKind = VK_RValue;
13729       type = Context.BoundMemberTy;
13730     }
13731 
13732     MemberExpr *ME = MemberExpr::Create(
13733         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13734         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13735         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13736         OK_Ordinary);
13737     ME->setHadMultipleCandidates(true);
13738     MarkMemberReferenced(ME);
13739     return ME;
13740   }
13741 
13742   llvm_unreachable("Invalid reference to overloaded function");
13743 }
13744 
13745 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13746                                                 DeclAccessPair Found,
13747                                                 FunctionDecl *Fn) {
13748   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13749 }
13750