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_IncompletePack:
633     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634   case Sema::TDK_Inconsistent:
635   case Sema::TDK_Underqualified: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638     Saved->Param = Info.Param;
639     Saved->FirstArg = Info.FirstArg;
640     Saved->SecondArg = Info.SecondArg;
641     Result.Data = Saved;
642     break;
643   }
644 
645   case Sema::TDK_SubstitutionFailure:
646     Result.Data = Info.take();
647     if (Info.hasSFINAEDiagnostic()) {
648       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649           SourceLocation(), PartialDiagnostic::NullDiagnostic());
650       Info.takeSFINAEDiagnostic(*Diag);
651       Result.HasDiagnostic = true;
652     }
653     break;
654 
655   case Sema::TDK_Success:
656   case Sema::TDK_NonDependentConversionFailure:
657     llvm_unreachable("not a deduction failure");
658   }
659 
660   return Result;
661 }
662 
663 void DeductionFailureInfo::Destroy() {
664   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665   case Sema::TDK_Success:
666   case Sema::TDK_Invalid:
667   case Sema::TDK_InstantiationDepth:
668   case Sema::TDK_Incomplete:
669   case Sema::TDK_TooManyArguments:
670   case Sema::TDK_TooFewArguments:
671   case Sema::TDK_InvalidExplicitArguments:
672   case Sema::TDK_CUDATargetMismatch:
673   case Sema::TDK_NonDependentConversionFailure:
674     break;
675 
676   case Sema::TDK_IncompletePack:
677   case Sema::TDK_Inconsistent:
678   case Sema::TDK_Underqualified:
679   case Sema::TDK_DeducedMismatch:
680   case Sema::TDK_DeducedMismatchNested:
681   case Sema::TDK_NonDeducedMismatch:
682     // FIXME: Destroy the data?
683     Data = nullptr;
684     break;
685 
686   case Sema::TDK_SubstitutionFailure:
687     // FIXME: Destroy the template argument list?
688     Data = nullptr;
689     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690       Diag->~PartialDiagnosticAt();
691       HasDiagnostic = false;
692     }
693     break;
694 
695   // Unhandled
696   case Sema::TDK_MiscellaneousDeductionFailure:
697     break;
698   }
699 }
700 
701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702   if (HasDiagnostic)
703     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704   return nullptr;
705 }
706 
707 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709   case Sema::TDK_Success:
710   case Sema::TDK_Invalid:
711   case Sema::TDK_InstantiationDepth:
712   case Sema::TDK_TooManyArguments:
713   case Sema::TDK_TooFewArguments:
714   case Sema::TDK_SubstitutionFailure:
715   case Sema::TDK_DeducedMismatch:
716   case Sema::TDK_DeducedMismatchNested:
717   case Sema::TDK_NonDeducedMismatch:
718   case Sema::TDK_CUDATargetMismatch:
719   case Sema::TDK_NonDependentConversionFailure:
720     return TemplateParameter();
721 
722   case Sema::TDK_Incomplete:
723   case Sema::TDK_InvalidExplicitArguments:
724     return TemplateParameter::getFromOpaqueValue(Data);
725 
726   case Sema::TDK_IncompletePack:
727   case Sema::TDK_Inconsistent:
728   case Sema::TDK_Underqualified:
729     return static_cast<DFIParamWithArguments*>(Data)->Param;
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 
736   return TemplateParameter();
737 }
738 
739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741   case Sema::TDK_Success:
742   case Sema::TDK_Invalid:
743   case Sema::TDK_InstantiationDepth:
744   case Sema::TDK_TooManyArguments:
745   case Sema::TDK_TooFewArguments:
746   case Sema::TDK_Incomplete:
747   case Sema::TDK_IncompletePack:
748   case Sema::TDK_InvalidExplicitArguments:
749   case Sema::TDK_Inconsistent:
750   case Sema::TDK_Underqualified:
751   case Sema::TDK_NonDeducedMismatch:
752   case Sema::TDK_CUDATargetMismatch:
753   case Sema::TDK_NonDependentConversionFailure:
754     return nullptr;
755 
756   case Sema::TDK_DeducedMismatch:
757   case Sema::TDK_DeducedMismatchNested:
758     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759 
760   case Sema::TDK_SubstitutionFailure:
761     return static_cast<TemplateArgumentList*>(Data);
762 
763   // Unhandled
764   case Sema::TDK_MiscellaneousDeductionFailure:
765     break;
766   }
767 
768   return nullptr;
769 }
770 
771 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773   case Sema::TDK_Success:
774   case Sema::TDK_Invalid:
775   case Sema::TDK_InstantiationDepth:
776   case Sema::TDK_Incomplete:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_InvalidExplicitArguments:
780   case Sema::TDK_SubstitutionFailure:
781   case Sema::TDK_CUDATargetMismatch:
782   case Sema::TDK_NonDependentConversionFailure:
783     return nullptr;
784 
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_DeducedMismatch:
789   case Sema::TDK_DeducedMismatchNested:
790   case Sema::TDK_NonDeducedMismatch:
791     return &static_cast<DFIArguments*>(Data)->FirstArg;
792 
793   // Unhandled
794   case Sema::TDK_MiscellaneousDeductionFailure:
795     break;
796   }
797 
798   return nullptr;
799 }
800 
801 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803   case Sema::TDK_Success:
804   case Sema::TDK_Invalid:
805   case Sema::TDK_InstantiationDepth:
806   case Sema::TDK_Incomplete:
807   case Sema::TDK_IncompletePack:
808   case Sema::TDK_TooManyArguments:
809   case Sema::TDK_TooFewArguments:
810   case Sema::TDK_InvalidExplicitArguments:
811   case Sema::TDK_SubstitutionFailure:
812   case Sema::TDK_CUDATargetMismatch:
813   case Sema::TDK_NonDependentConversionFailure:
814     return nullptr;
815 
816   case Sema::TDK_Inconsistent:
817   case Sema::TDK_Underqualified:
818   case Sema::TDK_DeducedMismatch:
819   case Sema::TDK_DeducedMismatchNested:
820   case Sema::TDK_NonDeducedMismatch:
821     return &static_cast<DFIArguments*>(Data)->SecondArg;
822 
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825     break;
826   }
827 
828   return nullptr;
829 }
830 
831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836 
837   default:
838     return llvm::None;
839   }
840 }
841 
842 void OverloadCandidateSet::destroyCandidates() {
843   for (iterator i = begin(), e = end(); i != e; ++i) {
844     for (auto &C : i->Conversions)
845       C.~ImplicitConversionSequence();
846     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847       i->DeductionFailure.Destroy();
848   }
849 }
850 
851 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852   destroyCandidates();
853   SlabAllocator.Reset();
854   NumInlineBytesUsed = 0;
855   Candidates.clear();
856   Functions.clear();
857   Kind = CSK;
858 }
859 
860 namespace {
861   class UnbridgedCastsSet {
862     struct Entry {
863       Expr **Addr;
864       Expr *Saved;
865     };
866     SmallVector<Entry, 2> Entries;
867 
868   public:
869     void save(Sema &S, Expr *&E) {
870       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871       Entry entry = { &E, E };
872       Entries.push_back(entry);
873       E = S.stripARCUnbridgedCast(E);
874     }
875 
876     void restore() {
877       for (SmallVectorImpl<Entry>::iterator
878              i = Entries.begin(), e = Entries.end(); i != e; ++i)
879         *i->Addr = i->Saved;
880     }
881   };
882 }
883 
884 /// checkPlaceholderForOverload - Do any interesting placeholder-like
885 /// preprocessing on the given expression.
886 ///
887 /// \param unbridgedCasts a collection to which to add unbridged casts;
888 ///   without this, they will be immediately diagnosed as errors
889 ///
890 /// Return true on unrecoverable error.
891 static bool
892 checkPlaceholderForOverload(Sema &S, Expr *&E,
893                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
894   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
895     // We can't handle overloaded expressions here because overload
896     // resolution might reasonably tweak them.
897     if (placeholder->getKind() == BuiltinType::Overload) return false;
898 
899     // If the context potentially accepts unbridged ARC casts, strip
900     // the unbridged cast and add it to the collection for later restoration.
901     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902         unbridgedCasts) {
903       unbridgedCasts->save(S, E);
904       return false;
905     }
906 
907     // Go ahead and check everything else.
908     ExprResult result = S.CheckPlaceholderExpr(E);
909     if (result.isInvalid())
910       return true;
911 
912     E = result.get();
913     return false;
914   }
915 
916   // Nothing to do.
917   return false;
918 }
919 
920 /// checkArgPlaceholdersForOverload - Check a set of call operands for
921 /// placeholders.
922 static bool checkArgPlaceholdersForOverload(Sema &S,
923                                             MultiExprArg Args,
924                                             UnbridgedCastsSet &unbridged) {
925   for (unsigned i = 0, e = Args.size(); i != e; ++i)
926     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927       return true;
928 
929   return false;
930 }
931 
932 /// Determine whether the given New declaration is an overload of the
933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934 /// New and Old cannot be overloaded, e.g., if New has the same signature as
935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936 /// functions (or function templates) at all. When it does return Ovl_Match or
937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939 /// declaration.
940 ///
941 /// Example: Given the following input:
942 ///
943 ///   void f(int, float); // #1
944 ///   void f(int, int); // #2
945 ///   int f(int, int); // #3
946 ///
947 /// When we process #1, there is no previous declaration of "f", so IsOverload
948 /// will not be used.
949 ///
950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951 /// the parameter types, we see that #1 and #2 are overloaded (since they have
952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953 /// unchanged.
954 ///
955 /// When we process #3, Old is an overload set containing #1 and #2. We compare
956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958 /// functions are not part of the signature), IsOverload returns Ovl_Match and
959 /// MatchedDecl will be set to point to the FunctionDecl for #2.
960 ///
961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962 /// by a using declaration. The rules for whether to hide shadow declarations
963 /// ignore some properties which otherwise figure into a function template's
964 /// signature.
965 Sema::OverloadKind
966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967                     NamedDecl *&Match, bool NewIsUsingDecl) {
968   for (LookupResult::iterator I = Old.begin(), E = Old.end();
969          I != E; ++I) {
970     NamedDecl *OldD = *I;
971 
972     bool OldIsUsingDecl = false;
973     if (isa<UsingShadowDecl>(OldD)) {
974       OldIsUsingDecl = true;
975 
976       // We can always introduce two using declarations into the same
977       // context, even if they have identical signatures.
978       if (NewIsUsingDecl) continue;
979 
980       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981     }
982 
983     // A using-declaration does not conflict with another declaration
984     // if one of them is hidden.
985     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986       continue;
987 
988     // If either declaration was introduced by a using declaration,
989     // we'll need to use slightly different rules for matching.
990     // Essentially, these rules are the normal rules, except that
991     // function templates hide function templates with different
992     // return types or template parameter lists.
993     bool UseMemberUsingDeclRules =
994       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995       !New->getFriendObjectKind();
996 
997     if (FunctionDecl *OldF = OldD->getAsFunction()) {
998       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001           continue;
1002         }
1003 
1004         if (!isa<FunctionTemplateDecl>(OldD) &&
1005             !shouldLinkPossiblyHiddenDecl(*I, New))
1006           continue;
1007 
1008         Match = *I;
1009         return Ovl_Match;
1010       }
1011 
1012       // Builtins that have custom typechecking or have a reference should
1013       // not be overloadable or redeclarable.
1014       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019       // We can overload with these, which can show up when doing
1020       // redeclaration checks for UsingDecls.
1021       assert(Old.getLookupKind() == LookupUsingDeclName);
1022     } else if (isa<TagDecl>(OldD)) {
1023       // We can always overload with tags by hiding them.
1024     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025       // Optimistically assume that an unresolved using decl will
1026       // overload; if it doesn't, we'll have to diagnose during
1027       // template instantiation.
1028       //
1029       // Exception: if the scope is dependent and this is not a class
1030       // member, the using declaration can only introduce an enumerator.
1031       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032         Match = *I;
1033         return Ovl_NonFunction;
1034       }
1035     } else {
1036       // (C++ 13p1):
1037       //   Only function declarations can be overloaded; object and type
1038       //   declarations cannot be overloaded.
1039       Match = *I;
1040       return Ovl_NonFunction;
1041     }
1042   }
1043 
1044   return Ovl_Overload;
1045 }
1046 
1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049   // C++ [basic.start.main]p2: This function shall not be overloaded.
1050   if (New->isMain())
1051     return false;
1052 
1053   // MSVCRT user defined entry points cannot be overloaded.
1054   if (New->isMSVCRTEntryPoint())
1055     return false;
1056 
1057   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059 
1060   // C++ [temp.fct]p2:
1061   //   A function template can be overloaded with other function templates
1062   //   and with normal (non-template) functions.
1063   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064     return true;
1065 
1066   // Is the function New an overload of the function Old?
1067   QualType OldQType = Context.getCanonicalType(Old->getType());
1068   QualType NewQType = Context.getCanonicalType(New->getType());
1069 
1070   // Compare the signatures (C++ 1.3.10) of the two functions to
1071   // determine whether they are overloads. If we find any mismatch
1072   // in the signature, they are overloads.
1073 
1074   // If either of these functions is a K&R-style function (no
1075   // prototype), then we consider them to have matching signatures.
1076   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078     return false;
1079 
1080   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082 
1083   // The signature of a function includes the types of its
1084   // parameters (C++ 1.3.10), which includes the presence or absence
1085   // of the ellipsis; see C++ DR 357).
1086   if (OldQType != NewQType &&
1087       (OldType->getNumParams() != NewType->getNumParams() ||
1088        OldType->isVariadic() != NewType->isVariadic() ||
1089        !FunctionParamTypesAreEqual(OldType, NewType)))
1090     return true;
1091 
1092   // C++ [temp.over.link]p4:
1093   //   The signature of a function template consists of its function
1094   //   signature, its return type and its template parameter list. The names
1095   //   of the template parameters are significant only for establishing the
1096   //   relationship between the template parameters and the rest of the
1097   //   signature.
1098   //
1099   // We check the return type and template parameter lists for function
1100   // templates first; the remaining checks follow.
1101   //
1102   // However, we don't consider either of these when deciding whether
1103   // a member introduced by a shadow declaration is hidden.
1104   if (!UseMemberUsingDeclRules && NewTemplate &&
1105       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106                                        OldTemplate->getTemplateParameters(),
1107                                        false, TPL_TemplateMatch) ||
1108        OldType->getReturnType() != NewType->getReturnType()))
1109     return true;
1110 
1111   // If the function is a class member, its signature includes the
1112   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1113   //
1114   // As part of this, also check whether one of the member functions
1115   // is static, in which case they are not overloads (C++
1116   // 13.1p2). While not part of the definition of the signature,
1117   // this check is important to determine whether these functions
1118   // can be overloaded.
1119   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1120   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1121   if (OldMethod && NewMethod &&
1122       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1123     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1124       if (!UseMemberUsingDeclRules &&
1125           (OldMethod->getRefQualifier() == RQ_None ||
1126            NewMethod->getRefQualifier() == RQ_None)) {
1127         // C++0x [over.load]p2:
1128         //   - Member function declarations with the same name and the same
1129         //     parameter-type-list as well as member function template
1130         //     declarations with the same name, the same parameter-type-list, and
1131         //     the same template parameter lists cannot be overloaded if any of
1132         //     them, but not all, have a ref-qualifier (8.3.5).
1133         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1134           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1135         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1136       }
1137       return true;
1138     }
1139 
1140     // We may not have applied the implicit const for a constexpr member
1141     // function yet (because we haven't yet resolved whether this is a static
1142     // or non-static member function). Add it now, on the assumption that this
1143     // is a redeclaration of OldMethod.
1144     unsigned OldQuals = OldMethod->getTypeQualifiers();
1145     unsigned NewQuals = NewMethod->getTypeQualifiers();
1146     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1147         !isa<CXXConstructorDecl>(NewMethod))
1148       NewQuals |= Qualifiers::Const;
1149 
1150     // We do not allow overloading based off of '__restrict'.
1151     OldQuals &= ~Qualifiers::Restrict;
1152     NewQuals &= ~Qualifiers::Restrict;
1153     if (OldQuals != NewQuals)
1154       return true;
1155   }
1156 
1157   // Though pass_object_size is placed on parameters and takes an argument, we
1158   // consider it to be a function-level modifier for the sake of function
1159   // identity. Either the function has one or more parameters with
1160   // pass_object_size or it doesn't.
1161   if (functionHasPassObjectSizeParams(New) !=
1162       functionHasPassObjectSizeParams(Old))
1163     return true;
1164 
1165   // enable_if attributes are an order-sensitive part of the signature.
1166   for (specific_attr_iterator<EnableIfAttr>
1167          NewI = New->specific_attr_begin<EnableIfAttr>(),
1168          NewE = New->specific_attr_end<EnableIfAttr>(),
1169          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1170          OldE = Old->specific_attr_end<EnableIfAttr>();
1171        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1172     if (NewI == NewE || OldI == OldE)
1173       return true;
1174     llvm::FoldingSetNodeID NewID, OldID;
1175     NewI->getCond()->Profile(NewID, Context, true);
1176     OldI->getCond()->Profile(OldID, Context, true);
1177     if (NewID != OldID)
1178       return true;
1179   }
1180 
1181   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1182     // Don't allow overloading of destructors.  (In theory we could, but it
1183     // would be a giant change to clang.)
1184     if (isa<CXXDestructorDecl>(New))
1185       return false;
1186 
1187     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1188                        OldTarget = IdentifyCUDATarget(Old);
1189     if (NewTarget == CFT_InvalidTarget)
1190       return false;
1191 
1192     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1193 
1194     // Allow overloading of functions with same signature and different CUDA
1195     // target attributes.
1196     return NewTarget != OldTarget;
1197   }
1198 
1199   // The signatures match; this is not an overload.
1200   return false;
1201 }
1202 
1203 /// Checks availability of the function depending on the current
1204 /// function context. Inside an unavailable function, unavailability is ignored.
1205 ///
1206 /// \returns true if \arg FD is unavailable and current context is inside
1207 /// an available function, false otherwise.
1208 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1209   if (!FD->isUnavailable())
1210     return false;
1211 
1212   // Walk up the context of the caller.
1213   Decl *C = cast<Decl>(CurContext);
1214   do {
1215     if (C->isUnavailable())
1216       return false;
1217   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1218   return true;
1219 }
1220 
1221 /// Tries a user-defined conversion from From to ToType.
1222 ///
1223 /// Produces an implicit conversion sequence for when a standard conversion
1224 /// is not an option. See TryImplicitConversion for more information.
1225 static ImplicitConversionSequence
1226 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1227                          bool SuppressUserConversions,
1228                          bool AllowExplicit,
1229                          bool InOverloadResolution,
1230                          bool CStyle,
1231                          bool AllowObjCWritebackConversion,
1232                          bool AllowObjCConversionOnExplicit) {
1233   ImplicitConversionSequence ICS;
1234 
1235   if (SuppressUserConversions) {
1236     // We're not in the case above, so there is no conversion that
1237     // we can perform.
1238     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1239     return ICS;
1240   }
1241 
1242   // Attempt user-defined conversion.
1243   OverloadCandidateSet Conversions(From->getExprLoc(),
1244                                    OverloadCandidateSet::CSK_Normal);
1245   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1246                                   Conversions, AllowExplicit,
1247                                   AllowObjCConversionOnExplicit)) {
1248   case OR_Success:
1249   case OR_Deleted:
1250     ICS.setUserDefined();
1251     // C++ [over.ics.user]p4:
1252     //   A conversion of an expression of class type to the same class
1253     //   type is given Exact Match rank, and a conversion of an
1254     //   expression of class type to a base class of that type is
1255     //   given Conversion rank, in spite of the fact that a copy
1256     //   constructor (i.e., a user-defined conversion function) is
1257     //   called for those cases.
1258     if (CXXConstructorDecl *Constructor
1259           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1260       QualType FromCanon
1261         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1262       QualType ToCanon
1263         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1264       if (Constructor->isCopyConstructor() &&
1265           (FromCanon == ToCanon ||
1266            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1267         // Turn this into a "standard" conversion sequence, so that it
1268         // gets ranked with standard conversion sequences.
1269         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1270         ICS.setStandard();
1271         ICS.Standard.setAsIdentityConversion();
1272         ICS.Standard.setFromType(From->getType());
1273         ICS.Standard.setAllToTypes(ToType);
1274         ICS.Standard.CopyConstructor = Constructor;
1275         ICS.Standard.FoundCopyConstructor = Found;
1276         if (ToCanon != FromCanon)
1277           ICS.Standard.Second = ICK_Derived_To_Base;
1278       }
1279     }
1280     break;
1281 
1282   case OR_Ambiguous:
1283     ICS.setAmbiguous();
1284     ICS.Ambiguous.setFromType(From->getType());
1285     ICS.Ambiguous.setToType(ToType);
1286     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1287          Cand != Conversions.end(); ++Cand)
1288       if (Cand->Viable)
1289         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1290     break;
1291 
1292     // Fall through.
1293   case OR_No_Viable_Function:
1294     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1295     break;
1296   }
1297 
1298   return ICS;
1299 }
1300 
1301 /// TryImplicitConversion - Attempt to perform an implicit conversion
1302 /// from the given expression (Expr) to the given type (ToType). This
1303 /// function returns an implicit conversion sequence that can be used
1304 /// to perform the initialization. Given
1305 ///
1306 ///   void f(float f);
1307 ///   void g(int i) { f(i); }
1308 ///
1309 /// this routine would produce an implicit conversion sequence to
1310 /// describe the initialization of f from i, which will be a standard
1311 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1312 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1313 //
1314 /// Note that this routine only determines how the conversion can be
1315 /// performed; it does not actually perform the conversion. As such,
1316 /// it will not produce any diagnostics if no conversion is available,
1317 /// but will instead return an implicit conversion sequence of kind
1318 /// "BadConversion".
1319 ///
1320 /// If @p SuppressUserConversions, then user-defined conversions are
1321 /// not permitted.
1322 /// If @p AllowExplicit, then explicit user-defined conversions are
1323 /// permitted.
1324 ///
1325 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1326 /// writeback conversion, which allows __autoreleasing id* parameters to
1327 /// be initialized with __strong id* or __weak id* arguments.
1328 static ImplicitConversionSequence
1329 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1330                       bool SuppressUserConversions,
1331                       bool AllowExplicit,
1332                       bool InOverloadResolution,
1333                       bool CStyle,
1334                       bool AllowObjCWritebackConversion,
1335                       bool AllowObjCConversionOnExplicit) {
1336   ImplicitConversionSequence ICS;
1337   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1338                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1339     ICS.setStandard();
1340     return ICS;
1341   }
1342 
1343   if (!S.getLangOpts().CPlusPlus) {
1344     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1345     return ICS;
1346   }
1347 
1348   // C++ [over.ics.user]p4:
1349   //   A conversion of an expression of class type to the same class
1350   //   type is given Exact Match rank, and a conversion of an
1351   //   expression of class type to a base class of that type is
1352   //   given Conversion rank, in spite of the fact that a copy/move
1353   //   constructor (i.e., a user-defined conversion function) is
1354   //   called for those cases.
1355   QualType FromType = From->getType();
1356   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1357       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1358        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1359     ICS.setStandard();
1360     ICS.Standard.setAsIdentityConversion();
1361     ICS.Standard.setFromType(FromType);
1362     ICS.Standard.setAllToTypes(ToType);
1363 
1364     // We don't actually check at this point whether there is a valid
1365     // copy/move constructor, since overloading just assumes that it
1366     // exists. When we actually perform initialization, we'll find the
1367     // appropriate constructor to copy the returned object, if needed.
1368     ICS.Standard.CopyConstructor = nullptr;
1369 
1370     // Determine whether this is considered a derived-to-base conversion.
1371     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1372       ICS.Standard.Second = ICK_Derived_To_Base;
1373 
1374     return ICS;
1375   }
1376 
1377   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1378                                   AllowExplicit, InOverloadResolution, CStyle,
1379                                   AllowObjCWritebackConversion,
1380                                   AllowObjCConversionOnExplicit);
1381 }
1382 
1383 ImplicitConversionSequence
1384 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1385                             bool SuppressUserConversions,
1386                             bool AllowExplicit,
1387                             bool InOverloadResolution,
1388                             bool CStyle,
1389                             bool AllowObjCWritebackConversion) {
1390   return ::TryImplicitConversion(*this, From, ToType,
1391                                  SuppressUserConversions, AllowExplicit,
1392                                  InOverloadResolution, CStyle,
1393                                  AllowObjCWritebackConversion,
1394                                  /*AllowObjCConversionOnExplicit=*/false);
1395 }
1396 
1397 /// PerformImplicitConversion - Perform an implicit conversion of the
1398 /// expression From to the type ToType. Returns the
1399 /// converted expression. Flavor is the kind of conversion we're
1400 /// performing, used in the error message. If @p AllowExplicit,
1401 /// explicit user-defined conversions are permitted.
1402 ExprResult
1403 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1404                                 AssignmentAction Action, bool AllowExplicit) {
1405   ImplicitConversionSequence ICS;
1406   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1407 }
1408 
1409 ExprResult
1410 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1411                                 AssignmentAction Action, bool AllowExplicit,
1412                                 ImplicitConversionSequence& ICS) {
1413   if (checkPlaceholderForOverload(*this, From))
1414     return ExprError();
1415 
1416   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1417   bool AllowObjCWritebackConversion
1418     = getLangOpts().ObjCAutoRefCount &&
1419       (Action == AA_Passing || Action == AA_Sending);
1420   if (getLangOpts().ObjC1)
1421     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1422                                       ToType, From->getType(), From);
1423   ICS = ::TryImplicitConversion(*this, From, ToType,
1424                                 /*SuppressUserConversions=*/false,
1425                                 AllowExplicit,
1426                                 /*InOverloadResolution=*/false,
1427                                 /*CStyle=*/false,
1428                                 AllowObjCWritebackConversion,
1429                                 /*AllowObjCConversionOnExplicit=*/false);
1430   return PerformImplicitConversion(From, ToType, ICS, Action);
1431 }
1432 
1433 /// Determine whether the conversion from FromType to ToType is a valid
1434 /// conversion that strips "noexcept" or "noreturn" off the nested function
1435 /// type.
1436 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1437                                 QualType &ResultTy) {
1438   if (Context.hasSameUnqualifiedType(FromType, ToType))
1439     return false;
1440 
1441   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1442   //                    or F(t noexcept) -> F(t)
1443   // where F adds one of the following at most once:
1444   //   - a pointer
1445   //   - a member pointer
1446   //   - a block pointer
1447   // Changes here need matching changes in FindCompositePointerType.
1448   CanQualType CanTo = Context.getCanonicalType(ToType);
1449   CanQualType CanFrom = Context.getCanonicalType(FromType);
1450   Type::TypeClass TyClass = CanTo->getTypeClass();
1451   if (TyClass != CanFrom->getTypeClass()) return false;
1452   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1453     if (TyClass == Type::Pointer) {
1454       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1455       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1456     } else if (TyClass == Type::BlockPointer) {
1457       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1458       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1459     } else if (TyClass == Type::MemberPointer) {
1460       auto ToMPT = CanTo.getAs<MemberPointerType>();
1461       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1462       // A function pointer conversion cannot change the class of the function.
1463       if (ToMPT->getClass() != FromMPT->getClass())
1464         return false;
1465       CanTo = ToMPT->getPointeeType();
1466       CanFrom = FromMPT->getPointeeType();
1467     } else {
1468       return false;
1469     }
1470 
1471     TyClass = CanTo->getTypeClass();
1472     if (TyClass != CanFrom->getTypeClass()) return false;
1473     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1474       return false;
1475   }
1476 
1477   const auto *FromFn = cast<FunctionType>(CanFrom);
1478   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1479 
1480   const auto *ToFn = cast<FunctionType>(CanTo);
1481   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1482 
1483   bool Changed = false;
1484 
1485   // Drop 'noreturn' if not present in target type.
1486   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1487     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1488     Changed = true;
1489   }
1490 
1491   // Drop 'noexcept' if not present in target type.
1492   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1493     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1494     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1495       FromFn = cast<FunctionType>(
1496           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1497                                                    EST_None)
1498                  .getTypePtr());
1499       Changed = true;
1500     }
1501 
1502     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1503     // only if the ExtParameterInfo lists of the two function prototypes can be
1504     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1505     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1506     bool CanUseToFPT, CanUseFromFPT;
1507     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1508                                       CanUseFromFPT, NewParamInfos) &&
1509         CanUseToFPT && !CanUseFromFPT) {
1510       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1511       ExtInfo.ExtParameterInfos =
1512           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1513       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1514                                             FromFPT->getParamTypes(), ExtInfo);
1515       FromFn = QT->getAs<FunctionType>();
1516       Changed = true;
1517     }
1518   }
1519 
1520   if (!Changed)
1521     return false;
1522 
1523   assert(QualType(FromFn, 0).isCanonical());
1524   if (QualType(FromFn, 0) != CanTo) return false;
1525 
1526   ResultTy = ToType;
1527   return true;
1528 }
1529 
1530 /// Determine whether the conversion from FromType to ToType is a valid
1531 /// vector conversion.
1532 ///
1533 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1534 /// conversion.
1535 static bool IsVectorConversion(Sema &S, QualType FromType,
1536                                QualType ToType, ImplicitConversionKind &ICK) {
1537   // We need at least one of these types to be a vector type to have a vector
1538   // conversion.
1539   if (!ToType->isVectorType() && !FromType->isVectorType())
1540     return false;
1541 
1542   // Identical types require no conversions.
1543   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1544     return false;
1545 
1546   // There are no conversions between extended vector types, only identity.
1547   if (ToType->isExtVectorType()) {
1548     // There are no conversions between extended vector types other than the
1549     // identity conversion.
1550     if (FromType->isExtVectorType())
1551       return false;
1552 
1553     // Vector splat from any arithmetic type to a vector.
1554     if (FromType->isArithmeticType()) {
1555       ICK = ICK_Vector_Splat;
1556       return true;
1557     }
1558   }
1559 
1560   // We can perform the conversion between vector types in the following cases:
1561   // 1)vector types are equivalent AltiVec and GCC vector types
1562   // 2)lax vector conversions are permitted and the vector types are of the
1563   //   same size
1564   if (ToType->isVectorType() && FromType->isVectorType()) {
1565     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1566         S.isLaxVectorConversion(FromType, ToType)) {
1567       ICK = ICK_Vector_Conversion;
1568       return true;
1569     }
1570   }
1571 
1572   return false;
1573 }
1574 
1575 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1576                                 bool InOverloadResolution,
1577                                 StandardConversionSequence &SCS,
1578                                 bool CStyle);
1579 
1580 /// IsStandardConversion - Determines whether there is a standard
1581 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1582 /// expression From to the type ToType. Standard conversion sequences
1583 /// only consider non-class types; for conversions that involve class
1584 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1585 /// contain the standard conversion sequence required to perform this
1586 /// conversion and this routine will return true. Otherwise, this
1587 /// routine will return false and the value of SCS is unspecified.
1588 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1589                                  bool InOverloadResolution,
1590                                  StandardConversionSequence &SCS,
1591                                  bool CStyle,
1592                                  bool AllowObjCWritebackConversion) {
1593   QualType FromType = From->getType();
1594 
1595   // Standard conversions (C++ [conv])
1596   SCS.setAsIdentityConversion();
1597   SCS.IncompatibleObjC = false;
1598   SCS.setFromType(FromType);
1599   SCS.CopyConstructor = nullptr;
1600 
1601   // There are no standard conversions for class types in C++, so
1602   // abort early. When overloading in C, however, we do permit them.
1603   if (S.getLangOpts().CPlusPlus &&
1604       (FromType->isRecordType() || ToType->isRecordType()))
1605     return false;
1606 
1607   // The first conversion can be an lvalue-to-rvalue conversion,
1608   // array-to-pointer conversion, or function-to-pointer conversion
1609   // (C++ 4p1).
1610 
1611   if (FromType == S.Context.OverloadTy) {
1612     DeclAccessPair AccessPair;
1613     if (FunctionDecl *Fn
1614           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1615                                                  AccessPair)) {
1616       // We were able to resolve the address of the overloaded function,
1617       // so we can convert to the type of that function.
1618       FromType = Fn->getType();
1619       SCS.setFromType(FromType);
1620 
1621       // we can sometimes resolve &foo<int> regardless of ToType, so check
1622       // if the type matches (identity) or we are converting to bool
1623       if (!S.Context.hasSameUnqualifiedType(
1624                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1625         QualType resultTy;
1626         // if the function type matches except for [[noreturn]], it's ok
1627         if (!S.IsFunctionConversion(FromType,
1628               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1629           // otherwise, only a boolean conversion is standard
1630           if (!ToType->isBooleanType())
1631             return false;
1632       }
1633 
1634       // Check if the "from" expression is taking the address of an overloaded
1635       // function and recompute the FromType accordingly. Take advantage of the
1636       // fact that non-static member functions *must* have such an address-of
1637       // expression.
1638       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1639       if (Method && !Method->isStatic()) {
1640         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1641                "Non-unary operator on non-static member address");
1642         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1643                == UO_AddrOf &&
1644                "Non-address-of operator on non-static member address");
1645         const Type *ClassType
1646           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1647         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1648       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1649         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1650                UO_AddrOf &&
1651                "Non-address-of operator for overloaded function expression");
1652         FromType = S.Context.getPointerType(FromType);
1653       }
1654 
1655       // Check that we've computed the proper type after overload resolution.
1656       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1657       // be calling it from within an NDEBUG block.
1658       assert(S.Context.hasSameType(
1659         FromType,
1660         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1661     } else {
1662       return false;
1663     }
1664   }
1665   // Lvalue-to-rvalue conversion (C++11 4.1):
1666   //   A glvalue (3.10) of a non-function, non-array type T can
1667   //   be converted to a prvalue.
1668   bool argIsLValue = From->isGLValue();
1669   if (argIsLValue &&
1670       !FromType->isFunctionType() && !FromType->isArrayType() &&
1671       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1672     SCS.First = ICK_Lvalue_To_Rvalue;
1673 
1674     // C11 6.3.2.1p2:
1675     //   ... if the lvalue has atomic type, the value has the non-atomic version
1676     //   of the type of the lvalue ...
1677     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1678       FromType = Atomic->getValueType();
1679 
1680     // If T is a non-class type, the type of the rvalue is the
1681     // cv-unqualified version of T. Otherwise, the type of the rvalue
1682     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1683     // just strip the qualifiers because they don't matter.
1684     FromType = FromType.getUnqualifiedType();
1685   } else if (FromType->isArrayType()) {
1686     // Array-to-pointer conversion (C++ 4.2)
1687     SCS.First = ICK_Array_To_Pointer;
1688 
1689     // An lvalue or rvalue of type "array of N T" or "array of unknown
1690     // bound of T" can be converted to an rvalue of type "pointer to
1691     // T" (C++ 4.2p1).
1692     FromType = S.Context.getArrayDecayedType(FromType);
1693 
1694     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1695       // This conversion is deprecated in C++03 (D.4)
1696       SCS.DeprecatedStringLiteralToCharPtr = true;
1697 
1698       // For the purpose of ranking in overload resolution
1699       // (13.3.3.1.1), this conversion is considered an
1700       // array-to-pointer conversion followed by a qualification
1701       // conversion (4.4). (C++ 4.2p2)
1702       SCS.Second = ICK_Identity;
1703       SCS.Third = ICK_Qualification;
1704       SCS.QualificationIncludesObjCLifetime = false;
1705       SCS.setAllToTypes(FromType);
1706       return true;
1707     }
1708   } else if (FromType->isFunctionType() && argIsLValue) {
1709     // Function-to-pointer conversion (C++ 4.3).
1710     SCS.First = ICK_Function_To_Pointer;
1711 
1712     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1713       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1714         if (!S.checkAddressOfFunctionIsAvailable(FD))
1715           return false;
1716 
1717     // An lvalue of function type T can be converted to an rvalue of
1718     // type "pointer to T." The result is a pointer to the
1719     // function. (C++ 4.3p1).
1720     FromType = S.Context.getPointerType(FromType);
1721   } else {
1722     // We don't require any conversions for the first step.
1723     SCS.First = ICK_Identity;
1724   }
1725   SCS.setToType(0, FromType);
1726 
1727   // The second conversion can be an integral promotion, floating
1728   // point promotion, integral conversion, floating point conversion,
1729   // floating-integral conversion, pointer conversion,
1730   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1731   // For overloading in C, this can also be a "compatible-type"
1732   // conversion.
1733   bool IncompatibleObjC = false;
1734   ImplicitConversionKind SecondICK = ICK_Identity;
1735   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1736     // The unqualified versions of the types are the same: there's no
1737     // conversion to do.
1738     SCS.Second = ICK_Identity;
1739   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1740     // Integral promotion (C++ 4.5).
1741     SCS.Second = ICK_Integral_Promotion;
1742     FromType = ToType.getUnqualifiedType();
1743   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1744     // Floating point promotion (C++ 4.6).
1745     SCS.Second = ICK_Floating_Promotion;
1746     FromType = ToType.getUnqualifiedType();
1747   } else if (S.IsComplexPromotion(FromType, ToType)) {
1748     // Complex promotion (Clang extension)
1749     SCS.Second = ICK_Complex_Promotion;
1750     FromType = ToType.getUnqualifiedType();
1751   } else if (ToType->isBooleanType() &&
1752              (FromType->isArithmeticType() ||
1753               FromType->isAnyPointerType() ||
1754               FromType->isBlockPointerType() ||
1755               FromType->isMemberPointerType() ||
1756               FromType->isNullPtrType())) {
1757     // Boolean conversions (C++ 4.12).
1758     SCS.Second = ICK_Boolean_Conversion;
1759     FromType = S.Context.BoolTy;
1760   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1761              ToType->isIntegralType(S.Context)) {
1762     // Integral conversions (C++ 4.7).
1763     SCS.Second = ICK_Integral_Conversion;
1764     FromType = ToType.getUnqualifiedType();
1765   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1766     // Complex conversions (C99 6.3.1.6)
1767     SCS.Second = ICK_Complex_Conversion;
1768     FromType = ToType.getUnqualifiedType();
1769   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1770              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1771     // Complex-real conversions (C99 6.3.1.7)
1772     SCS.Second = ICK_Complex_Real;
1773     FromType = ToType.getUnqualifiedType();
1774   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1775     // FIXME: disable conversions between long double and __float128 if
1776     // their representation is different until there is back end support
1777     // We of course allow this conversion if long double is really double.
1778     if (&S.Context.getFloatTypeSemantics(FromType) !=
1779         &S.Context.getFloatTypeSemantics(ToType)) {
1780       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1781                                     ToType == S.Context.LongDoubleTy) ||
1782                                    (FromType == S.Context.LongDoubleTy &&
1783                                     ToType == S.Context.Float128Ty));
1784       if (Float128AndLongDouble &&
1785           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1786            &llvm::APFloat::PPCDoubleDouble()))
1787         return false;
1788     }
1789     // Floating point conversions (C++ 4.8).
1790     SCS.Second = ICK_Floating_Conversion;
1791     FromType = ToType.getUnqualifiedType();
1792   } else if ((FromType->isRealFloatingType() &&
1793               ToType->isIntegralType(S.Context)) ||
1794              (FromType->isIntegralOrUnscopedEnumerationType() &&
1795               ToType->isRealFloatingType())) {
1796     // Floating-integral conversions (C++ 4.9).
1797     SCS.Second = ICK_Floating_Integral;
1798     FromType = ToType.getUnqualifiedType();
1799   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1800     SCS.Second = ICK_Block_Pointer_Conversion;
1801   } else if (AllowObjCWritebackConversion &&
1802              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1803     SCS.Second = ICK_Writeback_Conversion;
1804   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1805                                    FromType, IncompatibleObjC)) {
1806     // Pointer conversions (C++ 4.10).
1807     SCS.Second = ICK_Pointer_Conversion;
1808     SCS.IncompatibleObjC = IncompatibleObjC;
1809     FromType = FromType.getUnqualifiedType();
1810   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1811                                          InOverloadResolution, FromType)) {
1812     // Pointer to member conversions (4.11).
1813     SCS.Second = ICK_Pointer_Member;
1814   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1815     SCS.Second = SecondICK;
1816     FromType = ToType.getUnqualifiedType();
1817   } else if (!S.getLangOpts().CPlusPlus &&
1818              S.Context.typesAreCompatible(ToType, FromType)) {
1819     // Compatible conversions (Clang extension for C function overloading)
1820     SCS.Second = ICK_Compatible_Conversion;
1821     FromType = ToType.getUnqualifiedType();
1822   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1823                                              InOverloadResolution,
1824                                              SCS, CStyle)) {
1825     SCS.Second = ICK_TransparentUnionConversion;
1826     FromType = ToType;
1827   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1828                                  CStyle)) {
1829     // tryAtomicConversion has updated the standard conversion sequence
1830     // appropriately.
1831     return true;
1832   } else if (ToType->isEventT() &&
1833              From->isIntegerConstantExpr(S.getASTContext()) &&
1834              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1835     SCS.Second = ICK_Zero_Event_Conversion;
1836     FromType = ToType;
1837   } else if (ToType->isQueueT() &&
1838              From->isIntegerConstantExpr(S.getASTContext()) &&
1839              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1840     SCS.Second = ICK_Zero_Queue_Conversion;
1841     FromType = ToType;
1842   } else {
1843     // No second conversion required.
1844     SCS.Second = ICK_Identity;
1845   }
1846   SCS.setToType(1, FromType);
1847 
1848   // The third conversion can be a function pointer conversion or a
1849   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1850   bool ObjCLifetimeConversion;
1851   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1852     // Function pointer conversions (removing 'noexcept') including removal of
1853     // 'noreturn' (Clang extension).
1854     SCS.Third = ICK_Function_Conversion;
1855   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1856                                          ObjCLifetimeConversion)) {
1857     SCS.Third = ICK_Qualification;
1858     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1859     FromType = ToType;
1860   } else {
1861     // No conversion required
1862     SCS.Third = ICK_Identity;
1863   }
1864 
1865   // C++ [over.best.ics]p6:
1866   //   [...] Any difference in top-level cv-qualification is
1867   //   subsumed by the initialization itself and does not constitute
1868   //   a conversion. [...]
1869   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1870   QualType CanonTo = S.Context.getCanonicalType(ToType);
1871   if (CanonFrom.getLocalUnqualifiedType()
1872                                      == CanonTo.getLocalUnqualifiedType() &&
1873       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1874     FromType = ToType;
1875     CanonFrom = CanonTo;
1876   }
1877 
1878   SCS.setToType(2, FromType);
1879 
1880   if (CanonFrom == CanonTo)
1881     return true;
1882 
1883   // If we have not converted the argument type to the parameter type,
1884   // this is a bad conversion sequence, unless we're resolving an overload in C.
1885   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1886     return false;
1887 
1888   ExprResult ER = ExprResult{From};
1889   Sema::AssignConvertType Conv =
1890       S.CheckSingleAssignmentConstraints(ToType, ER,
1891                                          /*Diagnose=*/false,
1892                                          /*DiagnoseCFAudited=*/false,
1893                                          /*ConvertRHS=*/false);
1894   ImplicitConversionKind SecondConv;
1895   switch (Conv) {
1896   case Sema::Compatible:
1897     SecondConv = ICK_C_Only_Conversion;
1898     break;
1899   // For our purposes, discarding qualifiers is just as bad as using an
1900   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1901   // qualifiers, as well.
1902   case Sema::CompatiblePointerDiscardsQualifiers:
1903   case Sema::IncompatiblePointer:
1904   case Sema::IncompatiblePointerSign:
1905     SecondConv = ICK_Incompatible_Pointer_Conversion;
1906     break;
1907   default:
1908     return false;
1909   }
1910 
1911   // First can only be an lvalue conversion, so we pretend that this was the
1912   // second conversion. First should already be valid from earlier in the
1913   // function.
1914   SCS.Second = SecondConv;
1915   SCS.setToType(1, ToType);
1916 
1917   // Third is Identity, because Second should rank us worse than any other
1918   // conversion. This could also be ICK_Qualification, but it's simpler to just
1919   // lump everything in with the second conversion, and we don't gain anything
1920   // from making this ICK_Qualification.
1921   SCS.Third = ICK_Identity;
1922   SCS.setToType(2, ToType);
1923   return true;
1924 }
1925 
1926 static bool
1927 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1928                                      QualType &ToType,
1929                                      bool InOverloadResolution,
1930                                      StandardConversionSequence &SCS,
1931                                      bool CStyle) {
1932 
1933   const RecordType *UT = ToType->getAsUnionType();
1934   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1935     return false;
1936   // The field to initialize within the transparent union.
1937   RecordDecl *UD = UT->getDecl();
1938   // It's compatible if the expression matches any of the fields.
1939   for (const auto *it : UD->fields()) {
1940     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1941                              CStyle, /*ObjCWritebackConversion=*/false)) {
1942       ToType = it->getType();
1943       return true;
1944     }
1945   }
1946   return false;
1947 }
1948 
1949 /// IsIntegralPromotion - Determines whether the conversion from the
1950 /// expression From (whose potentially-adjusted type is FromType) to
1951 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1952 /// sets PromotedType to the promoted type.
1953 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1954   const BuiltinType *To = ToType->getAs<BuiltinType>();
1955   // All integers are built-in.
1956   if (!To) {
1957     return false;
1958   }
1959 
1960   // An rvalue of type char, signed char, unsigned char, short int, or
1961   // unsigned short int can be converted to an rvalue of type int if
1962   // int can represent all the values of the source type; otherwise,
1963   // the source rvalue can be converted to an rvalue of type unsigned
1964   // int (C++ 4.5p1).
1965   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1966       !FromType->isEnumeralType()) {
1967     if (// We can promote any signed, promotable integer type to an int
1968         (FromType->isSignedIntegerType() ||
1969          // We can promote any unsigned integer type whose size is
1970          // less than int to an int.
1971          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1972       return To->getKind() == BuiltinType::Int;
1973     }
1974 
1975     return To->getKind() == BuiltinType::UInt;
1976   }
1977 
1978   // C++11 [conv.prom]p3:
1979   //   A prvalue of an unscoped enumeration type whose underlying type is not
1980   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1981   //   following types that can represent all the values of the enumeration
1982   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1983   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1984   //   long long int. If none of the types in that list can represent all the
1985   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1986   //   type can be converted to an rvalue a prvalue of the extended integer type
1987   //   with lowest integer conversion rank (4.13) greater than the rank of long
1988   //   long in which all the values of the enumeration can be represented. If
1989   //   there are two such extended types, the signed one is chosen.
1990   // C++11 [conv.prom]p4:
1991   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1992   //   can be converted to a prvalue of its underlying type. Moreover, if
1993   //   integral promotion can be applied to its underlying type, a prvalue of an
1994   //   unscoped enumeration type whose underlying type is fixed can also be
1995   //   converted to a prvalue of the promoted underlying type.
1996   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1997     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1998     // provided for a scoped enumeration.
1999     if (FromEnumType->getDecl()->isScoped())
2000       return false;
2001 
2002     // We can perform an integral promotion to the underlying type of the enum,
2003     // even if that's not the promoted type. Note that the check for promoting
2004     // the underlying type is based on the type alone, and does not consider
2005     // the bitfield-ness of the actual source expression.
2006     if (FromEnumType->getDecl()->isFixed()) {
2007       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2008       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2009              IsIntegralPromotion(nullptr, Underlying, ToType);
2010     }
2011 
2012     // We have already pre-calculated the promotion type, so this is trivial.
2013     if (ToType->isIntegerType() &&
2014         isCompleteType(From->getLocStart(), FromType))
2015       return Context.hasSameUnqualifiedType(
2016           ToType, FromEnumType->getDecl()->getPromotionType());
2017 
2018     // C++ [conv.prom]p5:
2019     //   If the bit-field has an enumerated type, it is treated as any other
2020     //   value of that type for promotion purposes.
2021     //
2022     // ... so do not fall through into the bit-field checks below in C++.
2023     if (getLangOpts().CPlusPlus)
2024       return false;
2025   }
2026 
2027   // C++0x [conv.prom]p2:
2028   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2029   //   to an rvalue a prvalue of the first of the following types that can
2030   //   represent all the values of its underlying type: int, unsigned int,
2031   //   long int, unsigned long int, long long int, or unsigned long long int.
2032   //   If none of the types in that list can represent all the values of its
2033   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2034   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2035   //   type.
2036   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2037       ToType->isIntegerType()) {
2038     // Determine whether the type we're converting from is signed or
2039     // unsigned.
2040     bool FromIsSigned = FromType->isSignedIntegerType();
2041     uint64_t FromSize = Context.getTypeSize(FromType);
2042 
2043     // The types we'll try to promote to, in the appropriate
2044     // order. Try each of these types.
2045     QualType PromoteTypes[6] = {
2046       Context.IntTy, Context.UnsignedIntTy,
2047       Context.LongTy, Context.UnsignedLongTy ,
2048       Context.LongLongTy, Context.UnsignedLongLongTy
2049     };
2050     for (int Idx = 0; Idx < 6; ++Idx) {
2051       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2052       if (FromSize < ToSize ||
2053           (FromSize == ToSize &&
2054            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2055         // We found the type that we can promote to. If this is the
2056         // type we wanted, we have a promotion. Otherwise, no
2057         // promotion.
2058         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2059       }
2060     }
2061   }
2062 
2063   // An rvalue for an integral bit-field (9.6) can be converted to an
2064   // rvalue of type int if int can represent all the values of the
2065   // bit-field; otherwise, it can be converted to unsigned int if
2066   // unsigned int can represent all the values of the bit-field. If
2067   // the bit-field is larger yet, no integral promotion applies to
2068   // it. If the bit-field has an enumerated type, it is treated as any
2069   // other value of that type for promotion purposes (C++ 4.5p3).
2070   // FIXME: We should delay checking of bit-fields until we actually perform the
2071   // conversion.
2072   //
2073   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2074   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2075   // bit-fields and those whose underlying type is larger than int) for GCC
2076   // compatibility.
2077   if (From) {
2078     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2079       llvm::APSInt BitWidth;
2080       if (FromType->isIntegralType(Context) &&
2081           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2082         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2083         ToSize = Context.getTypeSize(ToType);
2084 
2085         // Are we promoting to an int from a bitfield that fits in an int?
2086         if (BitWidth < ToSize ||
2087             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2088           return To->getKind() == BuiltinType::Int;
2089         }
2090 
2091         // Are we promoting to an unsigned int from an unsigned bitfield
2092         // that fits into an unsigned int?
2093         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2094           return To->getKind() == BuiltinType::UInt;
2095         }
2096 
2097         return false;
2098       }
2099     }
2100   }
2101 
2102   // An rvalue of type bool can be converted to an rvalue of type int,
2103   // with false becoming zero and true becoming one (C++ 4.5p4).
2104   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2105     return true;
2106   }
2107 
2108   return false;
2109 }
2110 
2111 /// IsFloatingPointPromotion - Determines whether the conversion from
2112 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2113 /// returns true and sets PromotedType to the promoted type.
2114 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2115   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2116     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2117       /// An rvalue of type float can be converted to an rvalue of type
2118       /// double. (C++ 4.6p1).
2119       if (FromBuiltin->getKind() == BuiltinType::Float &&
2120           ToBuiltin->getKind() == BuiltinType::Double)
2121         return true;
2122 
2123       // C99 6.3.1.5p1:
2124       //   When a float is promoted to double or long double, or a
2125       //   double is promoted to long double [...].
2126       if (!getLangOpts().CPlusPlus &&
2127           (FromBuiltin->getKind() == BuiltinType::Float ||
2128            FromBuiltin->getKind() == BuiltinType::Double) &&
2129           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2130            ToBuiltin->getKind() == BuiltinType::Float128))
2131         return true;
2132 
2133       // Half can be promoted to float.
2134       if (!getLangOpts().NativeHalfType &&
2135            FromBuiltin->getKind() == BuiltinType::Half &&
2136           ToBuiltin->getKind() == BuiltinType::Float)
2137         return true;
2138     }
2139 
2140   return false;
2141 }
2142 
2143 /// Determine if a conversion is a complex promotion.
2144 ///
2145 /// A complex promotion is defined as a complex -> complex conversion
2146 /// where the conversion between the underlying real types is a
2147 /// floating-point or integral promotion.
2148 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2149   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2150   if (!FromComplex)
2151     return false;
2152 
2153   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2154   if (!ToComplex)
2155     return false;
2156 
2157   return IsFloatingPointPromotion(FromComplex->getElementType(),
2158                                   ToComplex->getElementType()) ||
2159     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2160                         ToComplex->getElementType());
2161 }
2162 
2163 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2164 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2165 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2166 /// if non-empty, will be a pointer to ToType that may or may not have
2167 /// the right set of qualifiers on its pointee.
2168 ///
2169 static QualType
2170 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2171                                    QualType ToPointee, QualType ToType,
2172                                    ASTContext &Context,
2173                                    bool StripObjCLifetime = false) {
2174   assert((FromPtr->getTypeClass() == Type::Pointer ||
2175           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2176          "Invalid similarly-qualified pointer type");
2177 
2178   /// Conversions to 'id' subsume cv-qualifier conversions.
2179   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2180     return ToType.getUnqualifiedType();
2181 
2182   QualType CanonFromPointee
2183     = Context.getCanonicalType(FromPtr->getPointeeType());
2184   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2185   Qualifiers Quals = CanonFromPointee.getQualifiers();
2186 
2187   if (StripObjCLifetime)
2188     Quals.removeObjCLifetime();
2189 
2190   // Exact qualifier match -> return the pointer type we're converting to.
2191   if (CanonToPointee.getLocalQualifiers() == Quals) {
2192     // ToType is exactly what we need. Return it.
2193     if (!ToType.isNull())
2194       return ToType.getUnqualifiedType();
2195 
2196     // Build a pointer to ToPointee. It has the right qualifiers
2197     // already.
2198     if (isa<ObjCObjectPointerType>(ToType))
2199       return Context.getObjCObjectPointerType(ToPointee);
2200     return Context.getPointerType(ToPointee);
2201   }
2202 
2203   // Just build a canonical type that has the right qualifiers.
2204   QualType QualifiedCanonToPointee
2205     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2206 
2207   if (isa<ObjCObjectPointerType>(ToType))
2208     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2209   return Context.getPointerType(QualifiedCanonToPointee);
2210 }
2211 
2212 static bool isNullPointerConstantForConversion(Expr *Expr,
2213                                                bool InOverloadResolution,
2214                                                ASTContext &Context) {
2215   // Handle value-dependent integral null pointer constants correctly.
2216   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2217   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2218       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2219     return !InOverloadResolution;
2220 
2221   return Expr->isNullPointerConstant(Context,
2222                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2223                                         : Expr::NPC_ValueDependentIsNull);
2224 }
2225 
2226 /// IsPointerConversion - Determines whether the conversion of the
2227 /// expression From, which has the (possibly adjusted) type FromType,
2228 /// can be converted to the type ToType via a pointer conversion (C++
2229 /// 4.10). If so, returns true and places the converted type (that
2230 /// might differ from ToType in its cv-qualifiers at some level) into
2231 /// ConvertedType.
2232 ///
2233 /// This routine also supports conversions to and from block pointers
2234 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2235 /// pointers to interfaces. FIXME: Once we've determined the
2236 /// appropriate overloading rules for Objective-C, we may want to
2237 /// split the Objective-C checks into a different routine; however,
2238 /// GCC seems to consider all of these conversions to be pointer
2239 /// conversions, so for now they live here. IncompatibleObjC will be
2240 /// set if the conversion is an allowed Objective-C conversion that
2241 /// should result in a warning.
2242 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2243                                bool InOverloadResolution,
2244                                QualType& ConvertedType,
2245                                bool &IncompatibleObjC) {
2246   IncompatibleObjC = false;
2247   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2248                               IncompatibleObjC))
2249     return true;
2250 
2251   // Conversion from a null pointer constant to any Objective-C pointer type.
2252   if (ToType->isObjCObjectPointerType() &&
2253       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2254     ConvertedType = ToType;
2255     return true;
2256   }
2257 
2258   // Blocks: Block pointers can be converted to void*.
2259   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2260       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2261     ConvertedType = ToType;
2262     return true;
2263   }
2264   // Blocks: A null pointer constant can be converted to a block
2265   // pointer type.
2266   if (ToType->isBlockPointerType() &&
2267       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2268     ConvertedType = ToType;
2269     return true;
2270   }
2271 
2272   // If the left-hand-side is nullptr_t, the right side can be a null
2273   // pointer constant.
2274   if (ToType->isNullPtrType() &&
2275       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2276     ConvertedType = ToType;
2277     return true;
2278   }
2279 
2280   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2281   if (!ToTypePtr)
2282     return false;
2283 
2284   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2285   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2286     ConvertedType = ToType;
2287     return true;
2288   }
2289 
2290   // Beyond this point, both types need to be pointers
2291   // , including objective-c pointers.
2292   QualType ToPointeeType = ToTypePtr->getPointeeType();
2293   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2294       !getLangOpts().ObjCAutoRefCount) {
2295     ConvertedType = BuildSimilarlyQualifiedPointerType(
2296                                       FromType->getAs<ObjCObjectPointerType>(),
2297                                                        ToPointeeType,
2298                                                        ToType, Context);
2299     return true;
2300   }
2301   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2302   if (!FromTypePtr)
2303     return false;
2304 
2305   QualType FromPointeeType = FromTypePtr->getPointeeType();
2306 
2307   // If the unqualified pointee types are the same, this can't be a
2308   // pointer conversion, so don't do all of the work below.
2309   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2310     return false;
2311 
2312   // An rvalue of type "pointer to cv T," where T is an object type,
2313   // can be converted to an rvalue of type "pointer to cv void" (C++
2314   // 4.10p2).
2315   if (FromPointeeType->isIncompleteOrObjectType() &&
2316       ToPointeeType->isVoidType()) {
2317     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2318                                                        ToPointeeType,
2319                                                        ToType, Context,
2320                                                    /*StripObjCLifetime=*/true);
2321     return true;
2322   }
2323 
2324   // MSVC allows implicit function to void* type conversion.
2325   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2326       ToPointeeType->isVoidType()) {
2327     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2328                                                        ToPointeeType,
2329                                                        ToType, Context);
2330     return true;
2331   }
2332 
2333   // When we're overloading in C, we allow a special kind of pointer
2334   // conversion for compatible-but-not-identical pointee types.
2335   if (!getLangOpts().CPlusPlus &&
2336       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2337     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338                                                        ToPointeeType,
2339                                                        ToType, Context);
2340     return true;
2341   }
2342 
2343   // C++ [conv.ptr]p3:
2344   //
2345   //   An rvalue of type "pointer to cv D," where D is a class type,
2346   //   can be converted to an rvalue of type "pointer to cv B," where
2347   //   B is a base class (clause 10) of D. If B is an inaccessible
2348   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2349   //   necessitates this conversion is ill-formed. The result of the
2350   //   conversion is a pointer to the base class sub-object of the
2351   //   derived class object. The null pointer value is converted to
2352   //   the null pointer value of the destination type.
2353   //
2354   // Note that we do not check for ambiguity or inaccessibility
2355   // here. That is handled by CheckPointerConversion.
2356   if (getLangOpts().CPlusPlus &&
2357       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2358       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2359       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2360     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2361                                                        ToPointeeType,
2362                                                        ToType, Context);
2363     return true;
2364   }
2365 
2366   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2367       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2368     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2369                                                        ToPointeeType,
2370                                                        ToType, Context);
2371     return true;
2372   }
2373 
2374   return false;
2375 }
2376 
2377 /// Adopt the given qualifiers for the given type.
2378 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2379   Qualifiers TQs = T.getQualifiers();
2380 
2381   // Check whether qualifiers already match.
2382   if (TQs == Qs)
2383     return T;
2384 
2385   if (Qs.compatiblyIncludes(TQs))
2386     return Context.getQualifiedType(T, Qs);
2387 
2388   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2389 }
2390 
2391 /// isObjCPointerConversion - Determines whether this is an
2392 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2393 /// with the same arguments and return values.
2394 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2395                                    QualType& ConvertedType,
2396                                    bool &IncompatibleObjC) {
2397   if (!getLangOpts().ObjC1)
2398     return false;
2399 
2400   // The set of qualifiers on the type we're converting from.
2401   Qualifiers FromQualifiers = FromType.getQualifiers();
2402 
2403   // First, we handle all conversions on ObjC object pointer types.
2404   const ObjCObjectPointerType* ToObjCPtr =
2405     ToType->getAs<ObjCObjectPointerType>();
2406   const ObjCObjectPointerType *FromObjCPtr =
2407     FromType->getAs<ObjCObjectPointerType>();
2408 
2409   if (ToObjCPtr && FromObjCPtr) {
2410     // If the pointee types are the same (ignoring qualifications),
2411     // then this is not a pointer conversion.
2412     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2413                                        FromObjCPtr->getPointeeType()))
2414       return false;
2415 
2416     // Conversion between Objective-C pointers.
2417     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2418       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2419       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2420       if (getLangOpts().CPlusPlus && LHS && RHS &&
2421           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2422                                                 FromObjCPtr->getPointeeType()))
2423         return false;
2424       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2425                                                    ToObjCPtr->getPointeeType(),
2426                                                          ToType, Context);
2427       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2428       return true;
2429     }
2430 
2431     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2432       // Okay: this is some kind of implicit downcast of Objective-C
2433       // interfaces, which is permitted. However, we're going to
2434       // complain about it.
2435       IncompatibleObjC = true;
2436       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2437                                                    ToObjCPtr->getPointeeType(),
2438                                                          ToType, Context);
2439       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2440       return true;
2441     }
2442   }
2443   // Beyond this point, both types need to be C pointers or block pointers.
2444   QualType ToPointeeType;
2445   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2446     ToPointeeType = ToCPtr->getPointeeType();
2447   else if (const BlockPointerType *ToBlockPtr =
2448             ToType->getAs<BlockPointerType>()) {
2449     // Objective C++: We're able to convert from a pointer to any object
2450     // to a block pointer type.
2451     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2452       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2453       return true;
2454     }
2455     ToPointeeType = ToBlockPtr->getPointeeType();
2456   }
2457   else if (FromType->getAs<BlockPointerType>() &&
2458            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2459     // Objective C++: We're able to convert from a block pointer type to a
2460     // pointer to any object.
2461     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2462     return true;
2463   }
2464   else
2465     return false;
2466 
2467   QualType FromPointeeType;
2468   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2469     FromPointeeType = FromCPtr->getPointeeType();
2470   else if (const BlockPointerType *FromBlockPtr =
2471            FromType->getAs<BlockPointerType>())
2472     FromPointeeType = FromBlockPtr->getPointeeType();
2473   else
2474     return false;
2475 
2476   // If we have pointers to pointers, recursively check whether this
2477   // is an Objective-C conversion.
2478   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2479       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2480                               IncompatibleObjC)) {
2481     // We always complain about this conversion.
2482     IncompatibleObjC = true;
2483     ConvertedType = Context.getPointerType(ConvertedType);
2484     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2485     return true;
2486   }
2487   // Allow conversion of pointee being objective-c pointer to another one;
2488   // as in I* to id.
2489   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2490       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2491       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2492                               IncompatibleObjC)) {
2493 
2494     ConvertedType = Context.getPointerType(ConvertedType);
2495     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2496     return true;
2497   }
2498 
2499   // If we have pointers to functions or blocks, check whether the only
2500   // differences in the argument and result types are in Objective-C
2501   // pointer conversions. If so, we permit the conversion (but
2502   // complain about it).
2503   const FunctionProtoType *FromFunctionType
2504     = FromPointeeType->getAs<FunctionProtoType>();
2505   const FunctionProtoType *ToFunctionType
2506     = ToPointeeType->getAs<FunctionProtoType>();
2507   if (FromFunctionType && ToFunctionType) {
2508     // If the function types are exactly the same, this isn't an
2509     // Objective-C pointer conversion.
2510     if (Context.getCanonicalType(FromPointeeType)
2511           == Context.getCanonicalType(ToPointeeType))
2512       return false;
2513 
2514     // Perform the quick checks that will tell us whether these
2515     // function types are obviously different.
2516     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2517         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2518         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2519       return false;
2520 
2521     bool HasObjCConversion = false;
2522     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2523         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2524       // Okay, the types match exactly. Nothing to do.
2525     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2526                                        ToFunctionType->getReturnType(),
2527                                        ConvertedType, IncompatibleObjC)) {
2528       // Okay, we have an Objective-C pointer conversion.
2529       HasObjCConversion = true;
2530     } else {
2531       // Function types are too different. Abort.
2532       return false;
2533     }
2534 
2535     // Check argument types.
2536     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2537          ArgIdx != NumArgs; ++ArgIdx) {
2538       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2539       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2540       if (Context.getCanonicalType(FromArgType)
2541             == Context.getCanonicalType(ToArgType)) {
2542         // Okay, the types match exactly. Nothing to do.
2543       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2544                                          ConvertedType, IncompatibleObjC)) {
2545         // Okay, we have an Objective-C pointer conversion.
2546         HasObjCConversion = true;
2547       } else {
2548         // Argument types are too different. Abort.
2549         return false;
2550       }
2551     }
2552 
2553     if (HasObjCConversion) {
2554       // We had an Objective-C conversion. Allow this pointer
2555       // conversion, but complain about it.
2556       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2557       IncompatibleObjC = true;
2558       return true;
2559     }
2560   }
2561 
2562   return false;
2563 }
2564 
2565 /// Determine whether this is an Objective-C writeback conversion,
2566 /// used for parameter passing when performing automatic reference counting.
2567 ///
2568 /// \param FromType The type we're converting form.
2569 ///
2570 /// \param ToType The type we're converting to.
2571 ///
2572 /// \param ConvertedType The type that will be produced after applying
2573 /// this conversion.
2574 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2575                                      QualType &ConvertedType) {
2576   if (!getLangOpts().ObjCAutoRefCount ||
2577       Context.hasSameUnqualifiedType(FromType, ToType))
2578     return false;
2579 
2580   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2581   QualType ToPointee;
2582   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2583     ToPointee = ToPointer->getPointeeType();
2584   else
2585     return false;
2586 
2587   Qualifiers ToQuals = ToPointee.getQualifiers();
2588   if (!ToPointee->isObjCLifetimeType() ||
2589       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2590       !ToQuals.withoutObjCLifetime().empty())
2591     return false;
2592 
2593   // Argument must be a pointer to __strong to __weak.
2594   QualType FromPointee;
2595   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2596     FromPointee = FromPointer->getPointeeType();
2597   else
2598     return false;
2599 
2600   Qualifiers FromQuals = FromPointee.getQualifiers();
2601   if (!FromPointee->isObjCLifetimeType() ||
2602       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2603        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2604     return false;
2605 
2606   // Make sure that we have compatible qualifiers.
2607   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2608   if (!ToQuals.compatiblyIncludes(FromQuals))
2609     return false;
2610 
2611   // Remove qualifiers from the pointee type we're converting from; they
2612   // aren't used in the compatibility check belong, and we'll be adding back
2613   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2614   FromPointee = FromPointee.getUnqualifiedType();
2615 
2616   // The unqualified form of the pointee types must be compatible.
2617   ToPointee = ToPointee.getUnqualifiedType();
2618   bool IncompatibleObjC;
2619   if (Context.typesAreCompatible(FromPointee, ToPointee))
2620     FromPointee = ToPointee;
2621   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2622                                     IncompatibleObjC))
2623     return false;
2624 
2625   /// Construct the type we're converting to, which is a pointer to
2626   /// __autoreleasing pointee.
2627   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2628   ConvertedType = Context.getPointerType(FromPointee);
2629   return true;
2630 }
2631 
2632 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2633                                     QualType& ConvertedType) {
2634   QualType ToPointeeType;
2635   if (const BlockPointerType *ToBlockPtr =
2636         ToType->getAs<BlockPointerType>())
2637     ToPointeeType = ToBlockPtr->getPointeeType();
2638   else
2639     return false;
2640 
2641   QualType FromPointeeType;
2642   if (const BlockPointerType *FromBlockPtr =
2643       FromType->getAs<BlockPointerType>())
2644     FromPointeeType = FromBlockPtr->getPointeeType();
2645   else
2646     return false;
2647   // We have pointer to blocks, check whether the only
2648   // differences in the argument and result types are in Objective-C
2649   // pointer conversions. If so, we permit the conversion.
2650 
2651   const FunctionProtoType *FromFunctionType
2652     = FromPointeeType->getAs<FunctionProtoType>();
2653   const FunctionProtoType *ToFunctionType
2654     = ToPointeeType->getAs<FunctionProtoType>();
2655 
2656   if (!FromFunctionType || !ToFunctionType)
2657     return false;
2658 
2659   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2660     return true;
2661 
2662   // Perform the quick checks that will tell us whether these
2663   // function types are obviously different.
2664   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2665       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2666     return false;
2667 
2668   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2669   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2670   if (FromEInfo != ToEInfo)
2671     return false;
2672 
2673   bool IncompatibleObjC = false;
2674   if (Context.hasSameType(FromFunctionType->getReturnType(),
2675                           ToFunctionType->getReturnType())) {
2676     // Okay, the types match exactly. Nothing to do.
2677   } else {
2678     QualType RHS = FromFunctionType->getReturnType();
2679     QualType LHS = ToFunctionType->getReturnType();
2680     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2681         !RHS.hasQualifiers() && LHS.hasQualifiers())
2682        LHS = LHS.getUnqualifiedType();
2683 
2684      if (Context.hasSameType(RHS,LHS)) {
2685        // OK exact match.
2686      } else if (isObjCPointerConversion(RHS, LHS,
2687                                         ConvertedType, IncompatibleObjC)) {
2688      if (IncompatibleObjC)
2689        return false;
2690      // Okay, we have an Objective-C pointer conversion.
2691      }
2692      else
2693        return false;
2694    }
2695 
2696    // Check argument types.
2697    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2698         ArgIdx != NumArgs; ++ArgIdx) {
2699      IncompatibleObjC = false;
2700      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2701      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2702      if (Context.hasSameType(FromArgType, ToArgType)) {
2703        // Okay, the types match exactly. Nothing to do.
2704      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2705                                         ConvertedType, IncompatibleObjC)) {
2706        if (IncompatibleObjC)
2707          return false;
2708        // Okay, we have an Objective-C pointer conversion.
2709      } else
2710        // Argument types are too different. Abort.
2711        return false;
2712    }
2713 
2714    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2715    bool CanUseToFPT, CanUseFromFPT;
2716    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2717                                       CanUseToFPT, CanUseFromFPT,
2718                                       NewParamInfos))
2719      return false;
2720 
2721    ConvertedType = ToType;
2722    return true;
2723 }
2724 
2725 enum {
2726   ft_default,
2727   ft_different_class,
2728   ft_parameter_arity,
2729   ft_parameter_mismatch,
2730   ft_return_type,
2731   ft_qualifer_mismatch,
2732   ft_noexcept
2733 };
2734 
2735 /// Attempts to get the FunctionProtoType from a Type. Handles
2736 /// MemberFunctionPointers properly.
2737 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2738   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2739     return FPT;
2740 
2741   if (auto *MPT = FromType->getAs<MemberPointerType>())
2742     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2743 
2744   return nullptr;
2745 }
2746 
2747 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2748 /// function types.  Catches different number of parameter, mismatch in
2749 /// parameter types, and different return types.
2750 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2751                                       QualType FromType, QualType ToType) {
2752   // If either type is not valid, include no extra info.
2753   if (FromType.isNull() || ToType.isNull()) {
2754     PDiag << ft_default;
2755     return;
2756   }
2757 
2758   // Get the function type from the pointers.
2759   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2760     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2761                             *ToMember = ToType->getAs<MemberPointerType>();
2762     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2763       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2764             << QualType(FromMember->getClass(), 0);
2765       return;
2766     }
2767     FromType = FromMember->getPointeeType();
2768     ToType = ToMember->getPointeeType();
2769   }
2770 
2771   if (FromType->isPointerType())
2772     FromType = FromType->getPointeeType();
2773   if (ToType->isPointerType())
2774     ToType = ToType->getPointeeType();
2775 
2776   // Remove references.
2777   FromType = FromType.getNonReferenceType();
2778   ToType = ToType.getNonReferenceType();
2779 
2780   // Don't print extra info for non-specialized template functions.
2781   if (FromType->isInstantiationDependentType() &&
2782       !FromType->getAs<TemplateSpecializationType>()) {
2783     PDiag << ft_default;
2784     return;
2785   }
2786 
2787   // No extra info for same types.
2788   if (Context.hasSameType(FromType, ToType)) {
2789     PDiag << ft_default;
2790     return;
2791   }
2792 
2793   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2794                           *ToFunction = tryGetFunctionProtoType(ToType);
2795 
2796   // Both types need to be function types.
2797   if (!FromFunction || !ToFunction) {
2798     PDiag << ft_default;
2799     return;
2800   }
2801 
2802   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2803     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2804           << FromFunction->getNumParams();
2805     return;
2806   }
2807 
2808   // Handle different parameter types.
2809   unsigned ArgPos;
2810   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2811     PDiag << ft_parameter_mismatch << ArgPos + 1
2812           << ToFunction->getParamType(ArgPos)
2813           << FromFunction->getParamType(ArgPos);
2814     return;
2815   }
2816 
2817   // Handle different return type.
2818   if (!Context.hasSameType(FromFunction->getReturnType(),
2819                            ToFunction->getReturnType())) {
2820     PDiag << ft_return_type << ToFunction->getReturnType()
2821           << FromFunction->getReturnType();
2822     return;
2823   }
2824 
2825   unsigned FromQuals = FromFunction->getTypeQuals(),
2826            ToQuals = ToFunction->getTypeQuals();
2827   if (FromQuals != ToQuals) {
2828     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2829     return;
2830   }
2831 
2832   // Handle exception specification differences on canonical type (in C++17
2833   // onwards).
2834   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2835           ->isNothrow() !=
2836       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2837           ->isNothrow()) {
2838     PDiag << ft_noexcept;
2839     return;
2840   }
2841 
2842   // Unable to find a difference, so add no extra info.
2843   PDiag << ft_default;
2844 }
2845 
2846 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2847 /// for equality of their argument types. Caller has already checked that
2848 /// they have same number of arguments.  If the parameters are different,
2849 /// ArgPos will have the parameter index of the first different parameter.
2850 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2851                                       const FunctionProtoType *NewType,
2852                                       unsigned *ArgPos) {
2853   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2854                                               N = NewType->param_type_begin(),
2855                                               E = OldType->param_type_end();
2856        O && (O != E); ++O, ++N) {
2857     if (!Context.hasSameType(O->getUnqualifiedType(),
2858                              N->getUnqualifiedType())) {
2859       if (ArgPos)
2860         *ArgPos = O - OldType->param_type_begin();
2861       return false;
2862     }
2863   }
2864   return true;
2865 }
2866 
2867 /// CheckPointerConversion - Check the pointer conversion from the
2868 /// expression From to the type ToType. This routine checks for
2869 /// ambiguous or inaccessible derived-to-base pointer
2870 /// conversions for which IsPointerConversion has already returned
2871 /// true. It returns true and produces a diagnostic if there was an
2872 /// error, or returns false otherwise.
2873 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2874                                   CastKind &Kind,
2875                                   CXXCastPath& BasePath,
2876                                   bool IgnoreBaseAccess,
2877                                   bool Diagnose) {
2878   QualType FromType = From->getType();
2879   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2880 
2881   Kind = CK_BitCast;
2882 
2883   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2884       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2885           Expr::NPCK_ZeroExpression) {
2886     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2887       DiagRuntimeBehavior(From->getExprLoc(), From,
2888                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2889                             << ToType << From->getSourceRange());
2890     else if (!isUnevaluatedContext())
2891       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2892         << ToType << From->getSourceRange();
2893   }
2894   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2895     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2896       QualType FromPointeeType = FromPtrType->getPointeeType(),
2897                ToPointeeType   = ToPtrType->getPointeeType();
2898 
2899       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2900           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2901         // We must have a derived-to-base conversion. Check an
2902         // ambiguous or inaccessible conversion.
2903         unsigned InaccessibleID = 0;
2904         unsigned AmbigiousID = 0;
2905         if (Diagnose) {
2906           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2907           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2908         }
2909         if (CheckDerivedToBaseConversion(
2910                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2911                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2912                 &BasePath, IgnoreBaseAccess))
2913           return true;
2914 
2915         // The conversion was successful.
2916         Kind = CK_DerivedToBase;
2917       }
2918 
2919       if (Diagnose && !IsCStyleOrFunctionalCast &&
2920           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2921         assert(getLangOpts().MSVCCompat &&
2922                "this should only be possible with MSVCCompat!");
2923         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2924             << From->getSourceRange();
2925       }
2926     }
2927   } else if (const ObjCObjectPointerType *ToPtrType =
2928                ToType->getAs<ObjCObjectPointerType>()) {
2929     if (const ObjCObjectPointerType *FromPtrType =
2930           FromType->getAs<ObjCObjectPointerType>()) {
2931       // Objective-C++ conversions are always okay.
2932       // FIXME: We should have a different class of conversions for the
2933       // Objective-C++ implicit conversions.
2934       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2935         return false;
2936     } else if (FromType->isBlockPointerType()) {
2937       Kind = CK_BlockPointerToObjCPointerCast;
2938     } else {
2939       Kind = CK_CPointerToObjCPointerCast;
2940     }
2941   } else if (ToType->isBlockPointerType()) {
2942     if (!FromType->isBlockPointerType())
2943       Kind = CK_AnyPointerToBlockPointerCast;
2944   }
2945 
2946   // We shouldn't fall into this case unless it's valid for other
2947   // reasons.
2948   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2949     Kind = CK_NullToPointer;
2950 
2951   return false;
2952 }
2953 
2954 /// IsMemberPointerConversion - Determines whether the conversion of the
2955 /// expression From, which has the (possibly adjusted) type FromType, can be
2956 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2957 /// If so, returns true and places the converted type (that might differ from
2958 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2959 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2960                                      QualType ToType,
2961                                      bool InOverloadResolution,
2962                                      QualType &ConvertedType) {
2963   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2964   if (!ToTypePtr)
2965     return false;
2966 
2967   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2968   if (From->isNullPointerConstant(Context,
2969                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970                                         : Expr::NPC_ValueDependentIsNull)) {
2971     ConvertedType = ToType;
2972     return true;
2973   }
2974 
2975   // Otherwise, both types have to be member pointers.
2976   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2977   if (!FromTypePtr)
2978     return false;
2979 
2980   // A pointer to member of B can be converted to a pointer to member of D,
2981   // where D is derived from B (C++ 4.11p2).
2982   QualType FromClass(FromTypePtr->getClass(), 0);
2983   QualType ToClass(ToTypePtr->getClass(), 0);
2984 
2985   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2986       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2987     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2988                                                  ToClass.getTypePtr());
2989     return true;
2990   }
2991 
2992   return false;
2993 }
2994 
2995 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2996 /// expression From to the type ToType. This routine checks for ambiguous or
2997 /// virtual or inaccessible base-to-derived member pointer conversions
2998 /// for which IsMemberPointerConversion has already returned true. It returns
2999 /// true and produces a diagnostic if there was an error, or returns false
3000 /// otherwise.
3001 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3002                                         CastKind &Kind,
3003                                         CXXCastPath &BasePath,
3004                                         bool IgnoreBaseAccess) {
3005   QualType FromType = From->getType();
3006   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3007   if (!FromPtrType) {
3008     // This must be a null pointer to member pointer conversion
3009     assert(From->isNullPointerConstant(Context,
3010                                        Expr::NPC_ValueDependentIsNull) &&
3011            "Expr must be null pointer constant!");
3012     Kind = CK_NullToMemberPointer;
3013     return false;
3014   }
3015 
3016   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3017   assert(ToPtrType && "No member pointer cast has a target type "
3018                       "that is not a member pointer.");
3019 
3020   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3021   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3022 
3023   // FIXME: What about dependent types?
3024   assert(FromClass->isRecordType() && "Pointer into non-class.");
3025   assert(ToClass->isRecordType() && "Pointer into non-class.");
3026 
3027   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3028                      /*DetectVirtual=*/true);
3029   bool DerivationOkay =
3030       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3031   assert(DerivationOkay &&
3032          "Should not have been called if derivation isn't OK.");
3033   (void)DerivationOkay;
3034 
3035   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3036                                   getUnqualifiedType())) {
3037     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3038     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3039       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3040     return true;
3041   }
3042 
3043   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3044     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3045       << FromClass << ToClass << QualType(VBase, 0)
3046       << From->getSourceRange();
3047     return true;
3048   }
3049 
3050   if (!IgnoreBaseAccess)
3051     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3052                          Paths.front(),
3053                          diag::err_downcast_from_inaccessible_base);
3054 
3055   // Must be a base to derived member conversion.
3056   BuildBasePathArray(Paths, BasePath);
3057   Kind = CK_BaseToDerivedMemberPointer;
3058   return false;
3059 }
3060 
3061 /// Determine whether the lifetime conversion between the two given
3062 /// qualifiers sets is nontrivial.
3063 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3064                                                Qualifiers ToQuals) {
3065   // Converting anything to const __unsafe_unretained is trivial.
3066   if (ToQuals.hasConst() &&
3067       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3068     return false;
3069 
3070   return true;
3071 }
3072 
3073 /// IsQualificationConversion - Determines whether the conversion from
3074 /// an rvalue of type FromType to ToType is a qualification conversion
3075 /// (C++ 4.4).
3076 ///
3077 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3078 /// when the qualification conversion involves a change in the Objective-C
3079 /// object lifetime.
3080 bool
3081 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3082                                 bool CStyle, bool &ObjCLifetimeConversion) {
3083   FromType = Context.getCanonicalType(FromType);
3084   ToType = Context.getCanonicalType(ToType);
3085   ObjCLifetimeConversion = false;
3086 
3087   // If FromType and ToType are the same type, this is not a
3088   // qualification conversion.
3089   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3090     return false;
3091 
3092   // (C++ 4.4p4):
3093   //   A conversion can add cv-qualifiers at levels other than the first
3094   //   in multi-level pointers, subject to the following rules: [...]
3095   bool PreviousToQualsIncludeConst = true;
3096   bool UnwrappedAnyPointer = false;
3097   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3098     // Within each iteration of the loop, we check the qualifiers to
3099     // determine if this still looks like a qualification
3100     // conversion. Then, if all is well, we unwrap one more level of
3101     // pointers or pointers-to-members and do it all again
3102     // until there are no more pointers or pointers-to-members left to
3103     // unwrap.
3104     UnwrappedAnyPointer = true;
3105 
3106     Qualifiers FromQuals = FromType.getQualifiers();
3107     Qualifiers ToQuals = ToType.getQualifiers();
3108 
3109     // Ignore __unaligned qualifier if this type is void.
3110     if (ToType.getUnqualifiedType()->isVoidType())
3111       FromQuals.removeUnaligned();
3112 
3113     // Objective-C ARC:
3114     //   Check Objective-C lifetime conversions.
3115     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3116         UnwrappedAnyPointer) {
3117       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3118         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3119           ObjCLifetimeConversion = true;
3120         FromQuals.removeObjCLifetime();
3121         ToQuals.removeObjCLifetime();
3122       } else {
3123         // Qualification conversions cannot cast between different
3124         // Objective-C lifetime qualifiers.
3125         return false;
3126       }
3127     }
3128 
3129     // Allow addition/removal of GC attributes but not changing GC attributes.
3130     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3131         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3132       FromQuals.removeObjCGCAttr();
3133       ToQuals.removeObjCGCAttr();
3134     }
3135 
3136     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3137     //      2,j, and similarly for volatile.
3138     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3139       return false;
3140 
3141     //   -- if the cv 1,j and cv 2,j are different, then const is in
3142     //      every cv for 0 < k < j.
3143     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3144         && !PreviousToQualsIncludeConst)
3145       return false;
3146 
3147     // Keep track of whether all prior cv-qualifiers in the "to" type
3148     // include const.
3149     PreviousToQualsIncludeConst
3150       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3151   }
3152 
3153   // Allows address space promotion by language rules implemented in
3154   // Type::Qualifiers::isAddressSpaceSupersetOf.
3155   Qualifiers FromQuals = FromType.getQualifiers();
3156   Qualifiers ToQuals = ToType.getQualifiers();
3157   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3158       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3159     return false;
3160   }
3161 
3162   // We are left with FromType and ToType being the pointee types
3163   // after unwrapping the original FromType and ToType the same number
3164   // of types. If we unwrapped any pointers, and if FromType and
3165   // ToType have the same unqualified type (since we checked
3166   // qualifiers above), then this is a qualification conversion.
3167   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3168 }
3169 
3170 /// - Determine whether this is a conversion from a scalar type to an
3171 /// atomic type.
3172 ///
3173 /// If successful, updates \c SCS's second and third steps in the conversion
3174 /// sequence to finish the conversion.
3175 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3176                                 bool InOverloadResolution,
3177                                 StandardConversionSequence &SCS,
3178                                 bool CStyle) {
3179   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3180   if (!ToAtomic)
3181     return false;
3182 
3183   StandardConversionSequence InnerSCS;
3184   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3185                             InOverloadResolution, InnerSCS,
3186                             CStyle, /*AllowObjCWritebackConversion=*/false))
3187     return false;
3188 
3189   SCS.Second = InnerSCS.Second;
3190   SCS.setToType(1, InnerSCS.getToType(1));
3191   SCS.Third = InnerSCS.Third;
3192   SCS.QualificationIncludesObjCLifetime
3193     = InnerSCS.QualificationIncludesObjCLifetime;
3194   SCS.setToType(2, InnerSCS.getToType(2));
3195   return true;
3196 }
3197 
3198 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3199                                               CXXConstructorDecl *Constructor,
3200                                               QualType Type) {
3201   const FunctionProtoType *CtorType =
3202       Constructor->getType()->getAs<FunctionProtoType>();
3203   if (CtorType->getNumParams() > 0) {
3204     QualType FirstArg = CtorType->getParamType(0);
3205     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3206       return true;
3207   }
3208   return false;
3209 }
3210 
3211 static OverloadingResult
3212 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3213                                        CXXRecordDecl *To,
3214                                        UserDefinedConversionSequence &User,
3215                                        OverloadCandidateSet &CandidateSet,
3216                                        bool AllowExplicit) {
3217   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3218   for (auto *D : S.LookupConstructors(To)) {
3219     auto Info = getConstructorInfo(D);
3220     if (!Info)
3221       continue;
3222 
3223     bool Usable = !Info.Constructor->isInvalidDecl() &&
3224                   S.isInitListConstructor(Info.Constructor) &&
3225                   (AllowExplicit || !Info.Constructor->isExplicit());
3226     if (Usable) {
3227       // If the first argument is (a reference to) the target type,
3228       // suppress conversions.
3229       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3230           S.Context, Info.Constructor, ToType);
3231       if (Info.ConstructorTmpl)
3232         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3233                                        /*ExplicitArgs*/ nullptr, From,
3234                                        CandidateSet, SuppressUserConversions);
3235       else
3236         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3237                                CandidateSet, SuppressUserConversions);
3238     }
3239   }
3240 
3241   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3242 
3243   OverloadCandidateSet::iterator Best;
3244   switch (auto Result =
3245             CandidateSet.BestViableFunction(S, From->getLocStart(),
3246                                             Best)) {
3247   case OR_Deleted:
3248   case OR_Success: {
3249     // Record the standard conversion we used and the conversion function.
3250     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3251     QualType ThisType = Constructor->getThisType(S.Context);
3252     // Initializer lists don't have conversions as such.
3253     User.Before.setAsIdentityConversion();
3254     User.HadMultipleCandidates = HadMultipleCandidates;
3255     User.ConversionFunction = Constructor;
3256     User.FoundConversionFunction = Best->FoundDecl;
3257     User.After.setAsIdentityConversion();
3258     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259     User.After.setAllToTypes(ToType);
3260     return Result;
3261   }
3262 
3263   case OR_No_Viable_Function:
3264     return OR_No_Viable_Function;
3265   case OR_Ambiguous:
3266     return OR_Ambiguous;
3267   }
3268 
3269   llvm_unreachable("Invalid OverloadResult!");
3270 }
3271 
3272 /// Determines whether there is a user-defined conversion sequence
3273 /// (C++ [over.ics.user]) that converts expression From to the type
3274 /// ToType. If such a conversion exists, User will contain the
3275 /// user-defined conversion sequence that performs such a conversion
3276 /// and this routine will return true. Otherwise, this routine returns
3277 /// false and User is unspecified.
3278 ///
3279 /// \param AllowExplicit  true if the conversion should consider C++0x
3280 /// "explicit" conversion functions as well as non-explicit conversion
3281 /// functions (C++0x [class.conv.fct]p2).
3282 ///
3283 /// \param AllowObjCConversionOnExplicit true if the conversion should
3284 /// allow an extra Objective-C pointer conversion on uses of explicit
3285 /// constructors. Requires \c AllowExplicit to also be set.
3286 static OverloadingResult
3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3288                         UserDefinedConversionSequence &User,
3289                         OverloadCandidateSet &CandidateSet,
3290                         bool AllowExplicit,
3291                         bool AllowObjCConversionOnExplicit) {
3292   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3293   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294 
3295   // Whether we will only visit constructors.
3296   bool ConstructorsOnly = false;
3297 
3298   // If the type we are conversion to is a class type, enumerate its
3299   // constructors.
3300   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3301     // C++ [over.match.ctor]p1:
3302     //   When objects of class type are direct-initialized (8.5), or
3303     //   copy-initialized from an expression of the same or a
3304     //   derived class type (8.5), overload resolution selects the
3305     //   constructor. [...] For copy-initialization, the candidate
3306     //   functions are all the converting constructors (12.3.1) of
3307     //   that class. The argument list is the expression-list within
3308     //   the parentheses of the initializer.
3309     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3310         (From->getType()->getAs<RecordType>() &&
3311          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3312       ConstructorsOnly = true;
3313 
3314     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3315       // We're not going to find any constructors.
3316     } else if (CXXRecordDecl *ToRecordDecl
3317                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3318 
3319       Expr **Args = &From;
3320       unsigned NumArgs = 1;
3321       bool ListInitializing = false;
3322       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3323         // But first, see if there is an init-list-constructor that will work.
3324         OverloadingResult Result = IsInitializerListConstructorConversion(
3325             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326         if (Result != OR_No_Viable_Function)
3327           return Result;
3328         // Never mind.
3329         CandidateSet.clear(
3330             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331 
3332         // If we're list-initializing, we pass the individual elements as
3333         // arguments, not the entire list.
3334         Args = InitList->getInits();
3335         NumArgs = InitList->getNumInits();
3336         ListInitializing = true;
3337       }
3338 
3339       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340         auto Info = getConstructorInfo(D);
3341         if (!Info)
3342           continue;
3343 
3344         bool Usable = !Info.Constructor->isInvalidDecl();
3345         if (ListInitializing)
3346           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3347         else
3348           Usable = Usable &&
3349                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3350         if (Usable) {
3351           bool SuppressUserConversions = !ConstructorsOnly;
3352           if (SuppressUserConversions && ListInitializing) {
3353             SuppressUserConversions = false;
3354             if (NumArgs == 1) {
3355               // If the first argument is (a reference to) the target type,
3356               // suppress conversions.
3357               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3358                   S.Context, Info.Constructor, ToType);
3359             }
3360           }
3361           if (Info.ConstructorTmpl)
3362             S.AddTemplateOverloadCandidate(
3363                 Info.ConstructorTmpl, Info.FoundDecl,
3364                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365                 CandidateSet, SuppressUserConversions);
3366           else
3367             // Allow one user-defined conversion when user specifies a
3368             // From->ToType conversion via an static cast (c-style, etc).
3369             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3370                                    llvm::makeArrayRef(Args, NumArgs),
3371                                    CandidateSet, SuppressUserConversions);
3372         }
3373       }
3374     }
3375   }
3376 
3377   // Enumerate conversion functions, if we're allowed to.
3378   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3379   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3380     // No conversion functions from incomplete types.
3381   } else if (const RecordType *FromRecordType
3382                                    = From->getType()->getAs<RecordType>()) {
3383     if (CXXRecordDecl *FromRecordDecl
3384          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385       // Add all of the conversion functions as candidates.
3386       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3388         DeclAccessPair FoundDecl = I.getPair();
3389         NamedDecl *D = FoundDecl.getDecl();
3390         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391         if (isa<UsingShadowDecl>(D))
3392           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393 
3394         CXXConversionDecl *Conv;
3395         FunctionTemplateDecl *ConvTemplate;
3396         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3398         else
3399           Conv = cast<CXXConversionDecl>(D);
3400 
3401         if (AllowExplicit || !Conv->isExplicit()) {
3402           if (ConvTemplate)
3403             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404                                              ActingContext, From, ToType,
3405                                              CandidateSet,
3406                                              AllowObjCConversionOnExplicit);
3407           else
3408             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3409                                      From, ToType, CandidateSet,
3410                                      AllowObjCConversionOnExplicit);
3411         }
3412       }
3413     }
3414   }
3415 
3416   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417 
3418   OverloadCandidateSet::iterator Best;
3419   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3420                                                         Best)) {
3421   case OR_Success:
3422   case OR_Deleted:
3423     // Record the standard conversion we used and the conversion function.
3424     if (CXXConstructorDecl *Constructor
3425           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426       // C++ [over.ics.user]p1:
3427       //   If the user-defined conversion is specified by a
3428       //   constructor (12.3.1), the initial standard conversion
3429       //   sequence converts the source type to the type required by
3430       //   the argument of the constructor.
3431       //
3432       QualType ThisType = Constructor->getThisType(S.Context);
3433       if (isa<InitListExpr>(From)) {
3434         // Initializer lists don't have conversions as such.
3435         User.Before.setAsIdentityConversion();
3436       } else {
3437         if (Best->Conversions[0].isEllipsis())
3438           User.EllipsisConversion = true;
3439         else {
3440           User.Before = Best->Conversions[0].Standard;
3441           User.EllipsisConversion = false;
3442         }
3443       }
3444       User.HadMultipleCandidates = HadMultipleCandidates;
3445       User.ConversionFunction = Constructor;
3446       User.FoundConversionFunction = Best->FoundDecl;
3447       User.After.setAsIdentityConversion();
3448       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449       User.After.setAllToTypes(ToType);
3450       return Result;
3451     }
3452     if (CXXConversionDecl *Conversion
3453                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454       // C++ [over.ics.user]p1:
3455       //
3456       //   [...] If the user-defined conversion is specified by a
3457       //   conversion function (12.3.2), the initial standard
3458       //   conversion sequence converts the source type to the
3459       //   implicit object parameter of the conversion function.
3460       User.Before = Best->Conversions[0].Standard;
3461       User.HadMultipleCandidates = HadMultipleCandidates;
3462       User.ConversionFunction = Conversion;
3463       User.FoundConversionFunction = Best->FoundDecl;
3464       User.EllipsisConversion = false;
3465 
3466       // C++ [over.ics.user]p2:
3467       //   The second standard conversion sequence converts the
3468       //   result of the user-defined conversion to the target type
3469       //   for the sequence. Since an implicit conversion sequence
3470       //   is an initialization, the special rules for
3471       //   initialization by user-defined conversion apply when
3472       //   selecting the best user-defined conversion for a
3473       //   user-defined conversion sequence (see 13.3.3 and
3474       //   13.3.3.1).
3475       User.After = Best->FinalConversion;
3476       return Result;
3477     }
3478     llvm_unreachable("Not a constructor or conversion function?");
3479 
3480   case OR_No_Viable_Function:
3481     return OR_No_Viable_Function;
3482 
3483   case OR_Ambiguous:
3484     return OR_Ambiguous;
3485   }
3486 
3487   llvm_unreachable("Invalid OverloadResult!");
3488 }
3489 
3490 bool
3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3492   ImplicitConversionSequence ICS;
3493   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494                                     OverloadCandidateSet::CSK_Normal);
3495   OverloadingResult OvResult =
3496     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3497                             CandidateSet, false, false);
3498   if (OvResult == OR_Ambiguous)
3499     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3500         << From->getType() << ToType << From->getSourceRange();
3501   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3502     if (!RequireCompleteType(From->getLocStart(), ToType,
3503                              diag::err_typecheck_nonviable_condition_incomplete,
3504                              From->getType(), From->getSourceRange()))
3505       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3506           << false << From->getType() << From->getSourceRange() << ToType;
3507   } else
3508     return false;
3509   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3510   return true;
3511 }
3512 
3513 /// Compare the user-defined conversion functions or constructors
3514 /// of two user-defined conversion sequences to determine whether any ordering
3515 /// is possible.
3516 static ImplicitConversionSequence::CompareKind
3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3518                            FunctionDecl *Function2) {
3519   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3520     return ImplicitConversionSequence::Indistinguishable;
3521 
3522   // Objective-C++:
3523   //   If both conversion functions are implicitly-declared conversions from
3524   //   a lambda closure type to a function pointer and a block pointer,
3525   //   respectively, always prefer the conversion to a function pointer,
3526   //   because the function pointer is more lightweight and is more likely
3527   //   to keep code working.
3528   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3529   if (!Conv1)
3530     return ImplicitConversionSequence::Indistinguishable;
3531 
3532   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533   if (!Conv2)
3534     return ImplicitConversionSequence::Indistinguishable;
3535 
3536   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539     if (Block1 != Block2)
3540       return Block1 ? ImplicitConversionSequence::Worse
3541                     : ImplicitConversionSequence::Better;
3542   }
3543 
3544   return ImplicitConversionSequence::Indistinguishable;
3545 }
3546 
3547 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548     const ImplicitConversionSequence &ICS) {
3549   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550          (ICS.isUserDefined() &&
3551           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552 }
3553 
3554 /// CompareImplicitConversionSequences - Compare two implicit
3555 /// conversion sequences to determine whether one is better than the
3556 /// other or if they are indistinguishable (C++ 13.3.3.2).
3557 static ImplicitConversionSequence::CompareKind
3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3559                                    const ImplicitConversionSequence& ICS1,
3560                                    const ImplicitConversionSequence& ICS2)
3561 {
3562   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563   // conversion sequences (as defined in 13.3.3.1)
3564   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3565   //      conversion sequence than a user-defined conversion sequence or
3566   //      an ellipsis conversion sequence, and
3567   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568   //      conversion sequence than an ellipsis conversion sequence
3569   //      (13.3.3.1.3).
3570   //
3571   // C++0x [over.best.ics]p10:
3572   //   For the purpose of ranking implicit conversion sequences as
3573   //   described in 13.3.3.2, the ambiguous conversion sequence is
3574   //   treated as a user-defined sequence that is indistinguishable
3575   //   from any other user-defined conversion sequence.
3576 
3577   // String literal to 'char *' conversion has been deprecated in C++03. It has
3578   // been removed from C++11. We still accept this conversion, if it happens at
3579   // the best viable function. Otherwise, this conversion is considered worse
3580   // than ellipsis conversion. Consider this as an extension; this is not in the
3581   // standard. For example:
3582   //
3583   // int &f(...);    // #1
3584   // void f(char*);  // #2
3585   // void g() { int &r = f("foo"); }
3586   //
3587   // In C++03, we pick #2 as the best viable function.
3588   // In C++11, we pick #1 as the best viable function, because ellipsis
3589   // conversion is better than string-literal to char* conversion (since there
3590   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591   // convert arguments, #2 would be the best viable function in C++11.
3592   // If the best viable function has this conversion, a warning will be issued
3593   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594 
3595   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599                ? ImplicitConversionSequence::Worse
3600                : ImplicitConversionSequence::Better;
3601 
3602   if (ICS1.getKindRank() < ICS2.getKindRank())
3603     return ImplicitConversionSequence::Better;
3604   if (ICS2.getKindRank() < ICS1.getKindRank())
3605     return ImplicitConversionSequence::Worse;
3606 
3607   // The following checks require both conversion sequences to be of
3608   // the same kind.
3609   if (ICS1.getKind() != ICS2.getKind())
3610     return ImplicitConversionSequence::Indistinguishable;
3611 
3612   ImplicitConversionSequence::CompareKind Result =
3613       ImplicitConversionSequence::Indistinguishable;
3614 
3615   // Two implicit conversion sequences of the same form are
3616   // indistinguishable conversion sequences unless one of the
3617   // following rules apply: (C++ 13.3.3.2p3):
3618 
3619   // List-initialization sequence L1 is a better conversion sequence than
3620   // list-initialization sequence L2 if:
3621   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622   //   if not that,
3623   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3624   //   and N1 is smaller than N2.,
3625   // even if one of the other rules in this paragraph would otherwise apply.
3626   if (!ICS1.isBad()) {
3627     if (ICS1.isStdInitializerListElement() &&
3628         !ICS2.isStdInitializerListElement())
3629       return ImplicitConversionSequence::Better;
3630     if (!ICS1.isStdInitializerListElement() &&
3631         ICS2.isStdInitializerListElement())
3632       return ImplicitConversionSequence::Worse;
3633   }
3634 
3635   if (ICS1.isStandard())
3636     // Standard conversion sequence S1 is a better conversion sequence than
3637     // standard conversion sequence S2 if [...]
3638     Result = CompareStandardConversionSequences(S, Loc,
3639                                                 ICS1.Standard, ICS2.Standard);
3640   else if (ICS1.isUserDefined()) {
3641     // User-defined conversion sequence U1 is a better conversion
3642     // sequence than another user-defined conversion sequence U2 if
3643     // they contain the same user-defined conversion function or
3644     // constructor and if the second standard conversion sequence of
3645     // U1 is better than the second standard conversion sequence of
3646     // U2 (C++ 13.3.3.2p3).
3647     if (ICS1.UserDefined.ConversionFunction ==
3648           ICS2.UserDefined.ConversionFunction)
3649       Result = CompareStandardConversionSequences(S, Loc,
3650                                                   ICS1.UserDefined.After,
3651                                                   ICS2.UserDefined.After);
3652     else
3653       Result = compareConversionFunctions(S,
3654                                           ICS1.UserDefined.ConversionFunction,
3655                                           ICS2.UserDefined.ConversionFunction);
3656   }
3657 
3658   return Result;
3659 }
3660 
3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3662 // determine if one is a proper subset of the other.
3663 static ImplicitConversionSequence::CompareKind
3664 compareStandardConversionSubsets(ASTContext &Context,
3665                                  const StandardConversionSequence& SCS1,
3666                                  const StandardConversionSequence& SCS2) {
3667   ImplicitConversionSequence::CompareKind Result
3668     = ImplicitConversionSequence::Indistinguishable;
3669 
3670   // the identity conversion sequence is considered to be a subsequence of
3671   // any non-identity conversion sequence
3672   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673     return ImplicitConversionSequence::Better;
3674   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675     return ImplicitConversionSequence::Worse;
3676 
3677   if (SCS1.Second != SCS2.Second) {
3678     if (SCS1.Second == ICK_Identity)
3679       Result = ImplicitConversionSequence::Better;
3680     else if (SCS2.Second == ICK_Identity)
3681       Result = ImplicitConversionSequence::Worse;
3682     else
3683       return ImplicitConversionSequence::Indistinguishable;
3684   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3685     return ImplicitConversionSequence::Indistinguishable;
3686 
3687   if (SCS1.Third == SCS2.Third) {
3688     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689                              : ImplicitConversionSequence::Indistinguishable;
3690   }
3691 
3692   if (SCS1.Third == ICK_Identity)
3693     return Result == ImplicitConversionSequence::Worse
3694              ? ImplicitConversionSequence::Indistinguishable
3695              : ImplicitConversionSequence::Better;
3696 
3697   if (SCS2.Third == ICK_Identity)
3698     return Result == ImplicitConversionSequence::Better
3699              ? ImplicitConversionSequence::Indistinguishable
3700              : ImplicitConversionSequence::Worse;
3701 
3702   return ImplicitConversionSequence::Indistinguishable;
3703 }
3704 
3705 /// Determine whether one of the given reference bindings is better
3706 /// than the other based on what kind of bindings they are.
3707 static bool
3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709                              const StandardConversionSequence &SCS2) {
3710   // C++0x [over.ics.rank]p3b4:
3711   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712   //      implicit object parameter of a non-static member function declared
3713   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3714   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3715   //      lvalue reference to a function lvalue and S2 binds an rvalue
3716   //      reference*.
3717   //
3718   // FIXME: Rvalue references. We're going rogue with the above edits,
3719   // because the semantics in the current C++0x working paper (N3225 at the
3720   // time of this writing) break the standard definition of std::forward
3721   // and std::reference_wrapper when dealing with references to functions.
3722   // Proposed wording changes submitted to CWG for consideration.
3723   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725     return false;
3726 
3727   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728           SCS2.IsLvalueReference) ||
3729          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3730           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3731 }
3732 
3733 /// CompareStandardConversionSequences - Compare two standard
3734 /// conversion sequences to determine whether one is better than the
3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3736 static ImplicitConversionSequence::CompareKind
3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3738                                    const StandardConversionSequence& SCS1,
3739                                    const StandardConversionSequence& SCS2)
3740 {
3741   // Standard conversion sequence S1 is a better conversion sequence
3742   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743 
3744   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3745   //     sequences in the canonical form defined by 13.3.3.1.1,
3746   //     excluding any Lvalue Transformation; the identity conversion
3747   //     sequence is considered to be a subsequence of any
3748   //     non-identity conversion sequence) or, if not that,
3749   if (ImplicitConversionSequence::CompareKind CK
3750         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3751     return CK;
3752 
3753   //  -- the rank of S1 is better than the rank of S2 (by the rules
3754   //     defined below), or, if not that,
3755   ImplicitConversionRank Rank1 = SCS1.getRank();
3756   ImplicitConversionRank Rank2 = SCS2.getRank();
3757   if (Rank1 < Rank2)
3758     return ImplicitConversionSequence::Better;
3759   else if (Rank2 < Rank1)
3760     return ImplicitConversionSequence::Worse;
3761 
3762   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763   // are indistinguishable unless one of the following rules
3764   // applies:
3765 
3766   //   A conversion that is not a conversion of a pointer, or
3767   //   pointer to member, to bool is better than another conversion
3768   //   that is such a conversion.
3769   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770     return SCS2.isPointerConversionToBool()
3771              ? ImplicitConversionSequence::Better
3772              : ImplicitConversionSequence::Worse;
3773 
3774   // C++ [over.ics.rank]p4b2:
3775   //
3776   //   If class B is derived directly or indirectly from class A,
3777   //   conversion of B* to A* is better than conversion of B* to
3778   //   void*, and conversion of A* to void* is better than conversion
3779   //   of B* to void*.
3780   bool SCS1ConvertsToVoid
3781     = SCS1.isPointerConversionToVoidPointer(S.Context);
3782   bool SCS2ConvertsToVoid
3783     = SCS2.isPointerConversionToVoidPointer(S.Context);
3784   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785     // Exactly one of the conversion sequences is a conversion to
3786     // a void pointer; it's the worse conversion.
3787     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788                               : ImplicitConversionSequence::Worse;
3789   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790     // Neither conversion sequence converts to a void pointer; compare
3791     // their derived-to-base conversions.
3792     if (ImplicitConversionSequence::CompareKind DerivedCK
3793           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3794       return DerivedCK;
3795   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3797     // Both conversion sequences are conversions to void
3798     // pointers. Compare the source types to determine if there's an
3799     // inheritance relationship in their sources.
3800     QualType FromType1 = SCS1.getFromType();
3801     QualType FromType2 = SCS2.getFromType();
3802 
3803     // Adjust the types we're converting from via the array-to-pointer
3804     // conversion, if we need to.
3805     if (SCS1.First == ICK_Array_To_Pointer)
3806       FromType1 = S.Context.getArrayDecayedType(FromType1);
3807     if (SCS2.First == ICK_Array_To_Pointer)
3808       FromType2 = S.Context.getArrayDecayedType(FromType2);
3809 
3810     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3812 
3813     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3814       return ImplicitConversionSequence::Better;
3815     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3816       return ImplicitConversionSequence::Worse;
3817 
3818     // Objective-C++: If one interface is more specific than the
3819     // other, it is the better one.
3820     const ObjCObjectPointerType* FromObjCPtr1
3821       = FromType1->getAs<ObjCObjectPointerType>();
3822     const ObjCObjectPointerType* FromObjCPtr2
3823       = FromType2->getAs<ObjCObjectPointerType>();
3824     if (FromObjCPtr1 && FromObjCPtr2) {
3825       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3826                                                           FromObjCPtr2);
3827       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3828                                                            FromObjCPtr1);
3829       if (AssignLeft != AssignRight) {
3830         return AssignLeft? ImplicitConversionSequence::Better
3831                          : ImplicitConversionSequence::Worse;
3832       }
3833     }
3834   }
3835 
3836   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837   // bullet 3).
3838   if (ImplicitConversionSequence::CompareKind QualCK
3839         = CompareQualificationConversions(S, SCS1, SCS2))
3840     return QualCK;
3841 
3842   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3843     // Check for a better reference binding based on the kind of bindings.
3844     if (isBetterReferenceBindingKind(SCS1, SCS2))
3845       return ImplicitConversionSequence::Better;
3846     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847       return ImplicitConversionSequence::Worse;
3848 
3849     // C++ [over.ics.rank]p3b4:
3850     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3851     //      which the references refer are the same type except for
3852     //      top-level cv-qualifiers, and the type to which the reference
3853     //      initialized by S2 refers is more cv-qualified than the type
3854     //      to which the reference initialized by S1 refers.
3855     QualType T1 = SCS1.getToType(2);
3856     QualType T2 = SCS2.getToType(2);
3857     T1 = S.Context.getCanonicalType(T1);
3858     T2 = S.Context.getCanonicalType(T2);
3859     Qualifiers T1Quals, T2Quals;
3860     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3862     if (UnqualT1 == UnqualT2) {
3863       // Objective-C++ ARC: If the references refer to objects with different
3864       // lifetimes, prefer bindings that don't change lifetime.
3865       if (SCS1.ObjCLifetimeConversionBinding !=
3866                                           SCS2.ObjCLifetimeConversionBinding) {
3867         return SCS1.ObjCLifetimeConversionBinding
3868                                            ? ImplicitConversionSequence::Worse
3869                                            : ImplicitConversionSequence::Better;
3870       }
3871 
3872       // If the type is an array type, promote the element qualifiers to the
3873       // type for comparison.
3874       if (isa<ArrayType>(T1) && T1Quals)
3875         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3876       if (isa<ArrayType>(T2) && T2Quals)
3877         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3878       if (T2.isMoreQualifiedThan(T1))
3879         return ImplicitConversionSequence::Better;
3880       else if (T1.isMoreQualifiedThan(T2))
3881         return ImplicitConversionSequence::Worse;
3882     }
3883   }
3884 
3885   // In Microsoft mode, prefer an integral conversion to a
3886   // floating-to-integral conversion if the integral conversion
3887   // is between types of the same size.
3888   // For example:
3889   // void f(float);
3890   // void f(int);
3891   // int main {
3892   //    long a;
3893   //    f(a);
3894   // }
3895   // Here, MSVC will call f(int) instead of generating a compile error
3896   // as clang will do in standard mode.
3897   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898       SCS2.Second == ICK_Floating_Integral &&
3899       S.Context.getTypeSize(SCS1.getFromType()) ==
3900           S.Context.getTypeSize(SCS1.getToType(2)))
3901     return ImplicitConversionSequence::Better;
3902 
3903   return ImplicitConversionSequence::Indistinguishable;
3904 }
3905 
3906 /// CompareQualificationConversions - Compares two standard conversion
3907 /// sequences to determine whether they can be ranked based on their
3908 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3909 static ImplicitConversionSequence::CompareKind
3910 CompareQualificationConversions(Sema &S,
3911                                 const StandardConversionSequence& SCS1,
3912                                 const StandardConversionSequence& SCS2) {
3913   // C++ 13.3.3.2p3:
3914   //  -- S1 and S2 differ only in their qualification conversion and
3915   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3916   //     cv-qualification signature of type T1 is a proper subset of
3917   //     the cv-qualification signature of type T2, and S1 is not the
3918   //     deprecated string literal array-to-pointer conversion (4.2).
3919   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3920       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3921     return ImplicitConversionSequence::Indistinguishable;
3922 
3923   // FIXME: the example in the standard doesn't use a qualification
3924   // conversion (!)
3925   QualType T1 = SCS1.getToType(2);
3926   QualType T2 = SCS2.getToType(2);
3927   T1 = S.Context.getCanonicalType(T1);
3928   T2 = S.Context.getCanonicalType(T2);
3929   Qualifiers T1Quals, T2Quals;
3930   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3931   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3932 
3933   // If the types are the same, we won't learn anything by unwrapped
3934   // them.
3935   if (UnqualT1 == UnqualT2)
3936     return ImplicitConversionSequence::Indistinguishable;
3937 
3938   // If the type is an array type, promote the element qualifiers to the type
3939   // for comparison.
3940   if (isa<ArrayType>(T1) && T1Quals)
3941     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3942   if (isa<ArrayType>(T2) && T2Quals)
3943     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3944 
3945   ImplicitConversionSequence::CompareKind Result
3946     = ImplicitConversionSequence::Indistinguishable;
3947 
3948   // Objective-C++ ARC:
3949   //   Prefer qualification conversions not involving a change in lifetime
3950   //   to qualification conversions that do not change lifetime.
3951   if (SCS1.QualificationIncludesObjCLifetime !=
3952                                       SCS2.QualificationIncludesObjCLifetime) {
3953     Result = SCS1.QualificationIncludesObjCLifetime
3954                ? ImplicitConversionSequence::Worse
3955                : ImplicitConversionSequence::Better;
3956   }
3957 
3958   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3959     // Within each iteration of the loop, we check the qualifiers to
3960     // determine if this still looks like a qualification
3961     // conversion. Then, if all is well, we unwrap one more level of
3962     // pointers or pointers-to-members and do it all again
3963     // until there are no more pointers or pointers-to-members left
3964     // to unwrap. This essentially mimics what
3965     // IsQualificationConversion does, but here we're checking for a
3966     // strict subset of qualifiers.
3967     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3968       // The qualifiers are the same, so this doesn't tell us anything
3969       // about how the sequences rank.
3970       ;
3971     else if (T2.isMoreQualifiedThan(T1)) {
3972       // T1 has fewer qualifiers, so it could be the better sequence.
3973       if (Result == ImplicitConversionSequence::Worse)
3974         // Neither has qualifiers that are a subset of the other's
3975         // qualifiers.
3976         return ImplicitConversionSequence::Indistinguishable;
3977 
3978       Result = ImplicitConversionSequence::Better;
3979     } else if (T1.isMoreQualifiedThan(T2)) {
3980       // T2 has fewer qualifiers, so it could be the better sequence.
3981       if (Result == ImplicitConversionSequence::Better)
3982         // Neither has qualifiers that are a subset of the other's
3983         // qualifiers.
3984         return ImplicitConversionSequence::Indistinguishable;
3985 
3986       Result = ImplicitConversionSequence::Worse;
3987     } else {
3988       // Qualifiers are disjoint.
3989       return ImplicitConversionSequence::Indistinguishable;
3990     }
3991 
3992     // If the types after this point are equivalent, we're done.
3993     if (S.Context.hasSameUnqualifiedType(T1, T2))
3994       break;
3995   }
3996 
3997   // Check that the winning standard conversion sequence isn't using
3998   // the deprecated string literal array to pointer conversion.
3999   switch (Result) {
4000   case ImplicitConversionSequence::Better:
4001     if (SCS1.DeprecatedStringLiteralToCharPtr)
4002       Result = ImplicitConversionSequence::Indistinguishable;
4003     break;
4004 
4005   case ImplicitConversionSequence::Indistinguishable:
4006     break;
4007 
4008   case ImplicitConversionSequence::Worse:
4009     if (SCS2.DeprecatedStringLiteralToCharPtr)
4010       Result = ImplicitConversionSequence::Indistinguishable;
4011     break;
4012   }
4013 
4014   return Result;
4015 }
4016 
4017 /// CompareDerivedToBaseConversions - Compares two standard conversion
4018 /// sequences to determine whether they can be ranked based on their
4019 /// various kinds of derived-to-base conversions (C++
4020 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4021 /// conversions between Objective-C interface types.
4022 static ImplicitConversionSequence::CompareKind
4023 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4024                                 const StandardConversionSequence& SCS1,
4025                                 const StandardConversionSequence& SCS2) {
4026   QualType FromType1 = SCS1.getFromType();
4027   QualType ToType1 = SCS1.getToType(1);
4028   QualType FromType2 = SCS2.getFromType();
4029   QualType ToType2 = SCS2.getToType(1);
4030 
4031   // Adjust the types we're converting from via the array-to-pointer
4032   // conversion, if we need to.
4033   if (SCS1.First == ICK_Array_To_Pointer)
4034     FromType1 = S.Context.getArrayDecayedType(FromType1);
4035   if (SCS2.First == ICK_Array_To_Pointer)
4036     FromType2 = S.Context.getArrayDecayedType(FromType2);
4037 
4038   // Canonicalize all of the types.
4039   FromType1 = S.Context.getCanonicalType(FromType1);
4040   ToType1 = S.Context.getCanonicalType(ToType1);
4041   FromType2 = S.Context.getCanonicalType(FromType2);
4042   ToType2 = S.Context.getCanonicalType(ToType2);
4043 
4044   // C++ [over.ics.rank]p4b3:
4045   //
4046   //   If class B is derived directly or indirectly from class A and
4047   //   class C is derived directly or indirectly from B,
4048   //
4049   // Compare based on pointer conversions.
4050   if (SCS1.Second == ICK_Pointer_Conversion &&
4051       SCS2.Second == ICK_Pointer_Conversion &&
4052       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4053       FromType1->isPointerType() && FromType2->isPointerType() &&
4054       ToType1->isPointerType() && ToType2->isPointerType()) {
4055     QualType FromPointee1
4056       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4057     QualType ToPointee1
4058       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4059     QualType FromPointee2
4060       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4061     QualType ToPointee2
4062       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4063 
4064     //   -- conversion of C* to B* is better than conversion of C* to A*,
4065     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4066       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4067         return ImplicitConversionSequence::Better;
4068       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4069         return ImplicitConversionSequence::Worse;
4070     }
4071 
4072     //   -- conversion of B* to A* is better than conversion of C* to A*,
4073     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4074       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4075         return ImplicitConversionSequence::Better;
4076       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4077         return ImplicitConversionSequence::Worse;
4078     }
4079   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4080              SCS2.Second == ICK_Pointer_Conversion) {
4081     const ObjCObjectPointerType *FromPtr1
4082       = FromType1->getAs<ObjCObjectPointerType>();
4083     const ObjCObjectPointerType *FromPtr2
4084       = FromType2->getAs<ObjCObjectPointerType>();
4085     const ObjCObjectPointerType *ToPtr1
4086       = ToType1->getAs<ObjCObjectPointerType>();
4087     const ObjCObjectPointerType *ToPtr2
4088       = ToType2->getAs<ObjCObjectPointerType>();
4089 
4090     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4091       // Apply the same conversion ranking rules for Objective-C pointer types
4092       // that we do for C++ pointers to class types. However, we employ the
4093       // Objective-C pseudo-subtyping relationship used for assignment of
4094       // Objective-C pointer types.
4095       bool FromAssignLeft
4096         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4097       bool FromAssignRight
4098         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4099       bool ToAssignLeft
4100         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4101       bool ToAssignRight
4102         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4103 
4104       // A conversion to an a non-id object pointer type or qualified 'id'
4105       // type is better than a conversion to 'id'.
4106       if (ToPtr1->isObjCIdType() &&
4107           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4108         return ImplicitConversionSequence::Worse;
4109       if (ToPtr2->isObjCIdType() &&
4110           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4111         return ImplicitConversionSequence::Better;
4112 
4113       // A conversion to a non-id object pointer type is better than a
4114       // conversion to a qualified 'id' type
4115       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4116         return ImplicitConversionSequence::Worse;
4117       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4118         return ImplicitConversionSequence::Better;
4119 
4120       // A conversion to an a non-Class object pointer type or qualified 'Class'
4121       // type is better than a conversion to 'Class'.
4122       if (ToPtr1->isObjCClassType() &&
4123           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4124         return ImplicitConversionSequence::Worse;
4125       if (ToPtr2->isObjCClassType() &&
4126           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4127         return ImplicitConversionSequence::Better;
4128 
4129       // A conversion to a non-Class object pointer type is better than a
4130       // conversion to a qualified 'Class' type.
4131       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4132         return ImplicitConversionSequence::Worse;
4133       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4134         return ImplicitConversionSequence::Better;
4135 
4136       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4137       if (S.Context.hasSameType(FromType1, FromType2) &&
4138           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4139           (ToAssignLeft != ToAssignRight)) {
4140         if (FromPtr1->isSpecialized()) {
4141           // "conversion of B<A> * to B * is better than conversion of B * to
4142           // C *.
4143           bool IsFirstSame =
4144               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4145           bool IsSecondSame =
4146               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4147           if (IsFirstSame) {
4148             if (!IsSecondSame)
4149               return ImplicitConversionSequence::Better;
4150           } else if (IsSecondSame)
4151             return ImplicitConversionSequence::Worse;
4152         }
4153         return ToAssignLeft? ImplicitConversionSequence::Worse
4154                            : ImplicitConversionSequence::Better;
4155       }
4156 
4157       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4158       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4159           (FromAssignLeft != FromAssignRight))
4160         return FromAssignLeft? ImplicitConversionSequence::Better
4161         : ImplicitConversionSequence::Worse;
4162     }
4163   }
4164 
4165   // Ranking of member-pointer types.
4166   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4167       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4168       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4169     const MemberPointerType * FromMemPointer1 =
4170                                         FromType1->getAs<MemberPointerType>();
4171     const MemberPointerType * ToMemPointer1 =
4172                                           ToType1->getAs<MemberPointerType>();
4173     const MemberPointerType * FromMemPointer2 =
4174                                           FromType2->getAs<MemberPointerType>();
4175     const MemberPointerType * ToMemPointer2 =
4176                                           ToType2->getAs<MemberPointerType>();
4177     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4178     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4179     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4180     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4181     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4182     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4183     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4184     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4185     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4186     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4187       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4188         return ImplicitConversionSequence::Worse;
4189       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4190         return ImplicitConversionSequence::Better;
4191     }
4192     // conversion of B::* to C::* is better than conversion of A::* to C::*
4193     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4194       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4195         return ImplicitConversionSequence::Better;
4196       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4197         return ImplicitConversionSequence::Worse;
4198     }
4199   }
4200 
4201   if (SCS1.Second == ICK_Derived_To_Base) {
4202     //   -- conversion of C to B is better than conversion of C to A,
4203     //   -- binding of an expression of type C to a reference of type
4204     //      B& is better than binding an expression of type C to a
4205     //      reference of type A&,
4206     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4207         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4208       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4209         return ImplicitConversionSequence::Better;
4210       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4211         return ImplicitConversionSequence::Worse;
4212     }
4213 
4214     //   -- conversion of B to A is better than conversion of C to A.
4215     //   -- binding of an expression of type B to a reference of type
4216     //      A& is better than binding an expression of type C to a
4217     //      reference of type A&,
4218     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4219         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4220       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4221         return ImplicitConversionSequence::Better;
4222       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4223         return ImplicitConversionSequence::Worse;
4224     }
4225   }
4226 
4227   return ImplicitConversionSequence::Indistinguishable;
4228 }
4229 
4230 /// Determine whether the given type is valid, e.g., it is not an invalid
4231 /// C++ class.
4232 static bool isTypeValid(QualType T) {
4233   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4234     return !Record->isInvalidDecl();
4235 
4236   return true;
4237 }
4238 
4239 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4240 /// determine whether they are reference-related,
4241 /// reference-compatible, reference-compatible with added
4242 /// qualification, or incompatible, for use in C++ initialization by
4243 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4244 /// type, and the first type (T1) is the pointee type of the reference
4245 /// type being initialized.
4246 Sema::ReferenceCompareResult
4247 Sema::CompareReferenceRelationship(SourceLocation Loc,
4248                                    QualType OrigT1, QualType OrigT2,
4249                                    bool &DerivedToBase,
4250                                    bool &ObjCConversion,
4251                                    bool &ObjCLifetimeConversion) {
4252   assert(!OrigT1->isReferenceType() &&
4253     "T1 must be the pointee type of the reference type");
4254   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4255 
4256   QualType T1 = Context.getCanonicalType(OrigT1);
4257   QualType T2 = Context.getCanonicalType(OrigT2);
4258   Qualifiers T1Quals, T2Quals;
4259   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261 
4262   // C++ [dcl.init.ref]p4:
4263   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4265   //   T1 is a base class of T2.
4266   DerivedToBase = false;
4267   ObjCConversion = false;
4268   ObjCLifetimeConversion = false;
4269   QualType ConvertedT2;
4270   if (UnqualT1 == UnqualT2) {
4271     // Nothing to do.
4272   } else if (isCompleteType(Loc, OrigT2) &&
4273              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4274              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4275     DerivedToBase = true;
4276   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4277            UnqualT2->isObjCObjectOrInterfaceType() &&
4278            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4279     ObjCConversion = true;
4280   else if (UnqualT2->isFunctionType() &&
4281            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4282     // C++1z [dcl.init.ref]p4:
4283     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4284     //   function" and T1 is "function"
4285     //
4286     // We extend this to also apply to 'noreturn', so allow any function
4287     // conversion between function types.
4288     return Ref_Compatible;
4289   else
4290     return Ref_Incompatible;
4291 
4292   // At this point, we know that T1 and T2 are reference-related (at
4293   // least).
4294 
4295   // If the type is an array type, promote the element qualifiers to the type
4296   // for comparison.
4297   if (isa<ArrayType>(T1) && T1Quals)
4298     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299   if (isa<ArrayType>(T2) && T2Quals)
4300     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301 
4302   // C++ [dcl.init.ref]p4:
4303   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4304   //   reference-related to T2 and cv1 is the same cv-qualification
4305   //   as, or greater cv-qualification than, cv2. For purposes of
4306   //   overload resolution, cases for which cv1 is greater
4307   //   cv-qualification than cv2 are identified as
4308   //   reference-compatible with added qualification (see 13.3.3.2).
4309   //
4310   // Note that we also require equivalence of Objective-C GC and address-space
4311   // qualifiers when performing these computations, so that e.g., an int in
4312   // address space 1 is not reference-compatible with an int in address
4313   // space 2.
4314   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4315       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4316     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4317       ObjCLifetimeConversion = true;
4318 
4319     T1Quals.removeObjCLifetime();
4320     T2Quals.removeObjCLifetime();
4321   }
4322 
4323   // MS compiler ignores __unaligned qualifier for references; do the same.
4324   T1Quals.removeUnaligned();
4325   T2Quals.removeUnaligned();
4326 
4327   if (T1Quals.compatiblyIncludes(T2Quals))
4328     return Ref_Compatible;
4329   else
4330     return Ref_Related;
4331 }
4332 
4333 /// Look for a user-defined conversion to a value reference-compatible
4334 ///        with DeclType. Return true if something definite is found.
4335 static bool
4336 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4337                          QualType DeclType, SourceLocation DeclLoc,
4338                          Expr *Init, QualType T2, bool AllowRvalues,
4339                          bool AllowExplicit) {
4340   assert(T2->isRecordType() && "Can only find conversions of record types.");
4341   CXXRecordDecl *T2RecordDecl
4342     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4343 
4344   OverloadCandidateSet CandidateSet(
4345       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4346   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4347   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4348     NamedDecl *D = *I;
4349     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4350     if (isa<UsingShadowDecl>(D))
4351       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4352 
4353     FunctionTemplateDecl *ConvTemplate
4354       = dyn_cast<FunctionTemplateDecl>(D);
4355     CXXConversionDecl *Conv;
4356     if (ConvTemplate)
4357       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4358     else
4359       Conv = cast<CXXConversionDecl>(D);
4360 
4361     // If this is an explicit conversion, and we're not allowed to consider
4362     // explicit conversions, skip it.
4363     if (!AllowExplicit && Conv->isExplicit())
4364       continue;
4365 
4366     if (AllowRvalues) {
4367       bool DerivedToBase = false;
4368       bool ObjCConversion = false;
4369       bool ObjCLifetimeConversion = false;
4370 
4371       // If we are initializing an rvalue reference, don't permit conversion
4372       // functions that return lvalues.
4373       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4374         const ReferenceType *RefType
4375           = Conv->getConversionType()->getAs<LValueReferenceType>();
4376         if (RefType && !RefType->getPointeeType()->isFunctionType())
4377           continue;
4378       }
4379 
4380       if (!ConvTemplate &&
4381           S.CompareReferenceRelationship(
4382             DeclLoc,
4383             Conv->getConversionType().getNonReferenceType()
4384               .getUnqualifiedType(),
4385             DeclType.getNonReferenceType().getUnqualifiedType(),
4386             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4387           Sema::Ref_Incompatible)
4388         continue;
4389     } else {
4390       // If the conversion function doesn't return a reference type,
4391       // it can't be considered for this conversion. An rvalue reference
4392       // is only acceptable if its referencee is a function type.
4393 
4394       const ReferenceType *RefType =
4395         Conv->getConversionType()->getAs<ReferenceType>();
4396       if (!RefType ||
4397           (!RefType->isLValueReferenceType() &&
4398            !RefType->getPointeeType()->isFunctionType()))
4399         continue;
4400     }
4401 
4402     if (ConvTemplate)
4403       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4404                                        Init, DeclType, CandidateSet,
4405                                        /*AllowObjCConversionOnExplicit=*/false);
4406     else
4407       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4408                                DeclType, CandidateSet,
4409                                /*AllowObjCConversionOnExplicit=*/false);
4410   }
4411 
4412   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4413 
4414   OverloadCandidateSet::iterator Best;
4415   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4416   case OR_Success:
4417     // C++ [over.ics.ref]p1:
4418     //
4419     //   [...] If the parameter binds directly to the result of
4420     //   applying a conversion function to the argument
4421     //   expression, the implicit conversion sequence is a
4422     //   user-defined conversion sequence (13.3.3.1.2), with the
4423     //   second standard conversion sequence either an identity
4424     //   conversion or, if the conversion function returns an
4425     //   entity of a type that is a derived class of the parameter
4426     //   type, a derived-to-base Conversion.
4427     if (!Best->FinalConversion.DirectBinding)
4428       return false;
4429 
4430     ICS.setUserDefined();
4431     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4432     ICS.UserDefined.After = Best->FinalConversion;
4433     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4434     ICS.UserDefined.ConversionFunction = Best->Function;
4435     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4436     ICS.UserDefined.EllipsisConversion = false;
4437     assert(ICS.UserDefined.After.ReferenceBinding &&
4438            ICS.UserDefined.After.DirectBinding &&
4439            "Expected a direct reference binding!");
4440     return true;
4441 
4442   case OR_Ambiguous:
4443     ICS.setAmbiguous();
4444     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4445          Cand != CandidateSet.end(); ++Cand)
4446       if (Cand->Viable)
4447         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4448     return true;
4449 
4450   case OR_No_Viable_Function:
4451   case OR_Deleted:
4452     // There was no suitable conversion, or we found a deleted
4453     // conversion; continue with other checks.
4454     return false;
4455   }
4456 
4457   llvm_unreachable("Invalid OverloadResult!");
4458 }
4459 
4460 /// Compute an implicit conversion sequence for reference
4461 /// initialization.
4462 static ImplicitConversionSequence
4463 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4464                  SourceLocation DeclLoc,
4465                  bool SuppressUserConversions,
4466                  bool AllowExplicit) {
4467   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4468 
4469   // Most paths end in a failed conversion.
4470   ImplicitConversionSequence ICS;
4471   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4472 
4473   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4474   QualType T2 = Init->getType();
4475 
4476   // If the initializer is the address of an overloaded function, try
4477   // to resolve the overloaded function. If all goes well, T2 is the
4478   // type of the resulting function.
4479   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4480     DeclAccessPair Found;
4481     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4482                                                                 false, Found))
4483       T2 = Fn->getType();
4484   }
4485 
4486   // Compute some basic properties of the types and the initializer.
4487   bool isRValRef = DeclType->isRValueReferenceType();
4488   bool DerivedToBase = false;
4489   bool ObjCConversion = false;
4490   bool ObjCLifetimeConversion = false;
4491   Expr::Classification InitCategory = Init->Classify(S.Context);
4492   Sema::ReferenceCompareResult RefRelationship
4493     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4494                                      ObjCConversion, ObjCLifetimeConversion);
4495 
4496 
4497   // C++0x [dcl.init.ref]p5:
4498   //   A reference to type "cv1 T1" is initialized by an expression
4499   //   of type "cv2 T2" as follows:
4500 
4501   //     -- If reference is an lvalue reference and the initializer expression
4502   if (!isRValRef) {
4503     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4504     //        reference-compatible with "cv2 T2," or
4505     //
4506     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4507     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4508       // C++ [over.ics.ref]p1:
4509       //   When a parameter of reference type binds directly (8.5.3)
4510       //   to an argument expression, the implicit conversion sequence
4511       //   is the identity conversion, unless the argument expression
4512       //   has a type that is a derived class of the parameter type,
4513       //   in which case the implicit conversion sequence is a
4514       //   derived-to-base Conversion (13.3.3.1).
4515       ICS.setStandard();
4516       ICS.Standard.First = ICK_Identity;
4517       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4518                          : ObjCConversion? ICK_Compatible_Conversion
4519                          : ICK_Identity;
4520       ICS.Standard.Third = ICK_Identity;
4521       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4522       ICS.Standard.setToType(0, T2);
4523       ICS.Standard.setToType(1, T1);
4524       ICS.Standard.setToType(2, T1);
4525       ICS.Standard.ReferenceBinding = true;
4526       ICS.Standard.DirectBinding = true;
4527       ICS.Standard.IsLvalueReference = !isRValRef;
4528       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4529       ICS.Standard.BindsToRvalue = false;
4530       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4531       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4532       ICS.Standard.CopyConstructor = nullptr;
4533       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4534 
4535       // Nothing more to do: the inaccessibility/ambiguity check for
4536       // derived-to-base conversions is suppressed when we're
4537       // computing the implicit conversion sequence (C++
4538       // [over.best.ics]p2).
4539       return ICS;
4540     }
4541 
4542     //       -- has a class type (i.e., T2 is a class type), where T1 is
4543     //          not reference-related to T2, and can be implicitly
4544     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4545     //          is reference-compatible with "cv3 T3" 92) (this
4546     //          conversion is selected by enumerating the applicable
4547     //          conversion functions (13.3.1.6) and choosing the best
4548     //          one through overload resolution (13.3)),
4549     if (!SuppressUserConversions && T2->isRecordType() &&
4550         S.isCompleteType(DeclLoc, T2) &&
4551         RefRelationship == Sema::Ref_Incompatible) {
4552       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4553                                    Init, T2, /*AllowRvalues=*/false,
4554                                    AllowExplicit))
4555         return ICS;
4556     }
4557   }
4558 
4559   //     -- Otherwise, the reference shall be an lvalue reference to a
4560   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4561   //        shall be an rvalue reference.
4562   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4563     return ICS;
4564 
4565   //       -- If the initializer expression
4566   //
4567   //            -- is an xvalue, class prvalue, array prvalue or function
4568   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4569   if (RefRelationship == Sema::Ref_Compatible &&
4570       (InitCategory.isXValue() ||
4571        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4572        (InitCategory.isLValue() && T2->isFunctionType()))) {
4573     ICS.setStandard();
4574     ICS.Standard.First = ICK_Identity;
4575     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4576                       : ObjCConversion? ICK_Compatible_Conversion
4577                       : ICK_Identity;
4578     ICS.Standard.Third = ICK_Identity;
4579     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4580     ICS.Standard.setToType(0, T2);
4581     ICS.Standard.setToType(1, T1);
4582     ICS.Standard.setToType(2, T1);
4583     ICS.Standard.ReferenceBinding = true;
4584     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4585     // binding unless we're binding to a class prvalue.
4586     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4587     // allow the use of rvalue references in C++98/03 for the benefit of
4588     // standard library implementors; therefore, we need the xvalue check here.
4589     ICS.Standard.DirectBinding =
4590       S.getLangOpts().CPlusPlus11 ||
4591       !(InitCategory.isPRValue() || T2->isRecordType());
4592     ICS.Standard.IsLvalueReference = !isRValRef;
4593     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4594     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4595     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4596     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4597     ICS.Standard.CopyConstructor = nullptr;
4598     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4599     return ICS;
4600   }
4601 
4602   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4603   //               reference-related to T2, and can be implicitly converted to
4604   //               an xvalue, class prvalue, or function lvalue of type
4605   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4606   //               "cv3 T3",
4607   //
4608   //          then the reference is bound to the value of the initializer
4609   //          expression in the first case and to the result of the conversion
4610   //          in the second case (or, in either case, to an appropriate base
4611   //          class subobject).
4612   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4613       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4614       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4615                                Init, T2, /*AllowRvalues=*/true,
4616                                AllowExplicit)) {
4617     // In the second case, if the reference is an rvalue reference
4618     // and the second standard conversion sequence of the
4619     // user-defined conversion sequence includes an lvalue-to-rvalue
4620     // conversion, the program is ill-formed.
4621     if (ICS.isUserDefined() && isRValRef &&
4622         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4623       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4624 
4625     return ICS;
4626   }
4627 
4628   // A temporary of function type cannot be created; don't even try.
4629   if (T1->isFunctionType())
4630     return ICS;
4631 
4632   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4633   //          initialized from the initializer expression using the
4634   //          rules for a non-reference copy initialization (8.5). The
4635   //          reference is then bound to the temporary. If T1 is
4636   //          reference-related to T2, cv1 must be the same
4637   //          cv-qualification as, or greater cv-qualification than,
4638   //          cv2; otherwise, the program is ill-formed.
4639   if (RefRelationship == Sema::Ref_Related) {
4640     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4641     // we would be reference-compatible or reference-compatible with
4642     // added qualification. But that wasn't the case, so the reference
4643     // initialization fails.
4644     //
4645     // Note that we only want to check address spaces and cvr-qualifiers here.
4646     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4647     Qualifiers T1Quals = T1.getQualifiers();
4648     Qualifiers T2Quals = T2.getQualifiers();
4649     T1Quals.removeObjCGCAttr();
4650     T1Quals.removeObjCLifetime();
4651     T2Quals.removeObjCGCAttr();
4652     T2Quals.removeObjCLifetime();
4653     // MS compiler ignores __unaligned qualifier for references; do the same.
4654     T1Quals.removeUnaligned();
4655     T2Quals.removeUnaligned();
4656     if (!T1Quals.compatiblyIncludes(T2Quals))
4657       return ICS;
4658   }
4659 
4660   // If at least one of the types is a class type, the types are not
4661   // related, and we aren't allowed any user conversions, the
4662   // reference binding fails. This case is important for breaking
4663   // recursion, since TryImplicitConversion below will attempt to
4664   // create a temporary through the use of a copy constructor.
4665   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666       (T1->isRecordType() || T2->isRecordType()))
4667     return ICS;
4668 
4669   // If T1 is reference-related to T2 and the reference is an rvalue
4670   // reference, the initializer expression shall not be an lvalue.
4671   if (RefRelationship >= Sema::Ref_Related &&
4672       isRValRef && Init->Classify(S.Context).isLValue())
4673     return ICS;
4674 
4675   // C++ [over.ics.ref]p2:
4676   //   When a parameter of reference type is not bound directly to
4677   //   an argument expression, the conversion sequence is the one
4678   //   required to convert the argument expression to the
4679   //   underlying type of the reference according to
4680   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4681   //   to copy-initializing a temporary of the underlying type with
4682   //   the argument expression. Any difference in top-level
4683   //   cv-qualification is subsumed by the initialization itself
4684   //   and does not constitute a conversion.
4685   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4686                               /*AllowExplicit=*/false,
4687                               /*InOverloadResolution=*/false,
4688                               /*CStyle=*/false,
4689                               /*AllowObjCWritebackConversion=*/false,
4690                               /*AllowObjCConversionOnExplicit=*/false);
4691 
4692   // Of course, that's still a reference binding.
4693   if (ICS.isStandard()) {
4694     ICS.Standard.ReferenceBinding = true;
4695     ICS.Standard.IsLvalueReference = !isRValRef;
4696     ICS.Standard.BindsToFunctionLvalue = false;
4697     ICS.Standard.BindsToRvalue = true;
4698     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4699     ICS.Standard.ObjCLifetimeConversionBinding = false;
4700   } else if (ICS.isUserDefined()) {
4701     const ReferenceType *LValRefType =
4702         ICS.UserDefined.ConversionFunction->getReturnType()
4703             ->getAs<LValueReferenceType>();
4704 
4705     // C++ [over.ics.ref]p3:
4706     //   Except for an implicit object parameter, for which see 13.3.1, a
4707     //   standard conversion sequence cannot be formed if it requires [...]
4708     //   binding an rvalue reference to an lvalue other than a function
4709     //   lvalue.
4710     // Note that the function case is not possible here.
4711     if (DeclType->isRValueReferenceType() && LValRefType) {
4712       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4713       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4714       // reference to an rvalue!
4715       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4716       return ICS;
4717     }
4718 
4719     ICS.UserDefined.After.ReferenceBinding = true;
4720     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4721     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4722     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4723     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4725   }
4726 
4727   return ICS;
4728 }
4729 
4730 static ImplicitConversionSequence
4731 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4732                       bool SuppressUserConversions,
4733                       bool InOverloadResolution,
4734                       bool AllowObjCWritebackConversion,
4735                       bool AllowExplicit = false);
4736 
4737 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4738 /// initializer list From.
4739 static ImplicitConversionSequence
4740 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4741                   bool SuppressUserConversions,
4742                   bool InOverloadResolution,
4743                   bool AllowObjCWritebackConversion) {
4744   // C++11 [over.ics.list]p1:
4745   //   When an argument is an initializer list, it is not an expression and
4746   //   special rules apply for converting it to a parameter type.
4747 
4748   ImplicitConversionSequence Result;
4749   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4750 
4751   // We need a complete type for what follows. Incomplete types can never be
4752   // initialized from init lists.
4753   if (!S.isCompleteType(From->getLocStart(), ToType))
4754     return Result;
4755 
4756   // Per DR1467:
4757   //   If the parameter type is a class X and the initializer list has a single
4758   //   element of type cv U, where U is X or a class derived from X, the
4759   //   implicit conversion sequence is the one required to convert the element
4760   //   to the parameter type.
4761   //
4762   //   Otherwise, if the parameter type is a character array [... ]
4763   //   and the initializer list has a single element that is an
4764   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4765   //   implicit conversion sequence is the identity conversion.
4766   if (From->getNumInits() == 1) {
4767     if (ToType->isRecordType()) {
4768       QualType InitType = From->getInit(0)->getType();
4769       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4770           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4771         return TryCopyInitialization(S, From->getInit(0), ToType,
4772                                      SuppressUserConversions,
4773                                      InOverloadResolution,
4774                                      AllowObjCWritebackConversion);
4775     }
4776     // FIXME: Check the other conditions here: array of character type,
4777     // initializer is a string literal.
4778     if (ToType->isArrayType()) {
4779       InitializedEntity Entity =
4780         InitializedEntity::InitializeParameter(S.Context, ToType,
4781                                                /*Consumed=*/false);
4782       if (S.CanPerformCopyInitialization(Entity, From)) {
4783         Result.setStandard();
4784         Result.Standard.setAsIdentityConversion();
4785         Result.Standard.setFromType(ToType);
4786         Result.Standard.setAllToTypes(ToType);
4787         return Result;
4788       }
4789     }
4790   }
4791 
4792   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4793   // C++11 [over.ics.list]p2:
4794   //   If the parameter type is std::initializer_list<X> or "array of X" and
4795   //   all the elements can be implicitly converted to X, the implicit
4796   //   conversion sequence is the worst conversion necessary to convert an
4797   //   element of the list to X.
4798   //
4799   // C++14 [over.ics.list]p3:
4800   //   Otherwise, if the parameter type is "array of N X", if the initializer
4801   //   list has exactly N elements or if it has fewer than N elements and X is
4802   //   default-constructible, and if all the elements of the initializer list
4803   //   can be implicitly converted to X, the implicit conversion sequence is
4804   //   the worst conversion necessary to convert an element of the list to X.
4805   //
4806   // FIXME: We're missing a lot of these checks.
4807   bool toStdInitializerList = false;
4808   QualType X;
4809   if (ToType->isArrayType())
4810     X = S.Context.getAsArrayType(ToType)->getElementType();
4811   else
4812     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4813   if (!X.isNull()) {
4814     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4815       Expr *Init = From->getInit(i);
4816       ImplicitConversionSequence ICS =
4817           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4818                                 InOverloadResolution,
4819                                 AllowObjCWritebackConversion);
4820       // If a single element isn't convertible, fail.
4821       if (ICS.isBad()) {
4822         Result = ICS;
4823         break;
4824       }
4825       // Otherwise, look for the worst conversion.
4826       if (Result.isBad() ||
4827           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4828                                              Result) ==
4829               ImplicitConversionSequence::Worse)
4830         Result = ICS;
4831     }
4832 
4833     // For an empty list, we won't have computed any conversion sequence.
4834     // Introduce the identity conversion sequence.
4835     if (From->getNumInits() == 0) {
4836       Result.setStandard();
4837       Result.Standard.setAsIdentityConversion();
4838       Result.Standard.setFromType(ToType);
4839       Result.Standard.setAllToTypes(ToType);
4840     }
4841 
4842     Result.setStdInitializerListElement(toStdInitializerList);
4843     return Result;
4844   }
4845 
4846   // C++14 [over.ics.list]p4:
4847   // C++11 [over.ics.list]p3:
4848   //   Otherwise, if the parameter is a non-aggregate class X and overload
4849   //   resolution chooses a single best constructor [...] the implicit
4850   //   conversion sequence is a user-defined conversion sequence. If multiple
4851   //   constructors are viable but none is better than the others, the
4852   //   implicit conversion sequence is a user-defined conversion sequence.
4853   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4854     // This function can deal with initializer lists.
4855     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4856                                     /*AllowExplicit=*/false,
4857                                     InOverloadResolution, /*CStyle=*/false,
4858                                     AllowObjCWritebackConversion,
4859                                     /*AllowObjCConversionOnExplicit=*/false);
4860   }
4861 
4862   // C++14 [over.ics.list]p5:
4863   // C++11 [over.ics.list]p4:
4864   //   Otherwise, if the parameter has an aggregate type which can be
4865   //   initialized from the initializer list [...] the implicit conversion
4866   //   sequence is a user-defined conversion sequence.
4867   if (ToType->isAggregateType()) {
4868     // Type is an aggregate, argument is an init list. At this point it comes
4869     // down to checking whether the initialization works.
4870     // FIXME: Find out whether this parameter is consumed or not.
4871     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4872     // need to call into the initialization code here; overload resolution
4873     // should not be doing that.
4874     InitializedEntity Entity =
4875         InitializedEntity::InitializeParameter(S.Context, ToType,
4876                                                /*Consumed=*/false);
4877     if (S.CanPerformCopyInitialization(Entity, From)) {
4878       Result.setUserDefined();
4879       Result.UserDefined.Before.setAsIdentityConversion();
4880       // Initializer lists don't have a type.
4881       Result.UserDefined.Before.setFromType(QualType());
4882       Result.UserDefined.Before.setAllToTypes(QualType());
4883 
4884       Result.UserDefined.After.setAsIdentityConversion();
4885       Result.UserDefined.After.setFromType(ToType);
4886       Result.UserDefined.After.setAllToTypes(ToType);
4887       Result.UserDefined.ConversionFunction = nullptr;
4888     }
4889     return Result;
4890   }
4891 
4892   // C++14 [over.ics.list]p6:
4893   // C++11 [over.ics.list]p5:
4894   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4895   if (ToType->isReferenceType()) {
4896     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4897     // mention initializer lists in any way. So we go by what list-
4898     // initialization would do and try to extrapolate from that.
4899 
4900     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4901 
4902     // If the initializer list has a single element that is reference-related
4903     // to the parameter type, we initialize the reference from that.
4904     if (From->getNumInits() == 1) {
4905       Expr *Init = From->getInit(0);
4906 
4907       QualType T2 = Init->getType();
4908 
4909       // If the initializer is the address of an overloaded function, try
4910       // to resolve the overloaded function. If all goes well, T2 is the
4911       // type of the resulting function.
4912       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4913         DeclAccessPair Found;
4914         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4915                                    Init, ToType, false, Found))
4916           T2 = Fn->getType();
4917       }
4918 
4919       // Compute some basic properties of the types and the initializer.
4920       bool dummy1 = false;
4921       bool dummy2 = false;
4922       bool dummy3 = false;
4923       Sema::ReferenceCompareResult RefRelationship
4924         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4925                                          dummy2, dummy3);
4926 
4927       if (RefRelationship >= Sema::Ref_Related) {
4928         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4929                                 SuppressUserConversions,
4930                                 /*AllowExplicit=*/false);
4931       }
4932     }
4933 
4934     // Otherwise, we bind the reference to a temporary created from the
4935     // initializer list.
4936     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4937                                InOverloadResolution,
4938                                AllowObjCWritebackConversion);
4939     if (Result.isFailure())
4940       return Result;
4941     assert(!Result.isEllipsis() &&
4942            "Sub-initialization cannot result in ellipsis conversion.");
4943 
4944     // Can we even bind to a temporary?
4945     if (ToType->isRValueReferenceType() ||
4946         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4947       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4948                                             Result.UserDefined.After;
4949       SCS.ReferenceBinding = true;
4950       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4951       SCS.BindsToRvalue = true;
4952       SCS.BindsToFunctionLvalue = false;
4953       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4954       SCS.ObjCLifetimeConversionBinding = false;
4955     } else
4956       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4957                     From, ToType);
4958     return Result;
4959   }
4960 
4961   // C++14 [over.ics.list]p7:
4962   // C++11 [over.ics.list]p6:
4963   //   Otherwise, if the parameter type is not a class:
4964   if (!ToType->isRecordType()) {
4965     //    - if the initializer list has one element that is not itself an
4966     //      initializer list, the implicit conversion sequence is the one
4967     //      required to convert the element to the parameter type.
4968     unsigned NumInits = From->getNumInits();
4969     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4970       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4971                                      SuppressUserConversions,
4972                                      InOverloadResolution,
4973                                      AllowObjCWritebackConversion);
4974     //    - if the initializer list has no elements, the implicit conversion
4975     //      sequence is the identity conversion.
4976     else if (NumInits == 0) {
4977       Result.setStandard();
4978       Result.Standard.setAsIdentityConversion();
4979       Result.Standard.setFromType(ToType);
4980       Result.Standard.setAllToTypes(ToType);
4981     }
4982     return Result;
4983   }
4984 
4985   // C++14 [over.ics.list]p8:
4986   // C++11 [over.ics.list]p7:
4987   //   In all cases other than those enumerated above, no conversion is possible
4988   return Result;
4989 }
4990 
4991 /// TryCopyInitialization - Try to copy-initialize a value of type
4992 /// ToType from the expression From. Return the implicit conversion
4993 /// sequence required to pass this argument, which may be a bad
4994 /// conversion sequence (meaning that the argument cannot be passed to
4995 /// a parameter of this type). If @p SuppressUserConversions, then we
4996 /// do not permit any user-defined conversion sequences.
4997 static ImplicitConversionSequence
4998 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4999                       bool SuppressUserConversions,
5000                       bool InOverloadResolution,
5001                       bool AllowObjCWritebackConversion,
5002                       bool AllowExplicit) {
5003   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5004     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5005                              InOverloadResolution,AllowObjCWritebackConversion);
5006 
5007   if (ToType->isReferenceType())
5008     return TryReferenceInit(S, From, ToType,
5009                             /*FIXME:*/From->getLocStart(),
5010                             SuppressUserConversions,
5011                             AllowExplicit);
5012 
5013   return TryImplicitConversion(S, From, ToType,
5014                                SuppressUserConversions,
5015                                /*AllowExplicit=*/false,
5016                                InOverloadResolution,
5017                                /*CStyle=*/false,
5018                                AllowObjCWritebackConversion,
5019                                /*AllowObjCConversionOnExplicit=*/false);
5020 }
5021 
5022 static bool TryCopyInitialization(const CanQualType FromQTy,
5023                                   const CanQualType ToQTy,
5024                                   Sema &S,
5025                                   SourceLocation Loc,
5026                                   ExprValueKind FromVK) {
5027   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5028   ImplicitConversionSequence ICS =
5029     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5030 
5031   return !ICS.isBad();
5032 }
5033 
5034 /// TryObjectArgumentInitialization - Try to initialize the object
5035 /// parameter of the given member function (@c Method) from the
5036 /// expression @p From.
5037 static ImplicitConversionSequence
5038 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5039                                 Expr::Classification FromClassification,
5040                                 CXXMethodDecl *Method,
5041                                 CXXRecordDecl *ActingContext) {
5042   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5043   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5044   //                 const volatile object.
5045   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5046     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5047   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5048 
5049   // Set up the conversion sequence as a "bad" conversion, to allow us
5050   // to exit early.
5051   ImplicitConversionSequence ICS;
5052 
5053   // We need to have an object of class type.
5054   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5055     FromType = PT->getPointeeType();
5056 
5057     // When we had a pointer, it's implicitly dereferenced, so we
5058     // better have an lvalue.
5059     assert(FromClassification.isLValue());
5060   }
5061 
5062   assert(FromType->isRecordType());
5063 
5064   // C++0x [over.match.funcs]p4:
5065   //   For non-static member functions, the type of the implicit object
5066   //   parameter is
5067   //
5068   //     - "lvalue reference to cv X" for functions declared without a
5069   //        ref-qualifier or with the & ref-qualifier
5070   //     - "rvalue reference to cv X" for functions declared with the &&
5071   //        ref-qualifier
5072   //
5073   // where X is the class of which the function is a member and cv is the
5074   // cv-qualification on the member function declaration.
5075   //
5076   // However, when finding an implicit conversion sequence for the argument, we
5077   // are not allowed to perform user-defined conversions
5078   // (C++ [over.match.funcs]p5). We perform a simplified version of
5079   // reference binding here, that allows class rvalues to bind to
5080   // non-constant references.
5081 
5082   // First check the qualifiers.
5083   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5084   if (ImplicitParamType.getCVRQualifiers()
5085                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5086       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5087     ICS.setBad(BadConversionSequence::bad_qualifiers,
5088                FromType, ImplicitParamType);
5089     return ICS;
5090   }
5091 
5092   // Check that we have either the same type or a derived type. It
5093   // affects the conversion rank.
5094   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5095   ImplicitConversionKind SecondKind;
5096   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5097     SecondKind = ICK_Identity;
5098   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5099     SecondKind = ICK_Derived_To_Base;
5100   else {
5101     ICS.setBad(BadConversionSequence::unrelated_class,
5102                FromType, ImplicitParamType);
5103     return ICS;
5104   }
5105 
5106   // Check the ref-qualifier.
5107   switch (Method->getRefQualifier()) {
5108   case RQ_None:
5109     // Do nothing; we don't care about lvalueness or rvalueness.
5110     break;
5111 
5112   case RQ_LValue:
5113     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5114       // non-const lvalue reference cannot bind to an rvalue
5115       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5116                  ImplicitParamType);
5117       return ICS;
5118     }
5119     break;
5120 
5121   case RQ_RValue:
5122     if (!FromClassification.isRValue()) {
5123       // rvalue reference cannot bind to an lvalue
5124       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5125                  ImplicitParamType);
5126       return ICS;
5127     }
5128     break;
5129   }
5130 
5131   // Success. Mark this as a reference binding.
5132   ICS.setStandard();
5133   ICS.Standard.setAsIdentityConversion();
5134   ICS.Standard.Second = SecondKind;
5135   ICS.Standard.setFromType(FromType);
5136   ICS.Standard.setAllToTypes(ImplicitParamType);
5137   ICS.Standard.ReferenceBinding = true;
5138   ICS.Standard.DirectBinding = true;
5139   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5140   ICS.Standard.BindsToFunctionLvalue = false;
5141   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5142   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5143     = (Method->getRefQualifier() == RQ_None);
5144   return ICS;
5145 }
5146 
5147 /// PerformObjectArgumentInitialization - Perform initialization of
5148 /// the implicit object parameter for the given Method with the given
5149 /// expression.
5150 ExprResult
5151 Sema::PerformObjectArgumentInitialization(Expr *From,
5152                                           NestedNameSpecifier *Qualifier,
5153                                           NamedDecl *FoundDecl,
5154                                           CXXMethodDecl *Method) {
5155   QualType FromRecordType, DestType;
5156   QualType ImplicitParamRecordType  =
5157     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5158 
5159   Expr::Classification FromClassification;
5160   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5161     FromRecordType = PT->getPointeeType();
5162     DestType = Method->getThisType(Context);
5163     FromClassification = Expr::Classification::makeSimpleLValue();
5164   } else {
5165     FromRecordType = From->getType();
5166     DestType = ImplicitParamRecordType;
5167     FromClassification = From->Classify(Context);
5168 
5169     // When performing member access on an rvalue, materialize a temporary.
5170     if (From->isRValue()) {
5171       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5172                                             Method->getRefQualifier() !=
5173                                                 RefQualifierKind::RQ_RValue);
5174     }
5175   }
5176 
5177   // Note that we always use the true parent context when performing
5178   // the actual argument initialization.
5179   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5180       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5181       Method->getParent());
5182   if (ICS.isBad()) {
5183     switch (ICS.Bad.Kind) {
5184     case BadConversionSequence::bad_qualifiers: {
5185       Qualifiers FromQs = FromRecordType.getQualifiers();
5186       Qualifiers ToQs = DestType.getQualifiers();
5187       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5188       if (CVR) {
5189         Diag(From->getLocStart(),
5190              diag::err_member_function_call_bad_cvr)
5191           << Method->getDeclName() << FromRecordType << (CVR - 1)
5192           << From->getSourceRange();
5193         Diag(Method->getLocation(), diag::note_previous_decl)
5194           << Method->getDeclName();
5195         return ExprError();
5196       }
5197       break;
5198     }
5199 
5200     case BadConversionSequence::lvalue_ref_to_rvalue:
5201     case BadConversionSequence::rvalue_ref_to_lvalue: {
5202       bool IsRValueQualified =
5203         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5204       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5205         << Method->getDeclName() << FromClassification.isRValue()
5206         << IsRValueQualified;
5207       Diag(Method->getLocation(), diag::note_previous_decl)
5208         << Method->getDeclName();
5209       return ExprError();
5210     }
5211 
5212     case BadConversionSequence::no_conversion:
5213     case BadConversionSequence::unrelated_class:
5214       break;
5215     }
5216 
5217     return Diag(From->getLocStart(),
5218                 diag::err_member_function_call_bad_type)
5219        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5220   }
5221 
5222   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5223     ExprResult FromRes =
5224       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5225     if (FromRes.isInvalid())
5226       return ExprError();
5227     From = FromRes.get();
5228   }
5229 
5230   if (!Context.hasSameType(From->getType(), DestType))
5231     From = ImpCastExprToType(From, DestType, CK_NoOp,
5232                              From->getValueKind()).get();
5233   return From;
5234 }
5235 
5236 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5237 /// expression From to bool (C++0x [conv]p3).
5238 static ImplicitConversionSequence
5239 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5240   return TryImplicitConversion(S, From, S.Context.BoolTy,
5241                                /*SuppressUserConversions=*/false,
5242                                /*AllowExplicit=*/true,
5243                                /*InOverloadResolution=*/false,
5244                                /*CStyle=*/false,
5245                                /*AllowObjCWritebackConversion=*/false,
5246                                /*AllowObjCConversionOnExplicit=*/false);
5247 }
5248 
5249 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5250 /// of the expression From to bool (C++0x [conv]p3).
5251 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5252   if (checkPlaceholderForOverload(*this, From))
5253     return ExprError();
5254 
5255   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5256   if (!ICS.isBad())
5257     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5258 
5259   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5260     return Diag(From->getLocStart(),
5261                 diag::err_typecheck_bool_condition)
5262                   << From->getType() << From->getSourceRange();
5263   return ExprError();
5264 }
5265 
5266 /// Check that the specified conversion is permitted in a converted constant
5267 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5268 /// is acceptable.
5269 static bool CheckConvertedConstantConversions(Sema &S,
5270                                               StandardConversionSequence &SCS) {
5271   // Since we know that the target type is an integral or unscoped enumeration
5272   // type, most conversion kinds are impossible. All possible First and Third
5273   // conversions are fine.
5274   switch (SCS.Second) {
5275   case ICK_Identity:
5276   case ICK_Function_Conversion:
5277   case ICK_Integral_Promotion:
5278   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5279   case ICK_Zero_Queue_Conversion:
5280     return true;
5281 
5282   case ICK_Boolean_Conversion:
5283     // Conversion from an integral or unscoped enumeration type to bool is
5284     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5285     // conversion, so we allow it in a converted constant expression.
5286     //
5287     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5288     // a lot of popular code. We should at least add a warning for this
5289     // (non-conforming) extension.
5290     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5291            SCS.getToType(2)->isBooleanType();
5292 
5293   case ICK_Pointer_Conversion:
5294   case ICK_Pointer_Member:
5295     // C++1z: null pointer conversions and null member pointer conversions are
5296     // only permitted if the source type is std::nullptr_t.
5297     return SCS.getFromType()->isNullPtrType();
5298 
5299   case ICK_Floating_Promotion:
5300   case ICK_Complex_Promotion:
5301   case ICK_Floating_Conversion:
5302   case ICK_Complex_Conversion:
5303   case ICK_Floating_Integral:
5304   case ICK_Compatible_Conversion:
5305   case ICK_Derived_To_Base:
5306   case ICK_Vector_Conversion:
5307   case ICK_Vector_Splat:
5308   case ICK_Complex_Real:
5309   case ICK_Block_Pointer_Conversion:
5310   case ICK_TransparentUnionConversion:
5311   case ICK_Writeback_Conversion:
5312   case ICK_Zero_Event_Conversion:
5313   case ICK_C_Only_Conversion:
5314   case ICK_Incompatible_Pointer_Conversion:
5315     return false;
5316 
5317   case ICK_Lvalue_To_Rvalue:
5318   case ICK_Array_To_Pointer:
5319   case ICK_Function_To_Pointer:
5320     llvm_unreachable("found a first conversion kind in Second");
5321 
5322   case ICK_Qualification:
5323     llvm_unreachable("found a third conversion kind in Second");
5324 
5325   case ICK_Num_Conversion_Kinds:
5326     break;
5327   }
5328 
5329   llvm_unreachable("unknown conversion kind");
5330 }
5331 
5332 /// CheckConvertedConstantExpression - Check that the expression From is a
5333 /// converted constant expression of type T, perform the conversion and produce
5334 /// the converted expression, per C++11 [expr.const]p3.
5335 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5336                                                    QualType T, APValue &Value,
5337                                                    Sema::CCEKind CCE,
5338                                                    bool RequireInt) {
5339   assert(S.getLangOpts().CPlusPlus11 &&
5340          "converted constant expression outside C++11");
5341 
5342   if (checkPlaceholderForOverload(S, From))
5343     return ExprError();
5344 
5345   // C++1z [expr.const]p3:
5346   //  A converted constant expression of type T is an expression,
5347   //  implicitly converted to type T, where the converted
5348   //  expression is a constant expression and the implicit conversion
5349   //  sequence contains only [... list of conversions ...].
5350   // C++1z [stmt.if]p2:
5351   //  If the if statement is of the form if constexpr, the value of the
5352   //  condition shall be a contextually converted constant expression of type
5353   //  bool.
5354   ImplicitConversionSequence ICS =
5355       CCE == Sema::CCEK_ConstexprIf
5356           ? TryContextuallyConvertToBool(S, From)
5357           : TryCopyInitialization(S, From, T,
5358                                   /*SuppressUserConversions=*/false,
5359                                   /*InOverloadResolution=*/false,
5360                                   /*AllowObjcWritebackConversion=*/false,
5361                                   /*AllowExplicit=*/false);
5362   StandardConversionSequence *SCS = nullptr;
5363   switch (ICS.getKind()) {
5364   case ImplicitConversionSequence::StandardConversion:
5365     SCS = &ICS.Standard;
5366     break;
5367   case ImplicitConversionSequence::UserDefinedConversion:
5368     // We are converting to a non-class type, so the Before sequence
5369     // must be trivial.
5370     SCS = &ICS.UserDefined.After;
5371     break;
5372   case ImplicitConversionSequence::AmbiguousConversion:
5373   case ImplicitConversionSequence::BadConversion:
5374     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5375       return S.Diag(From->getLocStart(),
5376                     diag::err_typecheck_converted_constant_expression)
5377                 << From->getType() << From->getSourceRange() << T;
5378     return ExprError();
5379 
5380   case ImplicitConversionSequence::EllipsisConversion:
5381     llvm_unreachable("ellipsis conversion in converted constant expression");
5382   }
5383 
5384   // Check that we would only use permitted conversions.
5385   if (!CheckConvertedConstantConversions(S, *SCS)) {
5386     return S.Diag(From->getLocStart(),
5387                   diag::err_typecheck_converted_constant_expression_disallowed)
5388              << From->getType() << From->getSourceRange() << T;
5389   }
5390   // [...] and where the reference binding (if any) binds directly.
5391   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5392     return S.Diag(From->getLocStart(),
5393                   diag::err_typecheck_converted_constant_expression_indirect)
5394              << From->getType() << From->getSourceRange() << T;
5395   }
5396 
5397   ExprResult Result =
5398       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5399   if (Result.isInvalid())
5400     return Result;
5401 
5402   // Check for a narrowing implicit conversion.
5403   APValue PreNarrowingValue;
5404   QualType PreNarrowingType;
5405   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5406                                 PreNarrowingType)) {
5407   case NK_Dependent_Narrowing:
5408     // Implicit conversion to a narrower type, but the expression is
5409     // value-dependent so we can't tell whether it's actually narrowing.
5410   case NK_Variable_Narrowing:
5411     // Implicit conversion to a narrower type, and the value is not a constant
5412     // expression. We'll diagnose this in a moment.
5413   case NK_Not_Narrowing:
5414     break;
5415 
5416   case NK_Constant_Narrowing:
5417     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5418       << CCE << /*Constant*/1
5419       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5420     break;
5421 
5422   case NK_Type_Narrowing:
5423     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5424       << CCE << /*Constant*/0 << From->getType() << T;
5425     break;
5426   }
5427 
5428   if (Result.get()->isValueDependent()) {
5429     Value = APValue();
5430     return Result;
5431   }
5432 
5433   // Check the expression is a constant expression.
5434   SmallVector<PartialDiagnosticAt, 8> Notes;
5435   Expr::EvalResult Eval;
5436   Eval.Diag = &Notes;
5437   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5438                                    ? Expr::EvaluateForMangling
5439                                    : Expr::EvaluateForCodeGen;
5440 
5441   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5442       (RequireInt && !Eval.Val.isInt())) {
5443     // The expression can't be folded, so we can't keep it at this position in
5444     // the AST.
5445     Result = ExprError();
5446   } else {
5447     Value = Eval.Val;
5448 
5449     if (Notes.empty()) {
5450       // It's a constant expression.
5451       return Result;
5452     }
5453   }
5454 
5455   // It's not a constant expression. Produce an appropriate diagnostic.
5456   if (Notes.size() == 1 &&
5457       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5458     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5459   else {
5460     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5461       << CCE << From->getSourceRange();
5462     for (unsigned I = 0; I < Notes.size(); ++I)
5463       S.Diag(Notes[I].first, Notes[I].second);
5464   }
5465   return ExprError();
5466 }
5467 
5468 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5469                                                   APValue &Value, CCEKind CCE) {
5470   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5471 }
5472 
5473 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5474                                                   llvm::APSInt &Value,
5475                                                   CCEKind CCE) {
5476   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5477 
5478   APValue V;
5479   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5480   if (!R.isInvalid() && !R.get()->isValueDependent())
5481     Value = V.getInt();
5482   return R;
5483 }
5484 
5485 
5486 /// dropPointerConversions - If the given standard conversion sequence
5487 /// involves any pointer conversions, remove them.  This may change
5488 /// the result type of the conversion sequence.
5489 static void dropPointerConversion(StandardConversionSequence &SCS) {
5490   if (SCS.Second == ICK_Pointer_Conversion) {
5491     SCS.Second = ICK_Identity;
5492     SCS.Third = ICK_Identity;
5493     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5494   }
5495 }
5496 
5497 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5498 /// convert the expression From to an Objective-C pointer type.
5499 static ImplicitConversionSequence
5500 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5501   // Do an implicit conversion to 'id'.
5502   QualType Ty = S.Context.getObjCIdType();
5503   ImplicitConversionSequence ICS
5504     = TryImplicitConversion(S, From, Ty,
5505                             // FIXME: Are these flags correct?
5506                             /*SuppressUserConversions=*/false,
5507                             /*AllowExplicit=*/true,
5508                             /*InOverloadResolution=*/false,
5509                             /*CStyle=*/false,
5510                             /*AllowObjCWritebackConversion=*/false,
5511                             /*AllowObjCConversionOnExplicit=*/true);
5512 
5513   // Strip off any final conversions to 'id'.
5514   switch (ICS.getKind()) {
5515   case ImplicitConversionSequence::BadConversion:
5516   case ImplicitConversionSequence::AmbiguousConversion:
5517   case ImplicitConversionSequence::EllipsisConversion:
5518     break;
5519 
5520   case ImplicitConversionSequence::UserDefinedConversion:
5521     dropPointerConversion(ICS.UserDefined.After);
5522     break;
5523 
5524   case ImplicitConversionSequence::StandardConversion:
5525     dropPointerConversion(ICS.Standard);
5526     break;
5527   }
5528 
5529   return ICS;
5530 }
5531 
5532 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5533 /// conversion of the expression From to an Objective-C pointer type.
5534 /// Returns a valid but null ExprResult if no conversion sequence exists.
5535 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5536   if (checkPlaceholderForOverload(*this, From))
5537     return ExprError();
5538 
5539   QualType Ty = Context.getObjCIdType();
5540   ImplicitConversionSequence ICS =
5541     TryContextuallyConvertToObjCPointer(*this, From);
5542   if (!ICS.isBad())
5543     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5544   return ExprResult();
5545 }
5546 
5547 /// Determine whether the provided type is an integral type, or an enumeration
5548 /// type of a permitted flavor.
5549 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5550   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5551                                  : T->isIntegralOrUnscopedEnumerationType();
5552 }
5553 
5554 static ExprResult
5555 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5556                             Sema::ContextualImplicitConverter &Converter,
5557                             QualType T, UnresolvedSetImpl &ViableConversions) {
5558 
5559   if (Converter.Suppress)
5560     return ExprError();
5561 
5562   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5563   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5564     CXXConversionDecl *Conv =
5565         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5566     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5567     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5568   }
5569   return From;
5570 }
5571 
5572 static bool
5573 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5574                            Sema::ContextualImplicitConverter &Converter,
5575                            QualType T, bool HadMultipleCandidates,
5576                            UnresolvedSetImpl &ExplicitConversions) {
5577   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5578     DeclAccessPair Found = ExplicitConversions[0];
5579     CXXConversionDecl *Conversion =
5580         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5581 
5582     // The user probably meant to invoke the given explicit
5583     // conversion; use it.
5584     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5585     std::string TypeStr;
5586     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5587 
5588     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5589         << FixItHint::CreateInsertion(From->getLocStart(),
5590                                       "static_cast<" + TypeStr + ">(")
5591         << FixItHint::CreateInsertion(
5592                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5593     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5594 
5595     // If we aren't in a SFINAE context, build a call to the
5596     // explicit conversion function.
5597     if (SemaRef.isSFINAEContext())
5598       return true;
5599 
5600     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5601     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5602                                                        HadMultipleCandidates);
5603     if (Result.isInvalid())
5604       return true;
5605     // Record usage of conversion in an implicit cast.
5606     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5607                                     CK_UserDefinedConversion, Result.get(),
5608                                     nullptr, Result.get()->getValueKind());
5609   }
5610   return false;
5611 }
5612 
5613 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5614                              Sema::ContextualImplicitConverter &Converter,
5615                              QualType T, bool HadMultipleCandidates,
5616                              DeclAccessPair &Found) {
5617   CXXConversionDecl *Conversion =
5618       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5619   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5620 
5621   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5622   if (!Converter.SuppressConversion) {
5623     if (SemaRef.isSFINAEContext())
5624       return true;
5625 
5626     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5627         << From->getSourceRange();
5628   }
5629 
5630   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5631                                                      HadMultipleCandidates);
5632   if (Result.isInvalid())
5633     return true;
5634   // Record usage of conversion in an implicit cast.
5635   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5636                                   CK_UserDefinedConversion, Result.get(),
5637                                   nullptr, Result.get()->getValueKind());
5638   return false;
5639 }
5640 
5641 static ExprResult finishContextualImplicitConversion(
5642     Sema &SemaRef, SourceLocation Loc, Expr *From,
5643     Sema::ContextualImplicitConverter &Converter) {
5644   if (!Converter.match(From->getType()) && !Converter.Suppress)
5645     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5646         << From->getSourceRange();
5647 
5648   return SemaRef.DefaultLvalueConversion(From);
5649 }
5650 
5651 static void
5652 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5653                                   UnresolvedSetImpl &ViableConversions,
5654                                   OverloadCandidateSet &CandidateSet) {
5655   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5656     DeclAccessPair FoundDecl = ViableConversions[I];
5657     NamedDecl *D = FoundDecl.getDecl();
5658     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5659     if (isa<UsingShadowDecl>(D))
5660       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5661 
5662     CXXConversionDecl *Conv;
5663     FunctionTemplateDecl *ConvTemplate;
5664     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5665       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5666     else
5667       Conv = cast<CXXConversionDecl>(D);
5668 
5669     if (ConvTemplate)
5670       SemaRef.AddTemplateConversionCandidate(
5671         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5672         /*AllowObjCConversionOnExplicit=*/false);
5673     else
5674       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5675                                      ToType, CandidateSet,
5676                                      /*AllowObjCConversionOnExplicit=*/false);
5677   }
5678 }
5679 
5680 /// Attempt to convert the given expression to a type which is accepted
5681 /// by the given converter.
5682 ///
5683 /// This routine will attempt to convert an expression of class type to a
5684 /// type accepted by the specified converter. In C++11 and before, the class
5685 /// must have a single non-explicit conversion function converting to a matching
5686 /// type. In C++1y, there can be multiple such conversion functions, but only
5687 /// one target type.
5688 ///
5689 /// \param Loc The source location of the construct that requires the
5690 /// conversion.
5691 ///
5692 /// \param From The expression we're converting from.
5693 ///
5694 /// \param Converter Used to control and diagnose the conversion process.
5695 ///
5696 /// \returns The expression, converted to an integral or enumeration type if
5697 /// successful.
5698 ExprResult Sema::PerformContextualImplicitConversion(
5699     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5700   // We can't perform any more checking for type-dependent expressions.
5701   if (From->isTypeDependent())
5702     return From;
5703 
5704   // Process placeholders immediately.
5705   if (From->hasPlaceholderType()) {
5706     ExprResult result = CheckPlaceholderExpr(From);
5707     if (result.isInvalid())
5708       return result;
5709     From = result.get();
5710   }
5711 
5712   // If the expression already has a matching type, we're golden.
5713   QualType T = From->getType();
5714   if (Converter.match(T))
5715     return DefaultLvalueConversion(From);
5716 
5717   // FIXME: Check for missing '()' if T is a function type?
5718 
5719   // We can only perform contextual implicit conversions on objects of class
5720   // type.
5721   const RecordType *RecordTy = T->getAs<RecordType>();
5722   if (!RecordTy || !getLangOpts().CPlusPlus) {
5723     if (!Converter.Suppress)
5724       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5725     return From;
5726   }
5727 
5728   // We must have a complete class type.
5729   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5730     ContextualImplicitConverter &Converter;
5731     Expr *From;
5732 
5733     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5734         : Converter(Converter), From(From) {}
5735 
5736     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5737       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5738     }
5739   } IncompleteDiagnoser(Converter, From);
5740 
5741   if (Converter.Suppress ? !isCompleteType(Loc, T)
5742                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5743     return From;
5744 
5745   // Look for a conversion to an integral or enumeration type.
5746   UnresolvedSet<4>
5747       ViableConversions; // These are *potentially* viable in C++1y.
5748   UnresolvedSet<4> ExplicitConversions;
5749   const auto &Conversions =
5750       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5751 
5752   bool HadMultipleCandidates =
5753       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5754 
5755   // To check that there is only one target type, in C++1y:
5756   QualType ToType;
5757   bool HasUniqueTargetType = true;
5758 
5759   // Collect explicit or viable (potentially in C++1y) conversions.
5760   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5761     NamedDecl *D = (*I)->getUnderlyingDecl();
5762     CXXConversionDecl *Conversion;
5763     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5764     if (ConvTemplate) {
5765       if (getLangOpts().CPlusPlus14)
5766         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5767       else
5768         continue; // C++11 does not consider conversion operator templates(?).
5769     } else
5770       Conversion = cast<CXXConversionDecl>(D);
5771 
5772     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5773            "Conversion operator templates are considered potentially "
5774            "viable in C++1y");
5775 
5776     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5777     if (Converter.match(CurToType) || ConvTemplate) {
5778 
5779       if (Conversion->isExplicit()) {
5780         // FIXME: For C++1y, do we need this restriction?
5781         // cf. diagnoseNoViableConversion()
5782         if (!ConvTemplate)
5783           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5784       } else {
5785         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5786           if (ToType.isNull())
5787             ToType = CurToType.getUnqualifiedType();
5788           else if (HasUniqueTargetType &&
5789                    (CurToType.getUnqualifiedType() != ToType))
5790             HasUniqueTargetType = false;
5791         }
5792         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5793       }
5794     }
5795   }
5796 
5797   if (getLangOpts().CPlusPlus14) {
5798     // C++1y [conv]p6:
5799     // ... An expression e of class type E appearing in such a context
5800     // is said to be contextually implicitly converted to a specified
5801     // type T and is well-formed if and only if e can be implicitly
5802     // converted to a type T that is determined as follows: E is searched
5803     // for conversion functions whose return type is cv T or reference to
5804     // cv T such that T is allowed by the context. There shall be
5805     // exactly one such T.
5806 
5807     // If no unique T is found:
5808     if (ToType.isNull()) {
5809       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5810                                      HadMultipleCandidates,
5811                                      ExplicitConversions))
5812         return ExprError();
5813       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5814     }
5815 
5816     // If more than one unique Ts are found:
5817     if (!HasUniqueTargetType)
5818       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819                                          ViableConversions);
5820 
5821     // If one unique T is found:
5822     // First, build a candidate set from the previously recorded
5823     // potentially viable conversions.
5824     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5825     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5826                                       CandidateSet);
5827 
5828     // Then, perform overload resolution over the candidate set.
5829     OverloadCandidateSet::iterator Best;
5830     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5831     case OR_Success: {
5832       // Apply this conversion.
5833       DeclAccessPair Found =
5834           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5835       if (recordConversion(*this, Loc, From, Converter, T,
5836                            HadMultipleCandidates, Found))
5837         return ExprError();
5838       break;
5839     }
5840     case OR_Ambiguous:
5841       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5842                                          ViableConversions);
5843     case OR_No_Viable_Function:
5844       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5845                                      HadMultipleCandidates,
5846                                      ExplicitConversions))
5847         return ExprError();
5848       LLVM_FALLTHROUGH;
5849     case OR_Deleted:
5850       // We'll complain below about a non-integral condition type.
5851       break;
5852     }
5853   } else {
5854     switch (ViableConversions.size()) {
5855     case 0: {
5856       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5857                                      HadMultipleCandidates,
5858                                      ExplicitConversions))
5859         return ExprError();
5860 
5861       // We'll complain below about a non-integral condition type.
5862       break;
5863     }
5864     case 1: {
5865       // Apply this conversion.
5866       DeclAccessPair Found = ViableConversions[0];
5867       if (recordConversion(*this, Loc, From, Converter, T,
5868                            HadMultipleCandidates, Found))
5869         return ExprError();
5870       break;
5871     }
5872     default:
5873       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5874                                          ViableConversions);
5875     }
5876   }
5877 
5878   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5879 }
5880 
5881 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5882 /// an acceptable non-member overloaded operator for a call whose
5883 /// arguments have types T1 (and, if non-empty, T2). This routine
5884 /// implements the check in C++ [over.match.oper]p3b2 concerning
5885 /// enumeration types.
5886 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5887                                                    FunctionDecl *Fn,
5888                                                    ArrayRef<Expr *> Args) {
5889   QualType T1 = Args[0]->getType();
5890   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5891 
5892   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5893     return true;
5894 
5895   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5896     return true;
5897 
5898   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5899   if (Proto->getNumParams() < 1)
5900     return false;
5901 
5902   if (T1->isEnumeralType()) {
5903     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5904     if (Context.hasSameUnqualifiedType(T1, ArgType))
5905       return true;
5906   }
5907 
5908   if (Proto->getNumParams() < 2)
5909     return false;
5910 
5911   if (!T2.isNull() && T2->isEnumeralType()) {
5912     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5913     if (Context.hasSameUnqualifiedType(T2, ArgType))
5914       return true;
5915   }
5916 
5917   return false;
5918 }
5919 
5920 /// AddOverloadCandidate - Adds the given function to the set of
5921 /// candidate functions, using the given function call arguments.  If
5922 /// @p SuppressUserConversions, then don't allow user-defined
5923 /// conversions via constructors or conversion operators.
5924 ///
5925 /// \param PartialOverloading true if we are performing "partial" overloading
5926 /// based on an incomplete set of function arguments. This feature is used by
5927 /// code completion.
5928 void
5929 Sema::AddOverloadCandidate(FunctionDecl *Function,
5930                            DeclAccessPair FoundDecl,
5931                            ArrayRef<Expr *> Args,
5932                            OverloadCandidateSet &CandidateSet,
5933                            bool SuppressUserConversions,
5934                            bool PartialOverloading,
5935                            bool AllowExplicit,
5936                            ConversionSequenceList EarlyConversions) {
5937   const FunctionProtoType *Proto
5938     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5939   assert(Proto && "Functions without a prototype cannot be overloaded");
5940   assert(!Function->getDescribedFunctionTemplate() &&
5941          "Use AddTemplateOverloadCandidate for function templates");
5942 
5943   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5944     if (!isa<CXXConstructorDecl>(Method)) {
5945       // If we get here, it's because we're calling a member function
5946       // that is named without a member access expression (e.g.,
5947       // "this->f") that was either written explicitly or created
5948       // implicitly. This can happen with a qualified call to a member
5949       // function, e.g., X::f(). We use an empty type for the implied
5950       // object argument (C++ [over.call.func]p3), and the acting context
5951       // is irrelevant.
5952       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5953                          Expr::Classification::makeSimpleLValue(), Args,
5954                          CandidateSet, SuppressUserConversions,
5955                          PartialOverloading, EarlyConversions);
5956       return;
5957     }
5958     // We treat a constructor like a non-member function, since its object
5959     // argument doesn't participate in overload resolution.
5960   }
5961 
5962   if (!CandidateSet.isNewCandidate(Function))
5963     return;
5964 
5965   // C++ [over.match.oper]p3:
5966   //   if no operand has a class type, only those non-member functions in the
5967   //   lookup set that have a first parameter of type T1 or "reference to
5968   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5969   //   is a right operand) a second parameter of type T2 or "reference to
5970   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5971   //   candidate functions.
5972   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5973       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5974     return;
5975 
5976   // C++11 [class.copy]p11: [DR1402]
5977   //   A defaulted move constructor that is defined as deleted is ignored by
5978   //   overload resolution.
5979   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5980   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5981       Constructor->isMoveConstructor())
5982     return;
5983 
5984   // Overload resolution is always an unevaluated context.
5985   EnterExpressionEvaluationContext Unevaluated(
5986       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5987 
5988   // Add this candidate
5989   OverloadCandidate &Candidate =
5990       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5991   Candidate.FoundDecl = FoundDecl;
5992   Candidate.Function = Function;
5993   Candidate.Viable = true;
5994   Candidate.IsSurrogate = false;
5995   Candidate.IgnoreObjectArgument = false;
5996   Candidate.ExplicitCallArguments = Args.size();
5997 
5998   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
5999       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6000     Candidate.Viable = false;
6001     Candidate.FailureKind = ovl_non_default_multiversion_function;
6002     return;
6003   }
6004 
6005   if (Constructor) {
6006     // C++ [class.copy]p3:
6007     //   A member function template is never instantiated to perform the copy
6008     //   of a class object to an object of its class type.
6009     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6010     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6011         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6012          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
6013                        ClassType))) {
6014       Candidate.Viable = false;
6015       Candidate.FailureKind = ovl_fail_illegal_constructor;
6016       return;
6017     }
6018 
6019     // C++ [over.match.funcs]p8: (proposed DR resolution)
6020     //   A constructor inherited from class type C that has a first parameter
6021     //   of type "reference to P" (including such a constructor instantiated
6022     //   from a template) is excluded from the set of candidate functions when
6023     //   constructing an object of type cv D if the argument list has exactly
6024     //   one argument and D is reference-related to P and P is reference-related
6025     //   to C.
6026     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6027     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6028         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6029       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6030       QualType C = Context.getRecordType(Constructor->getParent());
6031       QualType D = Context.getRecordType(Shadow->getParent());
6032       SourceLocation Loc = Args.front()->getExprLoc();
6033       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6034           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6035         Candidate.Viable = false;
6036         Candidate.FailureKind = ovl_fail_inhctor_slice;
6037         return;
6038       }
6039     }
6040   }
6041 
6042   unsigned NumParams = Proto->getNumParams();
6043 
6044   // (C++ 13.3.2p2): A candidate function having fewer than m
6045   // parameters is viable only if it has an ellipsis in its parameter
6046   // list (8.3.5).
6047   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6048       !Proto->isVariadic()) {
6049     Candidate.Viable = false;
6050     Candidate.FailureKind = ovl_fail_too_many_arguments;
6051     return;
6052   }
6053 
6054   // (C++ 13.3.2p2): A candidate function having more than m parameters
6055   // is viable only if the (m+1)st parameter has a default argument
6056   // (8.3.6). For the purposes of overload resolution, the
6057   // parameter list is truncated on the right, so that there are
6058   // exactly m parameters.
6059   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6060   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6061     // Not enough arguments.
6062     Candidate.Viable = false;
6063     Candidate.FailureKind = ovl_fail_too_few_arguments;
6064     return;
6065   }
6066 
6067   // (CUDA B.1): Check for invalid calls between targets.
6068   if (getLangOpts().CUDA)
6069     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6070       // Skip the check for callers that are implicit members, because in this
6071       // case we may not yet know what the member's target is; the target is
6072       // inferred for the member automatically, based on the bases and fields of
6073       // the class.
6074       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6075         Candidate.Viable = false;
6076         Candidate.FailureKind = ovl_fail_bad_target;
6077         return;
6078       }
6079 
6080   // Determine the implicit conversion sequences for each of the
6081   // arguments.
6082   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6083     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6084       // We already formed a conversion sequence for this parameter during
6085       // template argument deduction.
6086     } else if (ArgIdx < NumParams) {
6087       // (C++ 13.3.2p3): for F to be a viable function, there shall
6088       // exist for each argument an implicit conversion sequence
6089       // (13.3.3.1) that converts that argument to the corresponding
6090       // parameter of F.
6091       QualType ParamType = Proto->getParamType(ArgIdx);
6092       Candidate.Conversions[ArgIdx]
6093         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6094                                 SuppressUserConversions,
6095                                 /*InOverloadResolution=*/true,
6096                                 /*AllowObjCWritebackConversion=*/
6097                                   getLangOpts().ObjCAutoRefCount,
6098                                 AllowExplicit);
6099       if (Candidate.Conversions[ArgIdx].isBad()) {
6100         Candidate.Viable = false;
6101         Candidate.FailureKind = ovl_fail_bad_conversion;
6102         return;
6103       }
6104     } else {
6105       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6106       // argument for which there is no corresponding parameter is
6107       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6108       Candidate.Conversions[ArgIdx].setEllipsis();
6109     }
6110   }
6111 
6112   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6113     Candidate.Viable = false;
6114     Candidate.FailureKind = ovl_fail_enable_if;
6115     Candidate.DeductionFailure.Data = FailedAttr;
6116     return;
6117   }
6118 
6119   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6120     Candidate.Viable = false;
6121     Candidate.FailureKind = ovl_fail_ext_disabled;
6122     return;
6123   }
6124 }
6125 
6126 ObjCMethodDecl *
6127 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6128                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6129   if (Methods.size() <= 1)
6130     return nullptr;
6131 
6132   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6133     bool Match = true;
6134     ObjCMethodDecl *Method = Methods[b];
6135     unsigned NumNamedArgs = Sel.getNumArgs();
6136     // Method might have more arguments than selector indicates. This is due
6137     // to addition of c-style arguments in method.
6138     if (Method->param_size() > NumNamedArgs)
6139       NumNamedArgs = Method->param_size();
6140     if (Args.size() < NumNamedArgs)
6141       continue;
6142 
6143     for (unsigned i = 0; i < NumNamedArgs; i++) {
6144       // We can't do any type-checking on a type-dependent argument.
6145       if (Args[i]->isTypeDependent()) {
6146         Match = false;
6147         break;
6148       }
6149 
6150       ParmVarDecl *param = Method->parameters()[i];
6151       Expr *argExpr = Args[i];
6152       assert(argExpr && "SelectBestMethod(): missing expression");
6153 
6154       // Strip the unbridged-cast placeholder expression off unless it's
6155       // a consumed argument.
6156       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6157           !param->hasAttr<CFConsumedAttr>())
6158         argExpr = stripARCUnbridgedCast(argExpr);
6159 
6160       // If the parameter is __unknown_anytype, move on to the next method.
6161       if (param->getType() == Context.UnknownAnyTy) {
6162         Match = false;
6163         break;
6164       }
6165 
6166       ImplicitConversionSequence ConversionState
6167         = TryCopyInitialization(*this, argExpr, param->getType(),
6168                                 /*SuppressUserConversions*/false,
6169                                 /*InOverloadResolution=*/true,
6170                                 /*AllowObjCWritebackConversion=*/
6171                                 getLangOpts().ObjCAutoRefCount,
6172                                 /*AllowExplicit*/false);
6173       // This function looks for a reasonably-exact match, so we consider
6174       // incompatible pointer conversions to be a failure here.
6175       if (ConversionState.isBad() ||
6176           (ConversionState.isStandard() &&
6177            ConversionState.Standard.Second ==
6178                ICK_Incompatible_Pointer_Conversion)) {
6179         Match = false;
6180         break;
6181       }
6182     }
6183     // Promote additional arguments to variadic methods.
6184     if (Match && Method->isVariadic()) {
6185       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6186         if (Args[i]->isTypeDependent()) {
6187           Match = false;
6188           break;
6189         }
6190         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6191                                                           nullptr);
6192         if (Arg.isInvalid()) {
6193           Match = false;
6194           break;
6195         }
6196       }
6197     } else {
6198       // Check for extra arguments to non-variadic methods.
6199       if (Args.size() != NumNamedArgs)
6200         Match = false;
6201       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6202         // Special case when selectors have no argument. In this case, select
6203         // one with the most general result type of 'id'.
6204         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6205           QualType ReturnT = Methods[b]->getReturnType();
6206           if (ReturnT->isObjCIdType())
6207             return Methods[b];
6208         }
6209       }
6210     }
6211 
6212     if (Match)
6213       return Method;
6214   }
6215   return nullptr;
6216 }
6217 
6218 static bool
6219 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6220                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6221                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6222                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6223   if (ThisArg) {
6224     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6225     assert(!isa<CXXConstructorDecl>(Method) &&
6226            "Shouldn't have `this` for ctors!");
6227     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6228     ExprResult R = S.PerformObjectArgumentInitialization(
6229         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6230     if (R.isInvalid())
6231       return false;
6232     ConvertedThis = R.get();
6233   } else {
6234     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6235       (void)MD;
6236       assert((MissingImplicitThis || MD->isStatic() ||
6237               isa<CXXConstructorDecl>(MD)) &&
6238              "Expected `this` for non-ctor instance methods");
6239     }
6240     ConvertedThis = nullptr;
6241   }
6242 
6243   // Ignore any variadic arguments. Converting them is pointless, since the
6244   // user can't refer to them in the function condition.
6245   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6246 
6247   // Convert the arguments.
6248   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6249     ExprResult R;
6250     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6251                                         S.Context, Function->getParamDecl(I)),
6252                                     SourceLocation(), Args[I]);
6253 
6254     if (R.isInvalid())
6255       return false;
6256 
6257     ConvertedArgs.push_back(R.get());
6258   }
6259 
6260   if (Trap.hasErrorOccurred())
6261     return false;
6262 
6263   // Push default arguments if needed.
6264   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6265     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6266       ParmVarDecl *P = Function->getParamDecl(i);
6267       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6268                          ? P->getUninstantiatedDefaultArg()
6269                          : P->getDefaultArg();
6270       // This can only happen in code completion, i.e. when PartialOverloading
6271       // is true.
6272       if (!DefArg)
6273         return false;
6274       ExprResult R =
6275           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6276                                           S.Context, Function->getParamDecl(i)),
6277                                       SourceLocation(), DefArg);
6278       if (R.isInvalid())
6279         return false;
6280       ConvertedArgs.push_back(R.get());
6281     }
6282 
6283     if (Trap.hasErrorOccurred())
6284       return false;
6285   }
6286   return true;
6287 }
6288 
6289 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6290                                   bool MissingImplicitThis) {
6291   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6292   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6293     return nullptr;
6294 
6295   SFINAETrap Trap(*this);
6296   SmallVector<Expr *, 16> ConvertedArgs;
6297   // FIXME: We should look into making enable_if late-parsed.
6298   Expr *DiscardedThis;
6299   if (!convertArgsForAvailabilityChecks(
6300           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6301           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6302     return *EnableIfAttrs.begin();
6303 
6304   for (auto *EIA : EnableIfAttrs) {
6305     APValue Result;
6306     // FIXME: This doesn't consider value-dependent cases, because doing so is
6307     // very difficult. Ideally, we should handle them more gracefully.
6308     if (!EIA->getCond()->EvaluateWithSubstitution(
6309             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6310       return EIA;
6311 
6312     if (!Result.isInt() || !Result.getInt().getBoolValue())
6313       return EIA;
6314   }
6315   return nullptr;
6316 }
6317 
6318 template <typename CheckFn>
6319 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6320                                         bool ArgDependent, SourceLocation Loc,
6321                                         CheckFn &&IsSuccessful) {
6322   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6323   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6324     if (ArgDependent == DIA->getArgDependent())
6325       Attrs.push_back(DIA);
6326   }
6327 
6328   // Common case: No diagnose_if attributes, so we can quit early.
6329   if (Attrs.empty())
6330     return false;
6331 
6332   auto WarningBegin = std::stable_partition(
6333       Attrs.begin(), Attrs.end(),
6334       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6335 
6336   // Note that diagnose_if attributes are late-parsed, so they appear in the
6337   // correct order (unlike enable_if attributes).
6338   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6339                                IsSuccessful);
6340   if (ErrAttr != WarningBegin) {
6341     const DiagnoseIfAttr *DIA = *ErrAttr;
6342     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6343     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6344         << DIA->getParent() << DIA->getCond()->getSourceRange();
6345     return true;
6346   }
6347 
6348   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6349     if (IsSuccessful(DIA)) {
6350       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6351       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6352           << DIA->getParent() << DIA->getCond()->getSourceRange();
6353     }
6354 
6355   return false;
6356 }
6357 
6358 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6359                                                const Expr *ThisArg,
6360                                                ArrayRef<const Expr *> Args,
6361                                                SourceLocation Loc) {
6362   return diagnoseDiagnoseIfAttrsWith(
6363       *this, Function, /*ArgDependent=*/true, Loc,
6364       [&](const DiagnoseIfAttr *DIA) {
6365         APValue Result;
6366         // It's sane to use the same Args for any redecl of this function, since
6367         // EvaluateWithSubstitution only cares about the position of each
6368         // argument in the arg list, not the ParmVarDecl* it maps to.
6369         if (!DIA->getCond()->EvaluateWithSubstitution(
6370                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6371           return false;
6372         return Result.isInt() && Result.getInt().getBoolValue();
6373       });
6374 }
6375 
6376 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6377                                                  SourceLocation Loc) {
6378   return diagnoseDiagnoseIfAttrsWith(
6379       *this, ND, /*ArgDependent=*/false, Loc,
6380       [&](const DiagnoseIfAttr *DIA) {
6381         bool Result;
6382         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6383                Result;
6384       });
6385 }
6386 
6387 /// Add all of the function declarations in the given function set to
6388 /// the overload candidate set.
6389 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6390                                  ArrayRef<Expr *> Args,
6391                                  OverloadCandidateSet &CandidateSet,
6392                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6393                                  bool SuppressUserConversions,
6394                                  bool PartialOverloading,
6395                                  bool FirstArgumentIsBase) {
6396   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6397     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6398     ArrayRef<Expr *> FunctionArgs = Args;
6399 
6400     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6401     FunctionDecl *FD =
6402         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6403 
6404     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6405       QualType ObjectType;
6406       Expr::Classification ObjectClassification;
6407       if (Args.size() > 0) {
6408         if (Expr *E = Args[0]) {
6409           // Use the explicit base to restrict the lookup:
6410           ObjectType = E->getType();
6411           ObjectClassification = E->Classify(Context);
6412         } // .. else there is an implicit base.
6413         FunctionArgs = Args.slice(1);
6414       }
6415       if (FunTmpl) {
6416         AddMethodTemplateCandidate(
6417             FunTmpl, F.getPair(),
6418             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6419             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6420             FunctionArgs, CandidateSet, SuppressUserConversions,
6421             PartialOverloading);
6422       } else {
6423         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6424                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6425                            ObjectClassification, FunctionArgs, CandidateSet,
6426                            SuppressUserConversions, PartialOverloading);
6427       }
6428     } else {
6429       // This branch handles both standalone functions and static methods.
6430 
6431       // Slice the first argument (which is the base) when we access
6432       // static method as non-static.
6433       if (Args.size() > 0 &&
6434           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6435                         !isa<CXXConstructorDecl>(FD)))) {
6436         assert(cast<CXXMethodDecl>(FD)->isStatic());
6437         FunctionArgs = Args.slice(1);
6438       }
6439       if (FunTmpl) {
6440         AddTemplateOverloadCandidate(
6441             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6442             CandidateSet, SuppressUserConversions, PartialOverloading);
6443       } else {
6444         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6445                              SuppressUserConversions, PartialOverloading);
6446       }
6447     }
6448   }
6449 }
6450 
6451 /// AddMethodCandidate - Adds a named decl (which is some kind of
6452 /// method) as a method candidate to the given overload set.
6453 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6454                               QualType ObjectType,
6455                               Expr::Classification ObjectClassification,
6456                               ArrayRef<Expr *> Args,
6457                               OverloadCandidateSet& CandidateSet,
6458                               bool SuppressUserConversions) {
6459   NamedDecl *Decl = FoundDecl.getDecl();
6460   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6461 
6462   if (isa<UsingShadowDecl>(Decl))
6463     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6464 
6465   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6466     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6467            "Expected a member function template");
6468     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6469                                /*ExplicitArgs*/ nullptr, ObjectType,
6470                                ObjectClassification, Args, CandidateSet,
6471                                SuppressUserConversions);
6472   } else {
6473     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6474                        ObjectType, ObjectClassification, Args, CandidateSet,
6475                        SuppressUserConversions);
6476   }
6477 }
6478 
6479 /// AddMethodCandidate - Adds the given C++ member function to the set
6480 /// of candidate functions, using the given function call arguments
6481 /// and the object argument (@c Object). For example, in a call
6482 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6483 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6484 /// allow user-defined conversions via constructors or conversion
6485 /// operators.
6486 void
6487 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6488                          CXXRecordDecl *ActingContext, QualType ObjectType,
6489                          Expr::Classification ObjectClassification,
6490                          ArrayRef<Expr *> Args,
6491                          OverloadCandidateSet &CandidateSet,
6492                          bool SuppressUserConversions,
6493                          bool PartialOverloading,
6494                          ConversionSequenceList EarlyConversions) {
6495   const FunctionProtoType *Proto
6496     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6497   assert(Proto && "Methods without a prototype cannot be overloaded");
6498   assert(!isa<CXXConstructorDecl>(Method) &&
6499          "Use AddOverloadCandidate for constructors");
6500 
6501   if (!CandidateSet.isNewCandidate(Method))
6502     return;
6503 
6504   // C++11 [class.copy]p23: [DR1402]
6505   //   A defaulted move assignment operator that is defined as deleted is
6506   //   ignored by overload resolution.
6507   if (Method->isDefaulted() && Method->isDeleted() &&
6508       Method->isMoveAssignmentOperator())
6509     return;
6510 
6511   // Overload resolution is always an unevaluated context.
6512   EnterExpressionEvaluationContext Unevaluated(
6513       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6514 
6515   // Add this candidate
6516   OverloadCandidate &Candidate =
6517       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6518   Candidate.FoundDecl = FoundDecl;
6519   Candidate.Function = Method;
6520   Candidate.IsSurrogate = false;
6521   Candidate.IgnoreObjectArgument = false;
6522   Candidate.ExplicitCallArguments = Args.size();
6523 
6524   unsigned NumParams = Proto->getNumParams();
6525 
6526   // (C++ 13.3.2p2): A candidate function having fewer than m
6527   // parameters is viable only if it has an ellipsis in its parameter
6528   // list (8.3.5).
6529   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6530       !Proto->isVariadic()) {
6531     Candidate.Viable = false;
6532     Candidate.FailureKind = ovl_fail_too_many_arguments;
6533     return;
6534   }
6535 
6536   // (C++ 13.3.2p2): A candidate function having more than m parameters
6537   // is viable only if the (m+1)st parameter has a default argument
6538   // (8.3.6). For the purposes of overload resolution, the
6539   // parameter list is truncated on the right, so that there are
6540   // exactly m parameters.
6541   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6542   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6543     // Not enough arguments.
6544     Candidate.Viable = false;
6545     Candidate.FailureKind = ovl_fail_too_few_arguments;
6546     return;
6547   }
6548 
6549   Candidate.Viable = true;
6550 
6551   if (Method->isStatic() || ObjectType.isNull())
6552     // The implicit object argument is ignored.
6553     Candidate.IgnoreObjectArgument = true;
6554   else {
6555     // Determine the implicit conversion sequence for the object
6556     // parameter.
6557     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6558         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6559         Method, ActingContext);
6560     if (Candidate.Conversions[0].isBad()) {
6561       Candidate.Viable = false;
6562       Candidate.FailureKind = ovl_fail_bad_conversion;
6563       return;
6564     }
6565   }
6566 
6567   // (CUDA B.1): Check for invalid calls between targets.
6568   if (getLangOpts().CUDA)
6569     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6570       if (!IsAllowedCUDACall(Caller, Method)) {
6571         Candidate.Viable = false;
6572         Candidate.FailureKind = ovl_fail_bad_target;
6573         return;
6574       }
6575 
6576   // Determine the implicit conversion sequences for each of the
6577   // arguments.
6578   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6579     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6580       // We already formed a conversion sequence for this parameter during
6581       // template argument deduction.
6582     } else if (ArgIdx < NumParams) {
6583       // (C++ 13.3.2p3): for F to be a viable function, there shall
6584       // exist for each argument an implicit conversion sequence
6585       // (13.3.3.1) that converts that argument to the corresponding
6586       // parameter of F.
6587       QualType ParamType = Proto->getParamType(ArgIdx);
6588       Candidate.Conversions[ArgIdx + 1]
6589         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6590                                 SuppressUserConversions,
6591                                 /*InOverloadResolution=*/true,
6592                                 /*AllowObjCWritebackConversion=*/
6593                                   getLangOpts().ObjCAutoRefCount);
6594       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6595         Candidate.Viable = false;
6596         Candidate.FailureKind = ovl_fail_bad_conversion;
6597         return;
6598       }
6599     } else {
6600       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6601       // argument for which there is no corresponding parameter is
6602       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6603       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6604     }
6605   }
6606 
6607   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6608     Candidate.Viable = false;
6609     Candidate.FailureKind = ovl_fail_enable_if;
6610     Candidate.DeductionFailure.Data = FailedAttr;
6611     return;
6612   }
6613 
6614   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6615       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6616     Candidate.Viable = false;
6617     Candidate.FailureKind = ovl_non_default_multiversion_function;
6618   }
6619 }
6620 
6621 /// Add a C++ member function template as a candidate to the candidate
6622 /// set, using template argument deduction to produce an appropriate member
6623 /// function template specialization.
6624 void
6625 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6626                                  DeclAccessPair FoundDecl,
6627                                  CXXRecordDecl *ActingContext,
6628                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6629                                  QualType ObjectType,
6630                                  Expr::Classification ObjectClassification,
6631                                  ArrayRef<Expr *> Args,
6632                                  OverloadCandidateSet& CandidateSet,
6633                                  bool SuppressUserConversions,
6634                                  bool PartialOverloading) {
6635   if (!CandidateSet.isNewCandidate(MethodTmpl))
6636     return;
6637 
6638   // C++ [over.match.funcs]p7:
6639   //   In each case where a candidate is a function template, candidate
6640   //   function template specializations are generated using template argument
6641   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6642   //   candidate functions in the usual way.113) A given name can refer to one
6643   //   or more function templates and also to a set of overloaded non-template
6644   //   functions. In such a case, the candidate functions generated from each
6645   //   function template are combined with the set of non-template candidate
6646   //   functions.
6647   TemplateDeductionInfo Info(CandidateSet.getLocation());
6648   FunctionDecl *Specialization = nullptr;
6649   ConversionSequenceList Conversions;
6650   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6651           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6652           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6653             return CheckNonDependentConversions(
6654                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6655                 SuppressUserConversions, ActingContext, ObjectType,
6656                 ObjectClassification);
6657           })) {
6658     OverloadCandidate &Candidate =
6659         CandidateSet.addCandidate(Conversions.size(), Conversions);
6660     Candidate.FoundDecl = FoundDecl;
6661     Candidate.Function = MethodTmpl->getTemplatedDecl();
6662     Candidate.Viable = false;
6663     Candidate.IsSurrogate = false;
6664     Candidate.IgnoreObjectArgument =
6665         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6666         ObjectType.isNull();
6667     Candidate.ExplicitCallArguments = Args.size();
6668     if (Result == TDK_NonDependentConversionFailure)
6669       Candidate.FailureKind = ovl_fail_bad_conversion;
6670     else {
6671       Candidate.FailureKind = ovl_fail_bad_deduction;
6672       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6673                                                             Info);
6674     }
6675     return;
6676   }
6677 
6678   // Add the function template specialization produced by template argument
6679   // deduction as a candidate.
6680   assert(Specialization && "Missing member function template specialization?");
6681   assert(isa<CXXMethodDecl>(Specialization) &&
6682          "Specialization is not a member function?");
6683   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6684                      ActingContext, ObjectType, ObjectClassification, Args,
6685                      CandidateSet, SuppressUserConversions, PartialOverloading,
6686                      Conversions);
6687 }
6688 
6689 /// Add a C++ function template specialization as a candidate
6690 /// in the candidate set, using template argument deduction to produce
6691 /// an appropriate function template specialization.
6692 void
6693 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6694                                    DeclAccessPair FoundDecl,
6695                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6696                                    ArrayRef<Expr *> Args,
6697                                    OverloadCandidateSet& CandidateSet,
6698                                    bool SuppressUserConversions,
6699                                    bool PartialOverloading) {
6700   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6701     return;
6702 
6703   // C++ [over.match.funcs]p7:
6704   //   In each case where a candidate is a function template, candidate
6705   //   function template specializations are generated using template argument
6706   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6707   //   candidate functions in the usual way.113) A given name can refer to one
6708   //   or more function templates and also to a set of overloaded non-template
6709   //   functions. In such a case, the candidate functions generated from each
6710   //   function template are combined with the set of non-template candidate
6711   //   functions.
6712   TemplateDeductionInfo Info(CandidateSet.getLocation());
6713   FunctionDecl *Specialization = nullptr;
6714   ConversionSequenceList Conversions;
6715   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6716           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6717           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6718             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6719                                                 Args, CandidateSet, Conversions,
6720                                                 SuppressUserConversions);
6721           })) {
6722     OverloadCandidate &Candidate =
6723         CandidateSet.addCandidate(Conversions.size(), Conversions);
6724     Candidate.FoundDecl = FoundDecl;
6725     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6726     Candidate.Viable = false;
6727     Candidate.IsSurrogate = false;
6728     // Ignore the object argument if there is one, since we don't have an object
6729     // type.
6730     Candidate.IgnoreObjectArgument =
6731         isa<CXXMethodDecl>(Candidate.Function) &&
6732         !isa<CXXConstructorDecl>(Candidate.Function);
6733     Candidate.ExplicitCallArguments = Args.size();
6734     if (Result == TDK_NonDependentConversionFailure)
6735       Candidate.FailureKind = ovl_fail_bad_conversion;
6736     else {
6737       Candidate.FailureKind = ovl_fail_bad_deduction;
6738       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6739                                                             Info);
6740     }
6741     return;
6742   }
6743 
6744   // Add the function template specialization produced by template argument
6745   // deduction as a candidate.
6746   assert(Specialization && "Missing function template specialization?");
6747   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6748                        SuppressUserConversions, PartialOverloading,
6749                        /*AllowExplicit*/false, Conversions);
6750 }
6751 
6752 /// Check that implicit conversion sequences can be formed for each argument
6753 /// whose corresponding parameter has a non-dependent type, per DR1391's
6754 /// [temp.deduct.call]p10.
6755 bool Sema::CheckNonDependentConversions(
6756     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6757     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6758     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6759     CXXRecordDecl *ActingContext, QualType ObjectType,
6760     Expr::Classification ObjectClassification) {
6761   // FIXME: The cases in which we allow explicit conversions for constructor
6762   // arguments never consider calling a constructor template. It's not clear
6763   // that is correct.
6764   const bool AllowExplicit = false;
6765 
6766   auto *FD = FunctionTemplate->getTemplatedDecl();
6767   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6768   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6769   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6770 
6771   Conversions =
6772       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6773 
6774   // Overload resolution is always an unevaluated context.
6775   EnterExpressionEvaluationContext Unevaluated(
6776       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6777 
6778   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6779   // require that, but this check should never result in a hard error, and
6780   // overload resolution is permitted to sidestep instantiations.
6781   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6782       !ObjectType.isNull()) {
6783     Conversions[0] = TryObjectArgumentInitialization(
6784         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6785         Method, ActingContext);
6786     if (Conversions[0].isBad())
6787       return true;
6788   }
6789 
6790   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6791        ++I) {
6792     QualType ParamType = ParamTypes[I];
6793     if (!ParamType->isDependentType()) {
6794       Conversions[ThisConversions + I]
6795         = TryCopyInitialization(*this, Args[I], ParamType,
6796                                 SuppressUserConversions,
6797                                 /*InOverloadResolution=*/true,
6798                                 /*AllowObjCWritebackConversion=*/
6799                                   getLangOpts().ObjCAutoRefCount,
6800                                 AllowExplicit);
6801       if (Conversions[ThisConversions + I].isBad())
6802         return true;
6803     }
6804   }
6805 
6806   return false;
6807 }
6808 
6809 /// Determine whether this is an allowable conversion from the result
6810 /// of an explicit conversion operator to the expected type, per C++
6811 /// [over.match.conv]p1 and [over.match.ref]p1.
6812 ///
6813 /// \param ConvType The return type of the conversion function.
6814 ///
6815 /// \param ToType The type we are converting to.
6816 ///
6817 /// \param AllowObjCPointerConversion Allow a conversion from one
6818 /// Objective-C pointer to another.
6819 ///
6820 /// \returns true if the conversion is allowable, false otherwise.
6821 static bool isAllowableExplicitConversion(Sema &S,
6822                                           QualType ConvType, QualType ToType,
6823                                           bool AllowObjCPointerConversion) {
6824   QualType ToNonRefType = ToType.getNonReferenceType();
6825 
6826   // Easy case: the types are the same.
6827   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6828     return true;
6829 
6830   // Allow qualification conversions.
6831   bool ObjCLifetimeConversion;
6832   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6833                                   ObjCLifetimeConversion))
6834     return true;
6835 
6836   // If we're not allowed to consider Objective-C pointer conversions,
6837   // we're done.
6838   if (!AllowObjCPointerConversion)
6839     return false;
6840 
6841   // Is this an Objective-C pointer conversion?
6842   bool IncompatibleObjC = false;
6843   QualType ConvertedType;
6844   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6845                                    IncompatibleObjC);
6846 }
6847 
6848 /// AddConversionCandidate - Add a C++ conversion function as a
6849 /// candidate in the candidate set (C++ [over.match.conv],
6850 /// C++ [over.match.copy]). From is the expression we're converting from,
6851 /// and ToType is the type that we're eventually trying to convert to
6852 /// (which may or may not be the same type as the type that the
6853 /// conversion function produces).
6854 void
6855 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6856                              DeclAccessPair FoundDecl,
6857                              CXXRecordDecl *ActingContext,
6858                              Expr *From, QualType ToType,
6859                              OverloadCandidateSet& CandidateSet,
6860                              bool AllowObjCConversionOnExplicit,
6861                              bool AllowResultConversion) {
6862   assert(!Conversion->getDescribedFunctionTemplate() &&
6863          "Conversion function templates use AddTemplateConversionCandidate");
6864   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6865   if (!CandidateSet.isNewCandidate(Conversion))
6866     return;
6867 
6868   // If the conversion function has an undeduced return type, trigger its
6869   // deduction now.
6870   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6871     if (DeduceReturnType(Conversion, From->getExprLoc()))
6872       return;
6873     ConvType = Conversion->getConversionType().getNonReferenceType();
6874   }
6875 
6876   // If we don't allow any conversion of the result type, ignore conversion
6877   // functions that don't convert to exactly (possibly cv-qualified) T.
6878   if (!AllowResultConversion &&
6879       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6880     return;
6881 
6882   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6883   // operator is only a candidate if its return type is the target type or
6884   // can be converted to the target type with a qualification conversion.
6885   if (Conversion->isExplicit() &&
6886       !isAllowableExplicitConversion(*this, ConvType, ToType,
6887                                      AllowObjCConversionOnExplicit))
6888     return;
6889 
6890   // Overload resolution is always an unevaluated context.
6891   EnterExpressionEvaluationContext Unevaluated(
6892       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6893 
6894   // Add this candidate
6895   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6896   Candidate.FoundDecl = FoundDecl;
6897   Candidate.Function = Conversion;
6898   Candidate.IsSurrogate = false;
6899   Candidate.IgnoreObjectArgument = false;
6900   Candidate.FinalConversion.setAsIdentityConversion();
6901   Candidate.FinalConversion.setFromType(ConvType);
6902   Candidate.FinalConversion.setAllToTypes(ToType);
6903   Candidate.Viable = true;
6904   Candidate.ExplicitCallArguments = 1;
6905 
6906   // C++ [over.match.funcs]p4:
6907   //   For conversion functions, the function is considered to be a member of
6908   //   the class of the implicit implied object argument for the purpose of
6909   //   defining the type of the implicit object parameter.
6910   //
6911   // Determine the implicit conversion sequence for the implicit
6912   // object parameter.
6913   QualType ImplicitParamType = From->getType();
6914   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6915     ImplicitParamType = FromPtrType->getPointeeType();
6916   CXXRecordDecl *ConversionContext
6917     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6918 
6919   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6920       *this, CandidateSet.getLocation(), From->getType(),
6921       From->Classify(Context), Conversion, ConversionContext);
6922 
6923   if (Candidate.Conversions[0].isBad()) {
6924     Candidate.Viable = false;
6925     Candidate.FailureKind = ovl_fail_bad_conversion;
6926     return;
6927   }
6928 
6929   // We won't go through a user-defined type conversion function to convert a
6930   // derived to base as such conversions are given Conversion Rank. They only
6931   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6932   QualType FromCanon
6933     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6934   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6935   if (FromCanon == ToCanon ||
6936       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6937     Candidate.Viable = false;
6938     Candidate.FailureKind = ovl_fail_trivial_conversion;
6939     return;
6940   }
6941 
6942   // To determine what the conversion from the result of calling the
6943   // conversion function to the type we're eventually trying to
6944   // convert to (ToType), we need to synthesize a call to the
6945   // conversion function and attempt copy initialization from it. This
6946   // makes sure that we get the right semantics with respect to
6947   // lvalues/rvalues and the type. Fortunately, we can allocate this
6948   // call on the stack and we don't need its arguments to be
6949   // well-formed.
6950   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6951                             VK_LValue, From->getLocStart());
6952   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6953                                 Context.getPointerType(Conversion->getType()),
6954                                 CK_FunctionToPointerDecay,
6955                                 &ConversionRef, VK_RValue);
6956 
6957   QualType ConversionType = Conversion->getConversionType();
6958   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6959     Candidate.Viable = false;
6960     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6961     return;
6962   }
6963 
6964   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6965 
6966   // Note that it is safe to allocate CallExpr on the stack here because
6967   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6968   // allocator).
6969   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6970   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6971                 From->getLocStart());
6972   ImplicitConversionSequence ICS =
6973     TryCopyInitialization(*this, &Call, ToType,
6974                           /*SuppressUserConversions=*/true,
6975                           /*InOverloadResolution=*/false,
6976                           /*AllowObjCWritebackConversion=*/false);
6977 
6978   switch (ICS.getKind()) {
6979   case ImplicitConversionSequence::StandardConversion:
6980     Candidate.FinalConversion = ICS.Standard;
6981 
6982     // C++ [over.ics.user]p3:
6983     //   If the user-defined conversion is specified by a specialization of a
6984     //   conversion function template, the second standard conversion sequence
6985     //   shall have exact match rank.
6986     if (Conversion->getPrimaryTemplate() &&
6987         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6988       Candidate.Viable = false;
6989       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6990       return;
6991     }
6992 
6993     // C++0x [dcl.init.ref]p5:
6994     //    In the second case, if the reference is an rvalue reference and
6995     //    the second standard conversion sequence of the user-defined
6996     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6997     //    program is ill-formed.
6998     if (ToType->isRValueReferenceType() &&
6999         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7000       Candidate.Viable = false;
7001       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7002       return;
7003     }
7004     break;
7005 
7006   case ImplicitConversionSequence::BadConversion:
7007     Candidate.Viable = false;
7008     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7009     return;
7010 
7011   default:
7012     llvm_unreachable(
7013            "Can only end up with a standard conversion sequence or failure");
7014   }
7015 
7016   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7017     Candidate.Viable = false;
7018     Candidate.FailureKind = ovl_fail_enable_if;
7019     Candidate.DeductionFailure.Data = FailedAttr;
7020     return;
7021   }
7022 
7023   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7024       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7025     Candidate.Viable = false;
7026     Candidate.FailureKind = ovl_non_default_multiversion_function;
7027   }
7028 }
7029 
7030 /// Adds a conversion function template specialization
7031 /// candidate to the overload set, using template argument deduction
7032 /// to deduce the template arguments of the conversion function
7033 /// template from the type that we are converting to (C++
7034 /// [temp.deduct.conv]).
7035 void
7036 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7037                                      DeclAccessPair FoundDecl,
7038                                      CXXRecordDecl *ActingDC,
7039                                      Expr *From, QualType ToType,
7040                                      OverloadCandidateSet &CandidateSet,
7041                                      bool AllowObjCConversionOnExplicit,
7042                                      bool AllowResultConversion) {
7043   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7044          "Only conversion function templates permitted here");
7045 
7046   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7047     return;
7048 
7049   TemplateDeductionInfo Info(CandidateSet.getLocation());
7050   CXXConversionDecl *Specialization = nullptr;
7051   if (TemplateDeductionResult Result
7052         = DeduceTemplateArguments(FunctionTemplate, ToType,
7053                                   Specialization, Info)) {
7054     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7055     Candidate.FoundDecl = FoundDecl;
7056     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7057     Candidate.Viable = false;
7058     Candidate.FailureKind = ovl_fail_bad_deduction;
7059     Candidate.IsSurrogate = false;
7060     Candidate.IgnoreObjectArgument = false;
7061     Candidate.ExplicitCallArguments = 1;
7062     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7063                                                           Info);
7064     return;
7065   }
7066 
7067   // Add the conversion function template specialization produced by
7068   // template argument deduction as a candidate.
7069   assert(Specialization && "Missing function template specialization?");
7070   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7071                          CandidateSet, AllowObjCConversionOnExplicit,
7072                          AllowResultConversion);
7073 }
7074 
7075 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7076 /// converts the given @c Object to a function pointer via the
7077 /// conversion function @c Conversion, and then attempts to call it
7078 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7079 /// the type of function that we'll eventually be calling.
7080 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7081                                  DeclAccessPair FoundDecl,
7082                                  CXXRecordDecl *ActingContext,
7083                                  const FunctionProtoType *Proto,
7084                                  Expr *Object,
7085                                  ArrayRef<Expr *> Args,
7086                                  OverloadCandidateSet& CandidateSet) {
7087   if (!CandidateSet.isNewCandidate(Conversion))
7088     return;
7089 
7090   // Overload resolution is always an unevaluated context.
7091   EnterExpressionEvaluationContext Unevaluated(
7092       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7093 
7094   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7095   Candidate.FoundDecl = FoundDecl;
7096   Candidate.Function = nullptr;
7097   Candidate.Surrogate = Conversion;
7098   Candidate.Viable = true;
7099   Candidate.IsSurrogate = true;
7100   Candidate.IgnoreObjectArgument = false;
7101   Candidate.ExplicitCallArguments = Args.size();
7102 
7103   // Determine the implicit conversion sequence for the implicit
7104   // object parameter.
7105   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7106       *this, CandidateSet.getLocation(), Object->getType(),
7107       Object->Classify(Context), Conversion, ActingContext);
7108   if (ObjectInit.isBad()) {
7109     Candidate.Viable = false;
7110     Candidate.FailureKind = ovl_fail_bad_conversion;
7111     Candidate.Conversions[0] = ObjectInit;
7112     return;
7113   }
7114 
7115   // The first conversion is actually a user-defined conversion whose
7116   // first conversion is ObjectInit's standard conversion (which is
7117   // effectively a reference binding). Record it as such.
7118   Candidate.Conversions[0].setUserDefined();
7119   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7120   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7121   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7122   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7123   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7124   Candidate.Conversions[0].UserDefined.After
7125     = Candidate.Conversions[0].UserDefined.Before;
7126   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7127 
7128   // Find the
7129   unsigned NumParams = Proto->getNumParams();
7130 
7131   // (C++ 13.3.2p2): A candidate function having fewer than m
7132   // parameters is viable only if it has an ellipsis in its parameter
7133   // list (8.3.5).
7134   if (Args.size() > NumParams && !Proto->isVariadic()) {
7135     Candidate.Viable = false;
7136     Candidate.FailureKind = ovl_fail_too_many_arguments;
7137     return;
7138   }
7139 
7140   // Function types don't have any default arguments, so just check if
7141   // we have enough arguments.
7142   if (Args.size() < NumParams) {
7143     // Not enough arguments.
7144     Candidate.Viable = false;
7145     Candidate.FailureKind = ovl_fail_too_few_arguments;
7146     return;
7147   }
7148 
7149   // Determine the implicit conversion sequences for each of the
7150   // arguments.
7151   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7152     if (ArgIdx < NumParams) {
7153       // (C++ 13.3.2p3): for F to be a viable function, there shall
7154       // exist for each argument an implicit conversion sequence
7155       // (13.3.3.1) that converts that argument to the corresponding
7156       // parameter of F.
7157       QualType ParamType = Proto->getParamType(ArgIdx);
7158       Candidate.Conversions[ArgIdx + 1]
7159         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7160                                 /*SuppressUserConversions=*/false,
7161                                 /*InOverloadResolution=*/false,
7162                                 /*AllowObjCWritebackConversion=*/
7163                                   getLangOpts().ObjCAutoRefCount);
7164       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7165         Candidate.Viable = false;
7166         Candidate.FailureKind = ovl_fail_bad_conversion;
7167         return;
7168       }
7169     } else {
7170       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7171       // argument for which there is no corresponding parameter is
7172       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7173       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7174     }
7175   }
7176 
7177   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7178     Candidate.Viable = false;
7179     Candidate.FailureKind = ovl_fail_enable_if;
7180     Candidate.DeductionFailure.Data = FailedAttr;
7181     return;
7182   }
7183 }
7184 
7185 /// Add overload candidates for overloaded operators that are
7186 /// member functions.
7187 ///
7188 /// Add the overloaded operator candidates that are member functions
7189 /// for the operator Op that was used in an operator expression such
7190 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7191 /// CandidateSet will store the added overload candidates. (C++
7192 /// [over.match.oper]).
7193 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7194                                        SourceLocation OpLoc,
7195                                        ArrayRef<Expr *> Args,
7196                                        OverloadCandidateSet& CandidateSet,
7197                                        SourceRange OpRange) {
7198   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7199 
7200   // C++ [over.match.oper]p3:
7201   //   For a unary operator @ with an operand of a type whose
7202   //   cv-unqualified version is T1, and for a binary operator @ with
7203   //   a left operand of a type whose cv-unqualified version is T1 and
7204   //   a right operand of a type whose cv-unqualified version is T2,
7205   //   three sets of candidate functions, designated member
7206   //   candidates, non-member candidates and built-in candidates, are
7207   //   constructed as follows:
7208   QualType T1 = Args[0]->getType();
7209 
7210   //     -- If T1 is a complete class type or a class currently being
7211   //        defined, the set of member candidates is the result of the
7212   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7213   //        the set of member candidates is empty.
7214   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7215     // Complete the type if it can be completed.
7216     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7217       return;
7218     // If the type is neither complete nor being defined, bail out now.
7219     if (!T1Rec->getDecl()->getDefinition())
7220       return;
7221 
7222     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7223     LookupQualifiedName(Operators, T1Rec->getDecl());
7224     Operators.suppressDiagnostics();
7225 
7226     for (LookupResult::iterator Oper = Operators.begin(),
7227                              OperEnd = Operators.end();
7228          Oper != OperEnd;
7229          ++Oper)
7230       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7231                          Args[0]->Classify(Context), Args.slice(1),
7232                          CandidateSet, /*SuppressUserConversions=*/false);
7233   }
7234 }
7235 
7236 /// AddBuiltinCandidate - Add a candidate for a built-in
7237 /// operator. ResultTy and ParamTys are the result and parameter types
7238 /// of the built-in candidate, respectively. Args and NumArgs are the
7239 /// arguments being passed to the candidate. IsAssignmentOperator
7240 /// should be true when this built-in candidate is an assignment
7241 /// operator. NumContextualBoolArguments is the number of arguments
7242 /// (at the beginning of the argument list) that will be contextually
7243 /// converted to bool.
7244 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7245                                OverloadCandidateSet& CandidateSet,
7246                                bool IsAssignmentOperator,
7247                                unsigned NumContextualBoolArguments) {
7248   // Overload resolution is always an unevaluated context.
7249   EnterExpressionEvaluationContext Unevaluated(
7250       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7251 
7252   // Add this candidate
7253   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7254   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7255   Candidate.Function = nullptr;
7256   Candidate.IsSurrogate = false;
7257   Candidate.IgnoreObjectArgument = false;
7258   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7259 
7260   // Determine the implicit conversion sequences for each of the
7261   // arguments.
7262   Candidate.Viable = true;
7263   Candidate.ExplicitCallArguments = Args.size();
7264   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7265     // C++ [over.match.oper]p4:
7266     //   For the built-in assignment operators, conversions of the
7267     //   left operand are restricted as follows:
7268     //     -- no temporaries are introduced to hold the left operand, and
7269     //     -- no user-defined conversions are applied to the left
7270     //        operand to achieve a type match with the left-most
7271     //        parameter of a built-in candidate.
7272     //
7273     // We block these conversions by turning off user-defined
7274     // conversions, since that is the only way that initialization of
7275     // a reference to a non-class type can occur from something that
7276     // is not of the same type.
7277     if (ArgIdx < NumContextualBoolArguments) {
7278       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7279              "Contextual conversion to bool requires bool type");
7280       Candidate.Conversions[ArgIdx]
7281         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7282     } else {
7283       Candidate.Conversions[ArgIdx]
7284         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7285                                 ArgIdx == 0 && IsAssignmentOperator,
7286                                 /*InOverloadResolution=*/false,
7287                                 /*AllowObjCWritebackConversion=*/
7288                                   getLangOpts().ObjCAutoRefCount);
7289     }
7290     if (Candidate.Conversions[ArgIdx].isBad()) {
7291       Candidate.Viable = false;
7292       Candidate.FailureKind = ovl_fail_bad_conversion;
7293       break;
7294     }
7295   }
7296 }
7297 
7298 namespace {
7299 
7300 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7301 /// candidate operator functions for built-in operators (C++
7302 /// [over.built]). The types are separated into pointer types and
7303 /// enumeration types.
7304 class BuiltinCandidateTypeSet  {
7305   /// TypeSet - A set of types.
7306   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7307                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7308 
7309   /// PointerTypes - The set of pointer types that will be used in the
7310   /// built-in candidates.
7311   TypeSet PointerTypes;
7312 
7313   /// MemberPointerTypes - The set of member pointer types that will be
7314   /// used in the built-in candidates.
7315   TypeSet MemberPointerTypes;
7316 
7317   /// EnumerationTypes - The set of enumeration types that will be
7318   /// used in the built-in candidates.
7319   TypeSet EnumerationTypes;
7320 
7321   /// The set of vector types that will be used in the built-in
7322   /// candidates.
7323   TypeSet VectorTypes;
7324 
7325   /// A flag indicating non-record types are viable candidates
7326   bool HasNonRecordTypes;
7327 
7328   /// A flag indicating whether either arithmetic or enumeration types
7329   /// were present in the candidate set.
7330   bool HasArithmeticOrEnumeralTypes;
7331 
7332   /// A flag indicating whether the nullptr type was present in the
7333   /// candidate set.
7334   bool HasNullPtrType;
7335 
7336   /// Sema - The semantic analysis instance where we are building the
7337   /// candidate type set.
7338   Sema &SemaRef;
7339 
7340   /// Context - The AST context in which we will build the type sets.
7341   ASTContext &Context;
7342 
7343   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7344                                                const Qualifiers &VisibleQuals);
7345   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7346 
7347 public:
7348   /// iterator - Iterates through the types that are part of the set.
7349   typedef TypeSet::iterator iterator;
7350 
7351   BuiltinCandidateTypeSet(Sema &SemaRef)
7352     : HasNonRecordTypes(false),
7353       HasArithmeticOrEnumeralTypes(false),
7354       HasNullPtrType(false),
7355       SemaRef(SemaRef),
7356       Context(SemaRef.Context) { }
7357 
7358   void AddTypesConvertedFrom(QualType Ty,
7359                              SourceLocation Loc,
7360                              bool AllowUserConversions,
7361                              bool AllowExplicitConversions,
7362                              const Qualifiers &VisibleTypeConversionsQuals);
7363 
7364   /// pointer_begin - First pointer type found;
7365   iterator pointer_begin() { return PointerTypes.begin(); }
7366 
7367   /// pointer_end - Past the last pointer type found;
7368   iterator pointer_end() { return PointerTypes.end(); }
7369 
7370   /// member_pointer_begin - First member pointer type found;
7371   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7372 
7373   /// member_pointer_end - Past the last member pointer type found;
7374   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7375 
7376   /// enumeration_begin - First enumeration type found;
7377   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7378 
7379   /// enumeration_end - Past the last enumeration type found;
7380   iterator enumeration_end() { return EnumerationTypes.end(); }
7381 
7382   iterator vector_begin() { return VectorTypes.begin(); }
7383   iterator vector_end() { return VectorTypes.end(); }
7384 
7385   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7386   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7387   bool hasNullPtrType() const { return HasNullPtrType; }
7388 };
7389 
7390 } // end anonymous namespace
7391 
7392 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7393 /// the set of pointer types along with any more-qualified variants of
7394 /// that type. For example, if @p Ty is "int const *", this routine
7395 /// will add "int const *", "int const volatile *", "int const
7396 /// restrict *", and "int const volatile restrict *" to the set of
7397 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7398 /// false otherwise.
7399 ///
7400 /// FIXME: what to do about extended qualifiers?
7401 bool
7402 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7403                                              const Qualifiers &VisibleQuals) {
7404 
7405   // Insert this type.
7406   if (!PointerTypes.insert(Ty))
7407     return false;
7408 
7409   QualType PointeeTy;
7410   const PointerType *PointerTy = Ty->getAs<PointerType>();
7411   bool buildObjCPtr = false;
7412   if (!PointerTy) {
7413     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7414     PointeeTy = PTy->getPointeeType();
7415     buildObjCPtr = true;
7416   } else {
7417     PointeeTy = PointerTy->getPointeeType();
7418   }
7419 
7420   // Don't add qualified variants of arrays. For one, they're not allowed
7421   // (the qualifier would sink to the element type), and for another, the
7422   // only overload situation where it matters is subscript or pointer +- int,
7423   // and those shouldn't have qualifier variants anyway.
7424   if (PointeeTy->isArrayType())
7425     return true;
7426 
7427   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7428   bool hasVolatile = VisibleQuals.hasVolatile();
7429   bool hasRestrict = VisibleQuals.hasRestrict();
7430 
7431   // Iterate through all strict supersets of BaseCVR.
7432   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7433     if ((CVR | BaseCVR) != CVR) continue;
7434     // Skip over volatile if no volatile found anywhere in the types.
7435     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7436 
7437     // Skip over restrict if no restrict found anywhere in the types, or if
7438     // the type cannot be restrict-qualified.
7439     if ((CVR & Qualifiers::Restrict) &&
7440         (!hasRestrict ||
7441          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7442       continue;
7443 
7444     // Build qualified pointee type.
7445     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7446 
7447     // Build qualified pointer type.
7448     QualType QPointerTy;
7449     if (!buildObjCPtr)
7450       QPointerTy = Context.getPointerType(QPointeeTy);
7451     else
7452       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7453 
7454     // Insert qualified pointer type.
7455     PointerTypes.insert(QPointerTy);
7456   }
7457 
7458   return true;
7459 }
7460 
7461 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7462 /// to the set of pointer types along with any more-qualified variants of
7463 /// that type. For example, if @p Ty is "int const *", this routine
7464 /// will add "int const *", "int const volatile *", "int const
7465 /// restrict *", and "int const volatile restrict *" to the set of
7466 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7467 /// false otherwise.
7468 ///
7469 /// FIXME: what to do about extended qualifiers?
7470 bool
7471 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7472     QualType Ty) {
7473   // Insert this type.
7474   if (!MemberPointerTypes.insert(Ty))
7475     return false;
7476 
7477   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7478   assert(PointerTy && "type was not a member pointer type!");
7479 
7480   QualType PointeeTy = PointerTy->getPointeeType();
7481   // Don't add qualified variants of arrays. For one, they're not allowed
7482   // (the qualifier would sink to the element type), and for another, the
7483   // only overload situation where it matters is subscript or pointer +- int,
7484   // and those shouldn't have qualifier variants anyway.
7485   if (PointeeTy->isArrayType())
7486     return true;
7487   const Type *ClassTy = PointerTy->getClass();
7488 
7489   // Iterate through all strict supersets of the pointee type's CVR
7490   // qualifiers.
7491   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7492   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7493     if ((CVR | BaseCVR) != CVR) continue;
7494 
7495     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7496     MemberPointerTypes.insert(
7497       Context.getMemberPointerType(QPointeeTy, ClassTy));
7498   }
7499 
7500   return true;
7501 }
7502 
7503 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7504 /// Ty can be implicit converted to the given set of @p Types. We're
7505 /// primarily interested in pointer types and enumeration types. We also
7506 /// take member pointer types, for the conditional operator.
7507 /// AllowUserConversions is true if we should look at the conversion
7508 /// functions of a class type, and AllowExplicitConversions if we
7509 /// should also include the explicit conversion functions of a class
7510 /// type.
7511 void
7512 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7513                                                SourceLocation Loc,
7514                                                bool AllowUserConversions,
7515                                                bool AllowExplicitConversions,
7516                                                const Qualifiers &VisibleQuals) {
7517   // Only deal with canonical types.
7518   Ty = Context.getCanonicalType(Ty);
7519 
7520   // Look through reference types; they aren't part of the type of an
7521   // expression for the purposes of conversions.
7522   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7523     Ty = RefTy->getPointeeType();
7524 
7525   // If we're dealing with an array type, decay to the pointer.
7526   if (Ty->isArrayType())
7527     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7528 
7529   // Otherwise, we don't care about qualifiers on the type.
7530   Ty = Ty.getLocalUnqualifiedType();
7531 
7532   // Flag if we ever add a non-record type.
7533   const RecordType *TyRec = Ty->getAs<RecordType>();
7534   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7535 
7536   // Flag if we encounter an arithmetic type.
7537   HasArithmeticOrEnumeralTypes =
7538     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7539 
7540   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7541     PointerTypes.insert(Ty);
7542   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7543     // Insert our type, and its more-qualified variants, into the set
7544     // of types.
7545     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7546       return;
7547   } else if (Ty->isMemberPointerType()) {
7548     // Member pointers are far easier, since the pointee can't be converted.
7549     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7550       return;
7551   } else if (Ty->isEnumeralType()) {
7552     HasArithmeticOrEnumeralTypes = true;
7553     EnumerationTypes.insert(Ty);
7554   } else if (Ty->isVectorType()) {
7555     // We treat vector types as arithmetic types in many contexts as an
7556     // extension.
7557     HasArithmeticOrEnumeralTypes = true;
7558     VectorTypes.insert(Ty);
7559   } else if (Ty->isNullPtrType()) {
7560     HasNullPtrType = true;
7561   } else if (AllowUserConversions && TyRec) {
7562     // No conversion functions in incomplete types.
7563     if (!SemaRef.isCompleteType(Loc, Ty))
7564       return;
7565 
7566     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7567     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7568       if (isa<UsingShadowDecl>(D))
7569         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7570 
7571       // Skip conversion function templates; they don't tell us anything
7572       // about which builtin types we can convert to.
7573       if (isa<FunctionTemplateDecl>(D))
7574         continue;
7575 
7576       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7577       if (AllowExplicitConversions || !Conv->isExplicit()) {
7578         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7579                               VisibleQuals);
7580       }
7581     }
7582   }
7583 }
7584 
7585 /// Helper function for AddBuiltinOperatorCandidates() that adds
7586 /// the volatile- and non-volatile-qualified assignment operators for the
7587 /// given type to the candidate set.
7588 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7589                                                    QualType T,
7590                                                    ArrayRef<Expr *> Args,
7591                                     OverloadCandidateSet &CandidateSet) {
7592   QualType ParamTypes[2];
7593 
7594   // T& operator=(T&, T)
7595   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7596   ParamTypes[1] = T;
7597   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7598                         /*IsAssignmentOperator=*/true);
7599 
7600   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7601     // volatile T& operator=(volatile T&, T)
7602     ParamTypes[0]
7603       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7604     ParamTypes[1] = T;
7605     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7606                           /*IsAssignmentOperator=*/true);
7607   }
7608 }
7609 
7610 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7611 /// if any, found in visible type conversion functions found in ArgExpr's type.
7612 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7613     Qualifiers VRQuals;
7614     const RecordType *TyRec;
7615     if (const MemberPointerType *RHSMPType =
7616         ArgExpr->getType()->getAs<MemberPointerType>())
7617       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7618     else
7619       TyRec = ArgExpr->getType()->getAs<RecordType>();
7620     if (!TyRec) {
7621       // Just to be safe, assume the worst case.
7622       VRQuals.addVolatile();
7623       VRQuals.addRestrict();
7624       return VRQuals;
7625     }
7626 
7627     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7628     if (!ClassDecl->hasDefinition())
7629       return VRQuals;
7630 
7631     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7632       if (isa<UsingShadowDecl>(D))
7633         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7634       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7635         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7636         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7637           CanTy = ResTypeRef->getPointeeType();
7638         // Need to go down the pointer/mempointer chain and add qualifiers
7639         // as see them.
7640         bool done = false;
7641         while (!done) {
7642           if (CanTy.isRestrictQualified())
7643             VRQuals.addRestrict();
7644           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7645             CanTy = ResTypePtr->getPointeeType();
7646           else if (const MemberPointerType *ResTypeMPtr =
7647                 CanTy->getAs<MemberPointerType>())
7648             CanTy = ResTypeMPtr->getPointeeType();
7649           else
7650             done = true;
7651           if (CanTy.isVolatileQualified())
7652             VRQuals.addVolatile();
7653           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7654             return VRQuals;
7655         }
7656       }
7657     }
7658     return VRQuals;
7659 }
7660 
7661 namespace {
7662 
7663 /// Helper class to manage the addition of builtin operator overload
7664 /// candidates. It provides shared state and utility methods used throughout
7665 /// the process, as well as a helper method to add each group of builtin
7666 /// operator overloads from the standard to a candidate set.
7667 class BuiltinOperatorOverloadBuilder {
7668   // Common instance state available to all overload candidate addition methods.
7669   Sema &S;
7670   ArrayRef<Expr *> Args;
7671   Qualifiers VisibleTypeConversionsQuals;
7672   bool HasArithmeticOrEnumeralCandidateType;
7673   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7674   OverloadCandidateSet &CandidateSet;
7675 
7676   static constexpr int ArithmeticTypesCap = 24;
7677   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7678 
7679   // Define some indices used to iterate over the arithemetic types in
7680   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7681   // types are that preserved by promotion (C++ [over.built]p2).
7682   unsigned FirstIntegralType,
7683            LastIntegralType;
7684   unsigned FirstPromotedIntegralType,
7685            LastPromotedIntegralType;
7686   unsigned FirstPromotedArithmeticType,
7687            LastPromotedArithmeticType;
7688   unsigned NumArithmeticTypes;
7689 
7690   void InitArithmeticTypes() {
7691     // Start of promoted types.
7692     FirstPromotedArithmeticType = 0;
7693     ArithmeticTypes.push_back(S.Context.FloatTy);
7694     ArithmeticTypes.push_back(S.Context.DoubleTy);
7695     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7696     if (S.Context.getTargetInfo().hasFloat128Type())
7697       ArithmeticTypes.push_back(S.Context.Float128Ty);
7698 
7699     // Start of integral types.
7700     FirstIntegralType = ArithmeticTypes.size();
7701     FirstPromotedIntegralType = ArithmeticTypes.size();
7702     ArithmeticTypes.push_back(S.Context.IntTy);
7703     ArithmeticTypes.push_back(S.Context.LongTy);
7704     ArithmeticTypes.push_back(S.Context.LongLongTy);
7705     if (S.Context.getTargetInfo().hasInt128Type())
7706       ArithmeticTypes.push_back(S.Context.Int128Ty);
7707     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7708     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7709     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7710     if (S.Context.getTargetInfo().hasInt128Type())
7711       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7712     LastPromotedIntegralType = ArithmeticTypes.size();
7713     LastPromotedArithmeticType = ArithmeticTypes.size();
7714     // End of promoted types.
7715 
7716     ArithmeticTypes.push_back(S.Context.BoolTy);
7717     ArithmeticTypes.push_back(S.Context.CharTy);
7718     ArithmeticTypes.push_back(S.Context.WCharTy);
7719     if (S.Context.getLangOpts().Char8)
7720       ArithmeticTypes.push_back(S.Context.Char8Ty);
7721     ArithmeticTypes.push_back(S.Context.Char16Ty);
7722     ArithmeticTypes.push_back(S.Context.Char32Ty);
7723     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7724     ArithmeticTypes.push_back(S.Context.ShortTy);
7725     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7726     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7727     LastIntegralType = ArithmeticTypes.size();
7728     NumArithmeticTypes = ArithmeticTypes.size();
7729     // End of integral types.
7730     // FIXME: What about complex? What about half?
7731 
7732     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7733            "Enough inline storage for all arithmetic types.");
7734   }
7735 
7736   /// Helper method to factor out the common pattern of adding overloads
7737   /// for '++' and '--' builtin operators.
7738   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7739                                            bool HasVolatile,
7740                                            bool HasRestrict) {
7741     QualType ParamTypes[2] = {
7742       S.Context.getLValueReferenceType(CandidateTy),
7743       S.Context.IntTy
7744     };
7745 
7746     // Non-volatile version.
7747     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7748 
7749     // Use a heuristic to reduce number of builtin candidates in the set:
7750     // add volatile version only if there are conversions to a volatile type.
7751     if (HasVolatile) {
7752       ParamTypes[0] =
7753         S.Context.getLValueReferenceType(
7754           S.Context.getVolatileType(CandidateTy));
7755       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7756     }
7757 
7758     // Add restrict version only if there are conversions to a restrict type
7759     // and our candidate type is a non-restrict-qualified pointer.
7760     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7761         !CandidateTy.isRestrictQualified()) {
7762       ParamTypes[0]
7763         = S.Context.getLValueReferenceType(
7764             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7765       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7766 
7767       if (HasVolatile) {
7768         ParamTypes[0]
7769           = S.Context.getLValueReferenceType(
7770               S.Context.getCVRQualifiedType(CandidateTy,
7771                                             (Qualifiers::Volatile |
7772                                              Qualifiers::Restrict)));
7773         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7774       }
7775     }
7776 
7777   }
7778 
7779 public:
7780   BuiltinOperatorOverloadBuilder(
7781     Sema &S, ArrayRef<Expr *> Args,
7782     Qualifiers VisibleTypeConversionsQuals,
7783     bool HasArithmeticOrEnumeralCandidateType,
7784     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7785     OverloadCandidateSet &CandidateSet)
7786     : S(S), Args(Args),
7787       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7788       HasArithmeticOrEnumeralCandidateType(
7789         HasArithmeticOrEnumeralCandidateType),
7790       CandidateTypes(CandidateTypes),
7791       CandidateSet(CandidateSet) {
7792 
7793     InitArithmeticTypes();
7794   }
7795 
7796   // Increment is deprecated for bool since C++17.
7797   //
7798   // C++ [over.built]p3:
7799   //
7800   //   For every pair (T, VQ), where T is an arithmetic type other
7801   //   than bool, and VQ is either volatile or empty, there exist
7802   //   candidate operator functions of the form
7803   //
7804   //       VQ T&      operator++(VQ T&);
7805   //       T          operator++(VQ T&, int);
7806   //
7807   // C++ [over.built]p4:
7808   //
7809   //   For every pair (T, VQ), where T is an arithmetic type other
7810   //   than bool, and VQ is either volatile or empty, there exist
7811   //   candidate operator functions of the form
7812   //
7813   //       VQ T&      operator--(VQ T&);
7814   //       T          operator--(VQ T&, int);
7815   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7816     if (!HasArithmeticOrEnumeralCandidateType)
7817       return;
7818 
7819     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7820       const auto TypeOfT = ArithmeticTypes[Arith];
7821       if (TypeOfT == S.Context.BoolTy) {
7822         if (Op == OO_MinusMinus)
7823           continue;
7824         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7825           continue;
7826       }
7827       addPlusPlusMinusMinusStyleOverloads(
7828         TypeOfT,
7829         VisibleTypeConversionsQuals.hasVolatile(),
7830         VisibleTypeConversionsQuals.hasRestrict());
7831     }
7832   }
7833 
7834   // C++ [over.built]p5:
7835   //
7836   //   For every pair (T, VQ), where T is a cv-qualified or
7837   //   cv-unqualified object type, and VQ is either volatile or
7838   //   empty, there exist candidate operator functions of the form
7839   //
7840   //       T*VQ&      operator++(T*VQ&);
7841   //       T*VQ&      operator--(T*VQ&);
7842   //       T*         operator++(T*VQ&, int);
7843   //       T*         operator--(T*VQ&, int);
7844   void addPlusPlusMinusMinusPointerOverloads() {
7845     for (BuiltinCandidateTypeSet::iterator
7846               Ptr = CandidateTypes[0].pointer_begin(),
7847            PtrEnd = CandidateTypes[0].pointer_end();
7848          Ptr != PtrEnd; ++Ptr) {
7849       // Skip pointer types that aren't pointers to object types.
7850       if (!(*Ptr)->getPointeeType()->isObjectType())
7851         continue;
7852 
7853       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7854         (!(*Ptr).isVolatileQualified() &&
7855          VisibleTypeConversionsQuals.hasVolatile()),
7856         (!(*Ptr).isRestrictQualified() &&
7857          VisibleTypeConversionsQuals.hasRestrict()));
7858     }
7859   }
7860 
7861   // C++ [over.built]p6:
7862   //   For every cv-qualified or cv-unqualified object type T, there
7863   //   exist candidate operator functions of the form
7864   //
7865   //       T&         operator*(T*);
7866   //
7867   // C++ [over.built]p7:
7868   //   For every function type T that does not have cv-qualifiers or a
7869   //   ref-qualifier, there exist candidate operator functions of the form
7870   //       T&         operator*(T*);
7871   void addUnaryStarPointerOverloads() {
7872     for (BuiltinCandidateTypeSet::iterator
7873               Ptr = CandidateTypes[0].pointer_begin(),
7874            PtrEnd = CandidateTypes[0].pointer_end();
7875          Ptr != PtrEnd; ++Ptr) {
7876       QualType ParamTy = *Ptr;
7877       QualType PointeeTy = ParamTy->getPointeeType();
7878       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7879         continue;
7880 
7881       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7882         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7883           continue;
7884 
7885       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7886     }
7887   }
7888 
7889   // C++ [over.built]p9:
7890   //  For every promoted arithmetic type T, there exist candidate
7891   //  operator functions of the form
7892   //
7893   //       T         operator+(T);
7894   //       T         operator-(T);
7895   void addUnaryPlusOrMinusArithmeticOverloads() {
7896     if (!HasArithmeticOrEnumeralCandidateType)
7897       return;
7898 
7899     for (unsigned Arith = FirstPromotedArithmeticType;
7900          Arith < LastPromotedArithmeticType; ++Arith) {
7901       QualType ArithTy = ArithmeticTypes[Arith];
7902       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7903     }
7904 
7905     // Extension: We also add these operators for vector types.
7906     for (BuiltinCandidateTypeSet::iterator
7907               Vec = CandidateTypes[0].vector_begin(),
7908            VecEnd = CandidateTypes[0].vector_end();
7909          Vec != VecEnd; ++Vec) {
7910       QualType VecTy = *Vec;
7911       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7912     }
7913   }
7914 
7915   // C++ [over.built]p8:
7916   //   For every type T, there exist candidate operator functions of
7917   //   the form
7918   //
7919   //       T*         operator+(T*);
7920   void addUnaryPlusPointerOverloads() {
7921     for (BuiltinCandidateTypeSet::iterator
7922               Ptr = CandidateTypes[0].pointer_begin(),
7923            PtrEnd = CandidateTypes[0].pointer_end();
7924          Ptr != PtrEnd; ++Ptr) {
7925       QualType ParamTy = *Ptr;
7926       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7927     }
7928   }
7929 
7930   // C++ [over.built]p10:
7931   //   For every promoted integral type T, there exist candidate
7932   //   operator functions of the form
7933   //
7934   //        T         operator~(T);
7935   void addUnaryTildePromotedIntegralOverloads() {
7936     if (!HasArithmeticOrEnumeralCandidateType)
7937       return;
7938 
7939     for (unsigned Int = FirstPromotedIntegralType;
7940          Int < LastPromotedIntegralType; ++Int) {
7941       QualType IntTy = ArithmeticTypes[Int];
7942       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7943     }
7944 
7945     // Extension: We also add this operator for vector types.
7946     for (BuiltinCandidateTypeSet::iterator
7947               Vec = CandidateTypes[0].vector_begin(),
7948            VecEnd = CandidateTypes[0].vector_end();
7949          Vec != VecEnd; ++Vec) {
7950       QualType VecTy = *Vec;
7951       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7952     }
7953   }
7954 
7955   // C++ [over.match.oper]p16:
7956   //   For every pointer to member type T or type std::nullptr_t, there
7957   //   exist candidate operator functions of the form
7958   //
7959   //        bool operator==(T,T);
7960   //        bool operator!=(T,T);
7961   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7962     /// Set of (canonical) types that we've already handled.
7963     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7964 
7965     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7966       for (BuiltinCandidateTypeSet::iterator
7967                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7968              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7969            MemPtr != MemPtrEnd;
7970            ++MemPtr) {
7971         // Don't add the same builtin candidate twice.
7972         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7973           continue;
7974 
7975         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7976         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7977       }
7978 
7979       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7980         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7981         if (AddedTypes.insert(NullPtrTy).second) {
7982           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7983           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7984         }
7985       }
7986     }
7987   }
7988 
7989   // C++ [over.built]p15:
7990   //
7991   //   For every T, where T is an enumeration type or a pointer type,
7992   //   there exist candidate operator functions of the form
7993   //
7994   //        bool       operator<(T, T);
7995   //        bool       operator>(T, T);
7996   //        bool       operator<=(T, T);
7997   //        bool       operator>=(T, T);
7998   //        bool       operator==(T, T);
7999   //        bool       operator!=(T, T);
8000   //           R       operator<=>(T, T)
8001   void addGenericBinaryPointerOrEnumeralOverloads() {
8002     // C++ [over.match.oper]p3:
8003     //   [...]the built-in candidates include all of the candidate operator
8004     //   functions defined in 13.6 that, compared to the given operator, [...]
8005     //   do not have the same parameter-type-list as any non-template non-member
8006     //   candidate.
8007     //
8008     // Note that in practice, this only affects enumeration types because there
8009     // aren't any built-in candidates of record type, and a user-defined operator
8010     // must have an operand of record or enumeration type. Also, the only other
8011     // overloaded operator with enumeration arguments, operator=,
8012     // cannot be overloaded for enumeration types, so this is the only place
8013     // where we must suppress candidates like this.
8014     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8015       UserDefinedBinaryOperators;
8016 
8017     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8018       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8019           CandidateTypes[ArgIdx].enumeration_end()) {
8020         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8021                                          CEnd = CandidateSet.end();
8022              C != CEnd; ++C) {
8023           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8024             continue;
8025 
8026           if (C->Function->isFunctionTemplateSpecialization())
8027             continue;
8028 
8029           QualType FirstParamType =
8030             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8031           QualType SecondParamType =
8032             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8033 
8034           // Skip if either parameter isn't of enumeral type.
8035           if (!FirstParamType->isEnumeralType() ||
8036               !SecondParamType->isEnumeralType())
8037             continue;
8038 
8039           // Add this operator to the set of known user-defined operators.
8040           UserDefinedBinaryOperators.insert(
8041             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8042                            S.Context.getCanonicalType(SecondParamType)));
8043         }
8044       }
8045     }
8046 
8047     /// Set of (canonical) types that we've already handled.
8048     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8049 
8050     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8051       for (BuiltinCandidateTypeSet::iterator
8052                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8053              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8054            Ptr != PtrEnd; ++Ptr) {
8055         // Don't add the same builtin candidate twice.
8056         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8057           continue;
8058 
8059         QualType ParamTypes[2] = { *Ptr, *Ptr };
8060         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8061       }
8062       for (BuiltinCandidateTypeSet::iterator
8063                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8064              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8065            Enum != EnumEnd; ++Enum) {
8066         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8067 
8068         // Don't add the same builtin candidate twice, or if a user defined
8069         // candidate exists.
8070         if (!AddedTypes.insert(CanonType).second ||
8071             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8072                                                             CanonType)))
8073           continue;
8074         QualType ParamTypes[2] = { *Enum, *Enum };
8075         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8076       }
8077     }
8078   }
8079 
8080   // C++ [over.built]p13:
8081   //
8082   //   For every cv-qualified or cv-unqualified object type T
8083   //   there exist candidate operator functions of the form
8084   //
8085   //      T*         operator+(T*, ptrdiff_t);
8086   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8087   //      T*         operator-(T*, ptrdiff_t);
8088   //      T*         operator+(ptrdiff_t, T*);
8089   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8090   //
8091   // C++ [over.built]p14:
8092   //
8093   //   For every T, where T is a pointer to object type, there
8094   //   exist candidate operator functions of the form
8095   //
8096   //      ptrdiff_t  operator-(T, T);
8097   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8098     /// Set of (canonical) types that we've already handled.
8099     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8100 
8101     for (int Arg = 0; Arg < 2; ++Arg) {
8102       QualType AsymmetricParamTypes[2] = {
8103         S.Context.getPointerDiffType(),
8104         S.Context.getPointerDiffType(),
8105       };
8106       for (BuiltinCandidateTypeSet::iterator
8107                 Ptr = CandidateTypes[Arg].pointer_begin(),
8108              PtrEnd = CandidateTypes[Arg].pointer_end();
8109            Ptr != PtrEnd; ++Ptr) {
8110         QualType PointeeTy = (*Ptr)->getPointeeType();
8111         if (!PointeeTy->isObjectType())
8112           continue;
8113 
8114         AsymmetricParamTypes[Arg] = *Ptr;
8115         if (Arg == 0 || Op == OO_Plus) {
8116           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8117           // T* operator+(ptrdiff_t, T*);
8118           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8119         }
8120         if (Op == OO_Minus) {
8121           // ptrdiff_t operator-(T, T);
8122           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8123             continue;
8124 
8125           QualType ParamTypes[2] = { *Ptr, *Ptr };
8126           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8127         }
8128       }
8129     }
8130   }
8131 
8132   // C++ [over.built]p12:
8133   //
8134   //   For every pair of promoted arithmetic types L and R, there
8135   //   exist candidate operator functions of the form
8136   //
8137   //        LR         operator*(L, R);
8138   //        LR         operator/(L, R);
8139   //        LR         operator+(L, R);
8140   //        LR         operator-(L, R);
8141   //        bool       operator<(L, R);
8142   //        bool       operator>(L, R);
8143   //        bool       operator<=(L, R);
8144   //        bool       operator>=(L, R);
8145   //        bool       operator==(L, R);
8146   //        bool       operator!=(L, R);
8147   //
8148   //   where LR is the result of the usual arithmetic conversions
8149   //   between types L and R.
8150   //
8151   // C++ [over.built]p24:
8152   //
8153   //   For every pair of promoted arithmetic types L and R, there exist
8154   //   candidate operator functions of the form
8155   //
8156   //        LR       operator?(bool, L, R);
8157   //
8158   //   where LR is the result of the usual arithmetic conversions
8159   //   between types L and R.
8160   // Our candidates ignore the first parameter.
8161   void addGenericBinaryArithmeticOverloads() {
8162     if (!HasArithmeticOrEnumeralCandidateType)
8163       return;
8164 
8165     for (unsigned Left = FirstPromotedArithmeticType;
8166          Left < LastPromotedArithmeticType; ++Left) {
8167       for (unsigned Right = FirstPromotedArithmeticType;
8168            Right < LastPromotedArithmeticType; ++Right) {
8169         QualType LandR[2] = { ArithmeticTypes[Left],
8170                               ArithmeticTypes[Right] };
8171         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8172       }
8173     }
8174 
8175     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8176     // conditional operator for vector types.
8177     for (BuiltinCandidateTypeSet::iterator
8178               Vec1 = CandidateTypes[0].vector_begin(),
8179            Vec1End = CandidateTypes[0].vector_end();
8180          Vec1 != Vec1End; ++Vec1) {
8181       for (BuiltinCandidateTypeSet::iterator
8182                 Vec2 = CandidateTypes[1].vector_begin(),
8183              Vec2End = CandidateTypes[1].vector_end();
8184            Vec2 != Vec2End; ++Vec2) {
8185         QualType LandR[2] = { *Vec1, *Vec2 };
8186         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8187       }
8188     }
8189   }
8190 
8191   // C++2a [over.built]p14:
8192   //
8193   //   For every integral type T there exists a candidate operator function
8194   //   of the form
8195   //
8196   //        std::strong_ordering operator<=>(T, T)
8197   //
8198   // C++2a [over.built]p15:
8199   //
8200   //   For every pair of floating-point types L and R, there exists a candidate
8201   //   operator function of the form
8202   //
8203   //       std::partial_ordering operator<=>(L, R);
8204   //
8205   // FIXME: The current specification for integral types doesn't play nice with
8206   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8207   // comparisons. Under the current spec this can lead to ambiguity during
8208   // overload resolution. For example:
8209   //
8210   //   enum A : int {a};
8211   //   auto x = (a <=> (long)42);
8212   //
8213   //   error: call is ambiguous for arguments 'A' and 'long'.
8214   //   note: candidate operator<=>(int, int)
8215   //   note: candidate operator<=>(long, long)
8216   //
8217   // To avoid this error, this function deviates from the specification and adds
8218   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8219   // arithmetic types (the same as the generic relational overloads).
8220   //
8221   // For now this function acts as a placeholder.
8222   void addThreeWayArithmeticOverloads() {
8223     addGenericBinaryArithmeticOverloads();
8224   }
8225 
8226   // C++ [over.built]p17:
8227   //
8228   //   For every pair of promoted integral types L and R, there
8229   //   exist candidate operator functions of the form
8230   //
8231   //      LR         operator%(L, R);
8232   //      LR         operator&(L, R);
8233   //      LR         operator^(L, R);
8234   //      LR         operator|(L, R);
8235   //      L          operator<<(L, R);
8236   //      L          operator>>(L, R);
8237   //
8238   //   where LR is the result of the usual arithmetic conversions
8239   //   between types L and R.
8240   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8241     if (!HasArithmeticOrEnumeralCandidateType)
8242       return;
8243 
8244     for (unsigned Left = FirstPromotedIntegralType;
8245          Left < LastPromotedIntegralType; ++Left) {
8246       for (unsigned Right = FirstPromotedIntegralType;
8247            Right < LastPromotedIntegralType; ++Right) {
8248         QualType LandR[2] = { ArithmeticTypes[Left],
8249                               ArithmeticTypes[Right] };
8250         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8251       }
8252     }
8253   }
8254 
8255   // C++ [over.built]p20:
8256   //
8257   //   For every pair (T, VQ), where T is an enumeration or
8258   //   pointer to member type and VQ is either volatile or
8259   //   empty, there exist candidate operator functions of the form
8260   //
8261   //        VQ T&      operator=(VQ T&, T);
8262   void addAssignmentMemberPointerOrEnumeralOverloads() {
8263     /// Set of (canonical) types that we've already handled.
8264     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8265 
8266     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8267       for (BuiltinCandidateTypeSet::iterator
8268                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8269              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8270            Enum != EnumEnd; ++Enum) {
8271         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8272           continue;
8273 
8274         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8275       }
8276 
8277       for (BuiltinCandidateTypeSet::iterator
8278                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8279              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8280            MemPtr != MemPtrEnd; ++MemPtr) {
8281         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8282           continue;
8283 
8284         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8285       }
8286     }
8287   }
8288 
8289   // C++ [over.built]p19:
8290   //
8291   //   For every pair (T, VQ), where T is any type and VQ is either
8292   //   volatile or empty, there exist candidate operator functions
8293   //   of the form
8294   //
8295   //        T*VQ&      operator=(T*VQ&, T*);
8296   //
8297   // C++ [over.built]p21:
8298   //
8299   //   For every pair (T, VQ), where T is a cv-qualified or
8300   //   cv-unqualified object type and VQ is either volatile or
8301   //   empty, there exist candidate operator functions of the form
8302   //
8303   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8304   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8305   void addAssignmentPointerOverloads(bool isEqualOp) {
8306     /// Set of (canonical) types that we've already handled.
8307     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8308 
8309     for (BuiltinCandidateTypeSet::iterator
8310               Ptr = CandidateTypes[0].pointer_begin(),
8311            PtrEnd = CandidateTypes[0].pointer_end();
8312          Ptr != PtrEnd; ++Ptr) {
8313       // If this is operator=, keep track of the builtin candidates we added.
8314       if (isEqualOp)
8315         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8316       else if (!(*Ptr)->getPointeeType()->isObjectType())
8317         continue;
8318 
8319       // non-volatile version
8320       QualType ParamTypes[2] = {
8321         S.Context.getLValueReferenceType(*Ptr),
8322         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8323       };
8324       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8325                             /*IsAssigmentOperator=*/ isEqualOp);
8326 
8327       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8328                           VisibleTypeConversionsQuals.hasVolatile();
8329       if (NeedVolatile) {
8330         // volatile version
8331         ParamTypes[0] =
8332           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8333         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8334                               /*IsAssigmentOperator=*/isEqualOp);
8335       }
8336 
8337       if (!(*Ptr).isRestrictQualified() &&
8338           VisibleTypeConversionsQuals.hasRestrict()) {
8339         // restrict version
8340         ParamTypes[0]
8341           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8342         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8343                               /*IsAssigmentOperator=*/isEqualOp);
8344 
8345         if (NeedVolatile) {
8346           // volatile restrict version
8347           ParamTypes[0]
8348             = S.Context.getLValueReferenceType(
8349                 S.Context.getCVRQualifiedType(*Ptr,
8350                                               (Qualifiers::Volatile |
8351                                                Qualifiers::Restrict)));
8352           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8353                                 /*IsAssigmentOperator=*/isEqualOp);
8354         }
8355       }
8356     }
8357 
8358     if (isEqualOp) {
8359       for (BuiltinCandidateTypeSet::iterator
8360                 Ptr = CandidateTypes[1].pointer_begin(),
8361              PtrEnd = CandidateTypes[1].pointer_end();
8362            Ptr != PtrEnd; ++Ptr) {
8363         // Make sure we don't add the same candidate twice.
8364         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8365           continue;
8366 
8367         QualType ParamTypes[2] = {
8368           S.Context.getLValueReferenceType(*Ptr),
8369           *Ptr,
8370         };
8371 
8372         // non-volatile version
8373         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8374                               /*IsAssigmentOperator=*/true);
8375 
8376         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8377                            VisibleTypeConversionsQuals.hasVolatile();
8378         if (NeedVolatile) {
8379           // volatile version
8380           ParamTypes[0] =
8381             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8382           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8383                                 /*IsAssigmentOperator=*/true);
8384         }
8385 
8386         if (!(*Ptr).isRestrictQualified() &&
8387             VisibleTypeConversionsQuals.hasRestrict()) {
8388           // restrict version
8389           ParamTypes[0]
8390             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8391           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8392                                 /*IsAssigmentOperator=*/true);
8393 
8394           if (NeedVolatile) {
8395             // volatile restrict version
8396             ParamTypes[0]
8397               = S.Context.getLValueReferenceType(
8398                   S.Context.getCVRQualifiedType(*Ptr,
8399                                                 (Qualifiers::Volatile |
8400                                                  Qualifiers::Restrict)));
8401             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402                                   /*IsAssigmentOperator=*/true);
8403           }
8404         }
8405       }
8406     }
8407   }
8408 
8409   // C++ [over.built]p18:
8410   //
8411   //   For every triple (L, VQ, R), where L is an arithmetic type,
8412   //   VQ is either volatile or empty, and R is a promoted
8413   //   arithmetic type, there exist candidate operator functions of
8414   //   the form
8415   //
8416   //        VQ L&      operator=(VQ L&, R);
8417   //        VQ L&      operator*=(VQ L&, R);
8418   //        VQ L&      operator/=(VQ L&, R);
8419   //        VQ L&      operator+=(VQ L&, R);
8420   //        VQ L&      operator-=(VQ L&, R);
8421   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8422     if (!HasArithmeticOrEnumeralCandidateType)
8423       return;
8424 
8425     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8426       for (unsigned Right = FirstPromotedArithmeticType;
8427            Right < LastPromotedArithmeticType; ++Right) {
8428         QualType ParamTypes[2];
8429         ParamTypes[1] = ArithmeticTypes[Right];
8430 
8431         // Add this built-in operator as a candidate (VQ is empty).
8432         ParamTypes[0] =
8433           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8434         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8435                               /*IsAssigmentOperator=*/isEqualOp);
8436 
8437         // Add this built-in operator as a candidate (VQ is 'volatile').
8438         if (VisibleTypeConversionsQuals.hasVolatile()) {
8439           ParamTypes[0] =
8440             S.Context.getVolatileType(ArithmeticTypes[Left]);
8441           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8442           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8443                                 /*IsAssigmentOperator=*/isEqualOp);
8444         }
8445       }
8446     }
8447 
8448     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8449     for (BuiltinCandidateTypeSet::iterator
8450               Vec1 = CandidateTypes[0].vector_begin(),
8451            Vec1End = CandidateTypes[0].vector_end();
8452          Vec1 != Vec1End; ++Vec1) {
8453       for (BuiltinCandidateTypeSet::iterator
8454                 Vec2 = CandidateTypes[1].vector_begin(),
8455              Vec2End = CandidateTypes[1].vector_end();
8456            Vec2 != Vec2End; ++Vec2) {
8457         QualType ParamTypes[2];
8458         ParamTypes[1] = *Vec2;
8459         // Add this built-in operator as a candidate (VQ is empty).
8460         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8461         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8462                               /*IsAssigmentOperator=*/isEqualOp);
8463 
8464         // Add this built-in operator as a candidate (VQ is 'volatile').
8465         if (VisibleTypeConversionsQuals.hasVolatile()) {
8466           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8467           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8468           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8469                                 /*IsAssigmentOperator=*/isEqualOp);
8470         }
8471       }
8472     }
8473   }
8474 
8475   // C++ [over.built]p22:
8476   //
8477   //   For every triple (L, VQ, R), where L is an integral type, VQ
8478   //   is either volatile or empty, and R is a promoted integral
8479   //   type, there exist candidate operator functions of the form
8480   //
8481   //        VQ L&       operator%=(VQ L&, R);
8482   //        VQ L&       operator<<=(VQ L&, R);
8483   //        VQ L&       operator>>=(VQ L&, R);
8484   //        VQ L&       operator&=(VQ L&, R);
8485   //        VQ L&       operator^=(VQ L&, R);
8486   //        VQ L&       operator|=(VQ L&, R);
8487   void addAssignmentIntegralOverloads() {
8488     if (!HasArithmeticOrEnumeralCandidateType)
8489       return;
8490 
8491     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8492       for (unsigned Right = FirstPromotedIntegralType;
8493            Right < LastPromotedIntegralType; ++Right) {
8494         QualType ParamTypes[2];
8495         ParamTypes[1] = ArithmeticTypes[Right];
8496 
8497         // Add this built-in operator as a candidate (VQ is empty).
8498         ParamTypes[0] =
8499           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8500         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8501         if (VisibleTypeConversionsQuals.hasVolatile()) {
8502           // Add this built-in operator as a candidate (VQ is 'volatile').
8503           ParamTypes[0] = ArithmeticTypes[Left];
8504           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8505           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8506           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8507         }
8508       }
8509     }
8510   }
8511 
8512   // C++ [over.operator]p23:
8513   //
8514   //   There also exist candidate operator functions of the form
8515   //
8516   //        bool        operator!(bool);
8517   //        bool        operator&&(bool, bool);
8518   //        bool        operator||(bool, bool);
8519   void addExclaimOverload() {
8520     QualType ParamTy = S.Context.BoolTy;
8521     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8522                           /*IsAssignmentOperator=*/false,
8523                           /*NumContextualBoolArguments=*/1);
8524   }
8525   void addAmpAmpOrPipePipeOverload() {
8526     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8527     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8528                           /*IsAssignmentOperator=*/false,
8529                           /*NumContextualBoolArguments=*/2);
8530   }
8531 
8532   // C++ [over.built]p13:
8533   //
8534   //   For every cv-qualified or cv-unqualified object type T there
8535   //   exist candidate operator functions of the form
8536   //
8537   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8538   //        T&         operator[](T*, ptrdiff_t);
8539   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8540   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8541   //        T&         operator[](ptrdiff_t, T*);
8542   void addSubscriptOverloads() {
8543     for (BuiltinCandidateTypeSet::iterator
8544               Ptr = CandidateTypes[0].pointer_begin(),
8545            PtrEnd = CandidateTypes[0].pointer_end();
8546          Ptr != PtrEnd; ++Ptr) {
8547       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8548       QualType PointeeType = (*Ptr)->getPointeeType();
8549       if (!PointeeType->isObjectType())
8550         continue;
8551 
8552       // T& operator[](T*, ptrdiff_t)
8553       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8554     }
8555 
8556     for (BuiltinCandidateTypeSet::iterator
8557               Ptr = CandidateTypes[1].pointer_begin(),
8558            PtrEnd = CandidateTypes[1].pointer_end();
8559          Ptr != PtrEnd; ++Ptr) {
8560       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8561       QualType PointeeType = (*Ptr)->getPointeeType();
8562       if (!PointeeType->isObjectType())
8563         continue;
8564 
8565       // T& operator[](ptrdiff_t, T*)
8566       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8567     }
8568   }
8569 
8570   // C++ [over.built]p11:
8571   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8572   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8573   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8574   //    there exist candidate operator functions of the form
8575   //
8576   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8577   //
8578   //    where CV12 is the union of CV1 and CV2.
8579   void addArrowStarOverloads() {
8580     for (BuiltinCandidateTypeSet::iterator
8581              Ptr = CandidateTypes[0].pointer_begin(),
8582            PtrEnd = CandidateTypes[0].pointer_end();
8583          Ptr != PtrEnd; ++Ptr) {
8584       QualType C1Ty = (*Ptr);
8585       QualType C1;
8586       QualifierCollector Q1;
8587       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8588       if (!isa<RecordType>(C1))
8589         continue;
8590       // heuristic to reduce number of builtin candidates in the set.
8591       // Add volatile/restrict version only if there are conversions to a
8592       // volatile/restrict type.
8593       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8594         continue;
8595       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8596         continue;
8597       for (BuiltinCandidateTypeSet::iterator
8598                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8599              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8600            MemPtr != MemPtrEnd; ++MemPtr) {
8601         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8602         QualType C2 = QualType(mptr->getClass(), 0);
8603         C2 = C2.getUnqualifiedType();
8604         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8605           break;
8606         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8607         // build CV12 T&
8608         QualType T = mptr->getPointeeType();
8609         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8610             T.isVolatileQualified())
8611           continue;
8612         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8613             T.isRestrictQualified())
8614           continue;
8615         T = Q1.apply(S.Context, T);
8616         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8617       }
8618     }
8619   }
8620 
8621   // Note that we don't consider the first argument, since it has been
8622   // contextually converted to bool long ago. The candidates below are
8623   // therefore added as binary.
8624   //
8625   // C++ [over.built]p25:
8626   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8627   //   enumeration type, there exist candidate operator functions of the form
8628   //
8629   //        T        operator?(bool, T, T);
8630   //
8631   void addConditionalOperatorOverloads() {
8632     /// Set of (canonical) types that we've already handled.
8633     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8634 
8635     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8636       for (BuiltinCandidateTypeSet::iterator
8637                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8638              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8639            Ptr != PtrEnd; ++Ptr) {
8640         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8641           continue;
8642 
8643         QualType ParamTypes[2] = { *Ptr, *Ptr };
8644         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8645       }
8646 
8647       for (BuiltinCandidateTypeSet::iterator
8648                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8649              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8650            MemPtr != MemPtrEnd; ++MemPtr) {
8651         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8652           continue;
8653 
8654         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8655         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8656       }
8657 
8658       if (S.getLangOpts().CPlusPlus11) {
8659         for (BuiltinCandidateTypeSet::iterator
8660                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8661                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8662              Enum != EnumEnd; ++Enum) {
8663           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8664             continue;
8665 
8666           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8667             continue;
8668 
8669           QualType ParamTypes[2] = { *Enum, *Enum };
8670           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8671         }
8672       }
8673     }
8674   }
8675 };
8676 
8677 } // end anonymous namespace
8678 
8679 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8680 /// operator overloads to the candidate set (C++ [over.built]), based
8681 /// on the operator @p Op and the arguments given. For example, if the
8682 /// operator is a binary '+', this routine might add "int
8683 /// operator+(int, int)" to cover integer addition.
8684 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8685                                         SourceLocation OpLoc,
8686                                         ArrayRef<Expr *> Args,
8687                                         OverloadCandidateSet &CandidateSet) {
8688   // Find all of the types that the arguments can convert to, but only
8689   // if the operator we're looking at has built-in operator candidates
8690   // that make use of these types. Also record whether we encounter non-record
8691   // candidate types or either arithmetic or enumeral candidate types.
8692   Qualifiers VisibleTypeConversionsQuals;
8693   VisibleTypeConversionsQuals.addConst();
8694   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8695     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8696 
8697   bool HasNonRecordCandidateType = false;
8698   bool HasArithmeticOrEnumeralCandidateType = false;
8699   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8700   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8701     CandidateTypes.emplace_back(*this);
8702     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8703                                                  OpLoc,
8704                                                  true,
8705                                                  (Op == OO_Exclaim ||
8706                                                   Op == OO_AmpAmp ||
8707                                                   Op == OO_PipePipe),
8708                                                  VisibleTypeConversionsQuals);
8709     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8710         CandidateTypes[ArgIdx].hasNonRecordTypes();
8711     HasArithmeticOrEnumeralCandidateType =
8712         HasArithmeticOrEnumeralCandidateType ||
8713         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8714   }
8715 
8716   // Exit early when no non-record types have been added to the candidate set
8717   // for any of the arguments to the operator.
8718   //
8719   // We can't exit early for !, ||, or &&, since there we have always have
8720   // 'bool' overloads.
8721   if (!HasNonRecordCandidateType &&
8722       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8723     return;
8724 
8725   // Setup an object to manage the common state for building overloads.
8726   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8727                                            VisibleTypeConversionsQuals,
8728                                            HasArithmeticOrEnumeralCandidateType,
8729                                            CandidateTypes, CandidateSet);
8730 
8731   // Dispatch over the operation to add in only those overloads which apply.
8732   switch (Op) {
8733   case OO_None:
8734   case NUM_OVERLOADED_OPERATORS:
8735     llvm_unreachable("Expected an overloaded operator");
8736 
8737   case OO_New:
8738   case OO_Delete:
8739   case OO_Array_New:
8740   case OO_Array_Delete:
8741   case OO_Call:
8742     llvm_unreachable(
8743                     "Special operators don't use AddBuiltinOperatorCandidates");
8744 
8745   case OO_Comma:
8746   case OO_Arrow:
8747   case OO_Coawait:
8748     // C++ [over.match.oper]p3:
8749     //   -- For the operator ',', the unary operator '&', the
8750     //      operator '->', or the operator 'co_await', the
8751     //      built-in candidates set is empty.
8752     break;
8753 
8754   case OO_Plus: // '+' is either unary or binary
8755     if (Args.size() == 1)
8756       OpBuilder.addUnaryPlusPointerOverloads();
8757     LLVM_FALLTHROUGH;
8758 
8759   case OO_Minus: // '-' is either unary or binary
8760     if (Args.size() == 1) {
8761       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8762     } else {
8763       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8764       OpBuilder.addGenericBinaryArithmeticOverloads();
8765     }
8766     break;
8767 
8768   case OO_Star: // '*' is either unary or binary
8769     if (Args.size() == 1)
8770       OpBuilder.addUnaryStarPointerOverloads();
8771     else
8772       OpBuilder.addGenericBinaryArithmeticOverloads();
8773     break;
8774 
8775   case OO_Slash:
8776     OpBuilder.addGenericBinaryArithmeticOverloads();
8777     break;
8778 
8779   case OO_PlusPlus:
8780   case OO_MinusMinus:
8781     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8782     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8783     break;
8784 
8785   case OO_EqualEqual:
8786   case OO_ExclaimEqual:
8787     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8788     LLVM_FALLTHROUGH;
8789 
8790   case OO_Less:
8791   case OO_Greater:
8792   case OO_LessEqual:
8793   case OO_GreaterEqual:
8794     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8795     OpBuilder.addGenericBinaryArithmeticOverloads();
8796     break;
8797 
8798   case OO_Spaceship:
8799     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8800     OpBuilder.addThreeWayArithmeticOverloads();
8801     break;
8802 
8803   case OO_Percent:
8804   case OO_Caret:
8805   case OO_Pipe:
8806   case OO_LessLess:
8807   case OO_GreaterGreater:
8808     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8809     break;
8810 
8811   case OO_Amp: // '&' is either unary or binary
8812     if (Args.size() == 1)
8813       // C++ [over.match.oper]p3:
8814       //   -- For the operator ',', the unary operator '&', or the
8815       //      operator '->', the built-in candidates set is empty.
8816       break;
8817 
8818     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8819     break;
8820 
8821   case OO_Tilde:
8822     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8823     break;
8824 
8825   case OO_Equal:
8826     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8827     LLVM_FALLTHROUGH;
8828 
8829   case OO_PlusEqual:
8830   case OO_MinusEqual:
8831     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8832     LLVM_FALLTHROUGH;
8833 
8834   case OO_StarEqual:
8835   case OO_SlashEqual:
8836     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8837     break;
8838 
8839   case OO_PercentEqual:
8840   case OO_LessLessEqual:
8841   case OO_GreaterGreaterEqual:
8842   case OO_AmpEqual:
8843   case OO_CaretEqual:
8844   case OO_PipeEqual:
8845     OpBuilder.addAssignmentIntegralOverloads();
8846     break;
8847 
8848   case OO_Exclaim:
8849     OpBuilder.addExclaimOverload();
8850     break;
8851 
8852   case OO_AmpAmp:
8853   case OO_PipePipe:
8854     OpBuilder.addAmpAmpOrPipePipeOverload();
8855     break;
8856 
8857   case OO_Subscript:
8858     OpBuilder.addSubscriptOverloads();
8859     break;
8860 
8861   case OO_ArrowStar:
8862     OpBuilder.addArrowStarOverloads();
8863     break;
8864 
8865   case OO_Conditional:
8866     OpBuilder.addConditionalOperatorOverloads();
8867     OpBuilder.addGenericBinaryArithmeticOverloads();
8868     break;
8869   }
8870 }
8871 
8872 /// Add function candidates found via argument-dependent lookup
8873 /// to the set of overloading candidates.
8874 ///
8875 /// This routine performs argument-dependent name lookup based on the
8876 /// given function name (which may also be an operator name) and adds
8877 /// all of the overload candidates found by ADL to the overload
8878 /// candidate set (C++ [basic.lookup.argdep]).
8879 void
8880 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8881                                            SourceLocation Loc,
8882                                            ArrayRef<Expr *> Args,
8883                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8884                                            OverloadCandidateSet& CandidateSet,
8885                                            bool PartialOverloading) {
8886   ADLResult Fns;
8887 
8888   // FIXME: This approach for uniquing ADL results (and removing
8889   // redundant candidates from the set) relies on pointer-equality,
8890   // which means we need to key off the canonical decl.  However,
8891   // always going back to the canonical decl might not get us the
8892   // right set of default arguments.  What default arguments are
8893   // we supposed to consider on ADL candidates, anyway?
8894 
8895   // FIXME: Pass in the explicit template arguments?
8896   ArgumentDependentLookup(Name, Loc, Args, Fns);
8897 
8898   // Erase all of the candidates we already knew about.
8899   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8900                                    CandEnd = CandidateSet.end();
8901        Cand != CandEnd; ++Cand)
8902     if (Cand->Function) {
8903       Fns.erase(Cand->Function);
8904       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8905         Fns.erase(FunTmpl);
8906     }
8907 
8908   // For each of the ADL candidates we found, add it to the overload
8909   // set.
8910   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8911     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8912     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8913       if (ExplicitTemplateArgs)
8914         continue;
8915 
8916       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8917                            PartialOverloading);
8918     } else
8919       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8920                                    FoundDecl, ExplicitTemplateArgs,
8921                                    Args, CandidateSet, PartialOverloading);
8922   }
8923 }
8924 
8925 namespace {
8926 enum class Comparison { Equal, Better, Worse };
8927 }
8928 
8929 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8930 /// overload resolution.
8931 ///
8932 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8933 /// Cand1's first N enable_if attributes have precisely the same conditions as
8934 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8935 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8936 ///
8937 /// Note that you can have a pair of candidates such that Cand1's enable_if
8938 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8939 /// worse than Cand1's.
8940 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8941                                        const FunctionDecl *Cand2) {
8942   // Common case: One (or both) decls don't have enable_if attrs.
8943   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8944   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8945   if (!Cand1Attr || !Cand2Attr) {
8946     if (Cand1Attr == Cand2Attr)
8947       return Comparison::Equal;
8948     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8949   }
8950 
8951   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8952   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
8953 
8954   auto Cand1I = Cand1Attrs.begin();
8955   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8956   for (EnableIfAttr *Cand2A : Cand2Attrs) {
8957     Cand1ID.clear();
8958     Cand2ID.clear();
8959 
8960     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8961     // has fewer enable_if attributes than Cand2.
8962     auto Cand1A = Cand1I++;
8963     if (Cand1A == Cand1Attrs.end())
8964       return Comparison::Worse;
8965 
8966     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8967     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8968     if (Cand1ID != Cand2ID)
8969       return Comparison::Worse;
8970   }
8971 
8972   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8973 }
8974 
8975 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8976                                           const OverloadCandidate &Cand2) {
8977   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
8978       !Cand2.Function->isMultiVersion())
8979     return false;
8980 
8981   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
8982   // cpu_dispatch, else arbitrarily based on the identifiers.
8983   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
8984   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
8985   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
8986   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
8987 
8988   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
8989     return false;
8990 
8991   if (Cand1CPUDisp && !Cand2CPUDisp)
8992     return true;
8993   if (Cand2CPUDisp && !Cand1CPUDisp)
8994     return false;
8995 
8996   if (Cand1CPUSpec && Cand2CPUSpec) {
8997     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
8998       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
8999 
9000     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9001         FirstDiff = std::mismatch(
9002             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9003             Cand2CPUSpec->cpus_begin(),
9004             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9005               return LHS->getName() == RHS->getName();
9006             });
9007 
9008     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9009            "Two different cpu-specific versions should not have the same "
9010            "identifier list, otherwise they'd be the same decl!");
9011     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9012   }
9013   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9014 }
9015 
9016 /// isBetterOverloadCandidate - Determines whether the first overload
9017 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9018 bool clang::isBetterOverloadCandidate(
9019     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9020     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9021   // Define viable functions to be better candidates than non-viable
9022   // functions.
9023   if (!Cand2.Viable)
9024     return Cand1.Viable;
9025   else if (!Cand1.Viable)
9026     return false;
9027 
9028   // C++ [over.match.best]p1:
9029   //
9030   //   -- if F is a static member function, ICS1(F) is defined such
9031   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9032   //      any function G, and, symmetrically, ICS1(G) is neither
9033   //      better nor worse than ICS1(F).
9034   unsigned StartArg = 0;
9035   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9036     StartArg = 1;
9037 
9038   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9039     // We don't allow incompatible pointer conversions in C++.
9040     if (!S.getLangOpts().CPlusPlus)
9041       return ICS.isStandard() &&
9042              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9043 
9044     // The only ill-formed conversion we allow in C++ is the string literal to
9045     // char* conversion, which is only considered ill-formed after C++11.
9046     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9047            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9048   };
9049 
9050   // Define functions that don't require ill-formed conversions for a given
9051   // argument to be better candidates than functions that do.
9052   unsigned NumArgs = Cand1.Conversions.size();
9053   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9054   bool HasBetterConversion = false;
9055   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9056     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9057     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9058     if (Cand1Bad != Cand2Bad) {
9059       if (Cand1Bad)
9060         return false;
9061       HasBetterConversion = true;
9062     }
9063   }
9064 
9065   if (HasBetterConversion)
9066     return true;
9067 
9068   // C++ [over.match.best]p1:
9069   //   A viable function F1 is defined to be a better function than another
9070   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9071   //   conversion sequence than ICSi(F2), and then...
9072   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9073     switch (CompareImplicitConversionSequences(S, Loc,
9074                                                Cand1.Conversions[ArgIdx],
9075                                                Cand2.Conversions[ArgIdx])) {
9076     case ImplicitConversionSequence::Better:
9077       // Cand1 has a better conversion sequence.
9078       HasBetterConversion = true;
9079       break;
9080 
9081     case ImplicitConversionSequence::Worse:
9082       // Cand1 can't be better than Cand2.
9083       return false;
9084 
9085     case ImplicitConversionSequence::Indistinguishable:
9086       // Do nothing.
9087       break;
9088     }
9089   }
9090 
9091   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9092   //       ICSj(F2), or, if not that,
9093   if (HasBetterConversion)
9094     return true;
9095 
9096   //   -- the context is an initialization by user-defined conversion
9097   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9098   //      from the return type of F1 to the destination type (i.e.,
9099   //      the type of the entity being initialized) is a better
9100   //      conversion sequence than the standard conversion sequence
9101   //      from the return type of F2 to the destination type.
9102   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9103       Cand1.Function && Cand2.Function &&
9104       isa<CXXConversionDecl>(Cand1.Function) &&
9105       isa<CXXConversionDecl>(Cand2.Function)) {
9106     // First check whether we prefer one of the conversion functions over the
9107     // other. This only distinguishes the results in non-standard, extension
9108     // cases such as the conversion from a lambda closure type to a function
9109     // pointer or block.
9110     ImplicitConversionSequence::CompareKind Result =
9111         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9112     if (Result == ImplicitConversionSequence::Indistinguishable)
9113       Result = CompareStandardConversionSequences(S, Loc,
9114                                                   Cand1.FinalConversion,
9115                                                   Cand2.FinalConversion);
9116 
9117     if (Result != ImplicitConversionSequence::Indistinguishable)
9118       return Result == ImplicitConversionSequence::Better;
9119 
9120     // FIXME: Compare kind of reference binding if conversion functions
9121     // convert to a reference type used in direct reference binding, per
9122     // C++14 [over.match.best]p1 section 2 bullet 3.
9123   }
9124 
9125   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9126   // as combined with the resolution to CWG issue 243.
9127   //
9128   // When the context is initialization by constructor ([over.match.ctor] or
9129   // either phase of [over.match.list]), a constructor is preferred over
9130   // a conversion function.
9131   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9132       Cand1.Function && Cand2.Function &&
9133       isa<CXXConstructorDecl>(Cand1.Function) !=
9134           isa<CXXConstructorDecl>(Cand2.Function))
9135     return isa<CXXConstructorDecl>(Cand1.Function);
9136 
9137   //    -- F1 is a non-template function and F2 is a function template
9138   //       specialization, or, if not that,
9139   bool Cand1IsSpecialization = Cand1.Function &&
9140                                Cand1.Function->getPrimaryTemplate();
9141   bool Cand2IsSpecialization = Cand2.Function &&
9142                                Cand2.Function->getPrimaryTemplate();
9143   if (Cand1IsSpecialization != Cand2IsSpecialization)
9144     return Cand2IsSpecialization;
9145 
9146   //   -- F1 and F2 are function template specializations, and the function
9147   //      template for F1 is more specialized than the template for F2
9148   //      according to the partial ordering rules described in 14.5.5.2, or,
9149   //      if not that,
9150   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9151     if (FunctionTemplateDecl *BetterTemplate
9152           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9153                                          Cand2.Function->getPrimaryTemplate(),
9154                                          Loc,
9155                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9156                                                              : TPOC_Call,
9157                                          Cand1.ExplicitCallArguments,
9158                                          Cand2.ExplicitCallArguments))
9159       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9160   }
9161 
9162   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9163   // A derived-class constructor beats an (inherited) base class constructor.
9164   bool Cand1IsInherited =
9165       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9166   bool Cand2IsInherited =
9167       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9168   if (Cand1IsInherited != Cand2IsInherited)
9169     return Cand2IsInherited;
9170   else if (Cand1IsInherited) {
9171     assert(Cand2IsInherited);
9172     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9173     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9174     if (Cand1Class->isDerivedFrom(Cand2Class))
9175       return true;
9176     if (Cand2Class->isDerivedFrom(Cand1Class))
9177       return false;
9178     // Inherited from sibling base classes: still ambiguous.
9179   }
9180 
9181   // Check C++17 tie-breakers for deduction guides.
9182   {
9183     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9184     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9185     if (Guide1 && Guide2) {
9186       //  -- F1 is generated from a deduction-guide and F2 is not
9187       if (Guide1->isImplicit() != Guide2->isImplicit())
9188         return Guide2->isImplicit();
9189 
9190       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9191       if (Guide1->isCopyDeductionCandidate())
9192         return true;
9193     }
9194   }
9195 
9196   // Check for enable_if value-based overload resolution.
9197   if (Cand1.Function && Cand2.Function) {
9198     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9199     if (Cmp != Comparison::Equal)
9200       return Cmp == Comparison::Better;
9201   }
9202 
9203   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9204     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9205     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9206            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9207   }
9208 
9209   bool HasPS1 = Cand1.Function != nullptr &&
9210                 functionHasPassObjectSizeParams(Cand1.Function);
9211   bool HasPS2 = Cand2.Function != nullptr &&
9212                 functionHasPassObjectSizeParams(Cand2.Function);
9213   if (HasPS1 != HasPS2 && HasPS1)
9214     return true;
9215 
9216   return isBetterMultiversionCandidate(Cand1, Cand2);
9217 }
9218 
9219 /// Determine whether two declarations are "equivalent" for the purposes of
9220 /// name lookup and overload resolution. This applies when the same internal/no
9221 /// linkage entity is defined by two modules (probably by textually including
9222 /// the same header). In such a case, we don't consider the declarations to
9223 /// declare the same entity, but we also don't want lookups with both
9224 /// declarations visible to be ambiguous in some cases (this happens when using
9225 /// a modularized libstdc++).
9226 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9227                                                   const NamedDecl *B) {
9228   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9229   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9230   if (!VA || !VB)
9231     return false;
9232 
9233   // The declarations must be declaring the same name as an internal linkage
9234   // entity in different modules.
9235   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9236           VB->getDeclContext()->getRedeclContext()) ||
9237       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9238           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9239       VA->isExternallyVisible() || VB->isExternallyVisible())
9240     return false;
9241 
9242   // Check that the declarations appear to be equivalent.
9243   //
9244   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9245   // For constants and functions, we should check the initializer or body is
9246   // the same. For non-constant variables, we shouldn't allow it at all.
9247   if (Context.hasSameType(VA->getType(), VB->getType()))
9248     return true;
9249 
9250   // Enum constants within unnamed enumerations will have different types, but
9251   // may still be similar enough to be interchangeable for our purposes.
9252   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9253     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9254       // Only handle anonymous enums. If the enumerations were named and
9255       // equivalent, they would have been merged to the same type.
9256       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9257       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9258       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9259           !Context.hasSameType(EnumA->getIntegerType(),
9260                                EnumB->getIntegerType()))
9261         return false;
9262       // Allow this only if the value is the same for both enumerators.
9263       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9264     }
9265   }
9266 
9267   // Nothing else is sufficiently similar.
9268   return false;
9269 }
9270 
9271 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9272     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9273   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9274 
9275   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9276   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9277       << !M << (M ? M->getFullModuleName() : "");
9278 
9279   for (auto *E : Equiv) {
9280     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9281     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9282         << !M << (M ? M->getFullModuleName() : "");
9283   }
9284 }
9285 
9286 /// Computes the best viable function (C++ 13.3.3)
9287 /// within an overload candidate set.
9288 ///
9289 /// \param Loc The location of the function name (or operator symbol) for
9290 /// which overload resolution occurs.
9291 ///
9292 /// \param Best If overload resolution was successful or found a deleted
9293 /// function, \p Best points to the candidate function found.
9294 ///
9295 /// \returns The result of overload resolution.
9296 OverloadingResult
9297 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9298                                          iterator &Best) {
9299   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9300   std::transform(begin(), end(), std::back_inserter(Candidates),
9301                  [](OverloadCandidate &Cand) { return &Cand; });
9302 
9303   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9304   // are accepted by both clang and NVCC. However, during a particular
9305   // compilation mode only one call variant is viable. We need to
9306   // exclude non-viable overload candidates from consideration based
9307   // only on their host/device attributes. Specifically, if one
9308   // candidate call is WrongSide and the other is SameSide, we ignore
9309   // the WrongSide candidate.
9310   if (S.getLangOpts().CUDA) {
9311     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9312     bool ContainsSameSideCandidate =
9313         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9314           return Cand->Function &&
9315                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9316                      Sema::CFP_SameSide;
9317         });
9318     if (ContainsSameSideCandidate) {
9319       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9320         return Cand->Function &&
9321                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9322                    Sema::CFP_WrongSide;
9323       };
9324       llvm::erase_if(Candidates, IsWrongSideCandidate);
9325     }
9326   }
9327 
9328   // Find the best viable function.
9329   Best = end();
9330   for (auto *Cand : Candidates)
9331     if (Cand->Viable)
9332       if (Best == end() ||
9333           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9334         Best = Cand;
9335 
9336   // If we didn't find any viable functions, abort.
9337   if (Best == end())
9338     return OR_No_Viable_Function;
9339 
9340   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9341 
9342   // Make sure that this function is better than every other viable
9343   // function. If not, we have an ambiguity.
9344   for (auto *Cand : Candidates) {
9345     if (Cand->Viable && Cand != Best &&
9346         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9347       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9348                                                    Cand->Function)) {
9349         EquivalentCands.push_back(Cand->Function);
9350         continue;
9351       }
9352 
9353       Best = end();
9354       return OR_Ambiguous;
9355     }
9356   }
9357 
9358   // Best is the best viable function.
9359   if (Best->Function &&
9360       (Best->Function->isDeleted() ||
9361        S.isFunctionConsideredUnavailable(Best->Function)))
9362     return OR_Deleted;
9363 
9364   if (!EquivalentCands.empty())
9365     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9366                                                     EquivalentCands);
9367 
9368   return OR_Success;
9369 }
9370 
9371 namespace {
9372 
9373 enum OverloadCandidateKind {
9374   oc_function,
9375   oc_method,
9376   oc_constructor,
9377   oc_implicit_default_constructor,
9378   oc_implicit_copy_constructor,
9379   oc_implicit_move_constructor,
9380   oc_implicit_copy_assignment,
9381   oc_implicit_move_assignment,
9382   oc_inherited_constructor
9383 };
9384 
9385 enum OverloadCandidateSelect {
9386   ocs_non_template,
9387   ocs_template,
9388   ocs_described_template,
9389 };
9390 
9391 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9392 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9393                           std::string &Description) {
9394 
9395   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9396   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9397     isTemplate = true;
9398     Description = S.getTemplateArgumentBindingsText(
9399         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9400   }
9401 
9402   OverloadCandidateSelect Select = [&]() {
9403     if (!Description.empty())
9404       return ocs_described_template;
9405     return isTemplate ? ocs_template : ocs_non_template;
9406   }();
9407 
9408   OverloadCandidateKind Kind = [&]() {
9409     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9410       if (!Ctor->isImplicit()) {
9411         if (isa<ConstructorUsingShadowDecl>(Found))
9412           return oc_inherited_constructor;
9413         else
9414           return oc_constructor;
9415       }
9416 
9417       if (Ctor->isDefaultConstructor())
9418         return oc_implicit_default_constructor;
9419 
9420       if (Ctor->isMoveConstructor())
9421         return oc_implicit_move_constructor;
9422 
9423       assert(Ctor->isCopyConstructor() &&
9424              "unexpected sort of implicit constructor");
9425       return oc_implicit_copy_constructor;
9426     }
9427 
9428     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9429       // This actually gets spelled 'candidate function' for now, but
9430       // it doesn't hurt to split it out.
9431       if (!Meth->isImplicit())
9432         return oc_method;
9433 
9434       if (Meth->isMoveAssignmentOperator())
9435         return oc_implicit_move_assignment;
9436 
9437       if (Meth->isCopyAssignmentOperator())
9438         return oc_implicit_copy_assignment;
9439 
9440       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9441       return oc_method;
9442     }
9443 
9444     return oc_function;
9445   }();
9446 
9447   return std::make_pair(Kind, Select);
9448 }
9449 
9450 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9451   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9452   // set.
9453   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9454     S.Diag(FoundDecl->getLocation(),
9455            diag::note_ovl_candidate_inherited_constructor)
9456       << Shadow->getNominatedBaseClass();
9457 }
9458 
9459 } // end anonymous namespace
9460 
9461 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9462                                     const FunctionDecl *FD) {
9463   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9464     bool AlwaysTrue;
9465     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9466       return false;
9467     if (!AlwaysTrue)
9468       return false;
9469   }
9470   return true;
9471 }
9472 
9473 /// Returns true if we can take the address of the function.
9474 ///
9475 /// \param Complain - If true, we'll emit a diagnostic
9476 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9477 ///   we in overload resolution?
9478 /// \param Loc - The location of the statement we're complaining about. Ignored
9479 ///   if we're not complaining, or if we're in overload resolution.
9480 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9481                                               bool Complain,
9482                                               bool InOverloadResolution,
9483                                               SourceLocation Loc) {
9484   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9485     if (Complain) {
9486       if (InOverloadResolution)
9487         S.Diag(FD->getLocStart(),
9488                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9489       else
9490         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9491     }
9492     return false;
9493   }
9494 
9495   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9496     return P->hasAttr<PassObjectSizeAttr>();
9497   });
9498   if (I == FD->param_end())
9499     return true;
9500 
9501   if (Complain) {
9502     // Add one to ParamNo because it's user-facing
9503     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9504     if (InOverloadResolution)
9505       S.Diag(FD->getLocation(),
9506              diag::note_ovl_candidate_has_pass_object_size_params)
9507           << ParamNo;
9508     else
9509       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9510           << FD << ParamNo;
9511   }
9512   return false;
9513 }
9514 
9515 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9516                                                const FunctionDecl *FD) {
9517   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9518                                            /*InOverloadResolution=*/true,
9519                                            /*Loc=*/SourceLocation());
9520 }
9521 
9522 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9523                                              bool Complain,
9524                                              SourceLocation Loc) {
9525   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9526                                              /*InOverloadResolution=*/false,
9527                                              Loc);
9528 }
9529 
9530 // Notes the location of an overload candidate.
9531 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9532                                  QualType DestType, bool TakingAddress) {
9533   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9534     return;
9535   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9536       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9537     return;
9538 
9539   std::string FnDesc;
9540   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9541       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9542   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9543                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9544                          << Fn << FnDesc;
9545 
9546   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9547   Diag(Fn->getLocation(), PD);
9548   MaybeEmitInheritedConstructorNote(*this, Found);
9549 }
9550 
9551 // Notes the location of all overload candidates designated through
9552 // OverloadedExpr
9553 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9554                                      bool TakingAddress) {
9555   assert(OverloadedExpr->getType() == Context.OverloadTy);
9556 
9557   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9558   OverloadExpr *OvlExpr = Ovl.Expression;
9559 
9560   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9561                             IEnd = OvlExpr->decls_end();
9562        I != IEnd; ++I) {
9563     if (FunctionTemplateDecl *FunTmpl =
9564                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9565       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9566                             TakingAddress);
9567     } else if (FunctionDecl *Fun
9568                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9569       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9570     }
9571   }
9572 }
9573 
9574 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9575 /// "lead" diagnostic; it will be given two arguments, the source and
9576 /// target types of the conversion.
9577 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9578                                  Sema &S,
9579                                  SourceLocation CaretLoc,
9580                                  const PartialDiagnostic &PDiag) const {
9581   S.Diag(CaretLoc, PDiag)
9582     << Ambiguous.getFromType() << Ambiguous.getToType();
9583   // FIXME: The note limiting machinery is borrowed from
9584   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9585   // refactoring here.
9586   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9587   unsigned CandsShown = 0;
9588   AmbiguousConversionSequence::const_iterator I, E;
9589   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9590     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9591       break;
9592     ++CandsShown;
9593     S.NoteOverloadCandidate(I->first, I->second);
9594   }
9595   if (I != E)
9596     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9597 }
9598 
9599 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9600                                   unsigned I, bool TakingCandidateAddress) {
9601   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9602   assert(Conv.isBad());
9603   assert(Cand->Function && "for now, candidate must be a function");
9604   FunctionDecl *Fn = Cand->Function;
9605 
9606   // There's a conversion slot for the object argument if this is a
9607   // non-constructor method.  Note that 'I' corresponds the
9608   // conversion-slot index.
9609   bool isObjectArgument = false;
9610   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9611     if (I == 0)
9612       isObjectArgument = true;
9613     else
9614       I--;
9615   }
9616 
9617   std::string FnDesc;
9618   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9619       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9620 
9621   Expr *FromExpr = Conv.Bad.FromExpr;
9622   QualType FromTy = Conv.Bad.getFromType();
9623   QualType ToTy = Conv.Bad.getToType();
9624 
9625   if (FromTy == S.Context.OverloadTy) {
9626     assert(FromExpr && "overload set argument came from implicit argument?");
9627     Expr *E = FromExpr->IgnoreParens();
9628     if (isa<UnaryOperator>(E))
9629       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9630     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9631 
9632     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9633         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9634         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9635         << Name << I + 1;
9636     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9637     return;
9638   }
9639 
9640   // Do some hand-waving analysis to see if the non-viability is due
9641   // to a qualifier mismatch.
9642   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9643   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9644   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9645     CToTy = RT->getPointeeType();
9646   else {
9647     // TODO: detect and diagnose the full richness of const mismatches.
9648     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9649       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9650         CFromTy = FromPT->getPointeeType();
9651         CToTy = ToPT->getPointeeType();
9652       }
9653   }
9654 
9655   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9656       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9657     Qualifiers FromQs = CFromTy.getQualifiers();
9658     Qualifiers ToQs = CToTy.getQualifiers();
9659 
9660     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9661       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9662           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9663           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9664           << ToTy << (unsigned)isObjectArgument << I + 1;
9665       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9666       return;
9667     }
9668 
9669     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9670       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9671           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9672           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9673           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9674           << (unsigned)isObjectArgument << I + 1;
9675       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9676       return;
9677     }
9678 
9679     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9680       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9681           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9682           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9683           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9684           << (unsigned)isObjectArgument << I + 1;
9685       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9686       return;
9687     }
9688 
9689     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9690       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9691           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9692           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9693           << FromQs.hasUnaligned() << I + 1;
9694       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9695       return;
9696     }
9697 
9698     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9699     assert(CVR && "unexpected qualifiers mismatch");
9700 
9701     if (isObjectArgument) {
9702       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9703           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9704           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9705           << (CVR - 1);
9706     } else {
9707       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9708           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9709           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9710           << (CVR - 1) << I + 1;
9711     }
9712     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9713     return;
9714   }
9715 
9716   // Special diagnostic for failure to convert an initializer list, since
9717   // telling the user that it has type void is not useful.
9718   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9719     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9720         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9721         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9722         << ToTy << (unsigned)isObjectArgument << I + 1;
9723     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9724     return;
9725   }
9726 
9727   // Diagnose references or pointers to incomplete types differently,
9728   // since it's far from impossible that the incompleteness triggered
9729   // the failure.
9730   QualType TempFromTy = FromTy.getNonReferenceType();
9731   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9732     TempFromTy = PTy->getPointeeType();
9733   if (TempFromTy->isIncompleteType()) {
9734     // Emit the generic diagnostic and, optionally, add the hints to it.
9735     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9736         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9737         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9738         << ToTy << (unsigned)isObjectArgument << I + 1
9739         << (unsigned)(Cand->Fix.Kind);
9740 
9741     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9742     return;
9743   }
9744 
9745   // Diagnose base -> derived pointer conversions.
9746   unsigned BaseToDerivedConversion = 0;
9747   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9748     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9749       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9750                                                FromPtrTy->getPointeeType()) &&
9751           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9752           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9753           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9754                           FromPtrTy->getPointeeType()))
9755         BaseToDerivedConversion = 1;
9756     }
9757   } else if (const ObjCObjectPointerType *FromPtrTy
9758                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9759     if (const ObjCObjectPointerType *ToPtrTy
9760                                         = ToTy->getAs<ObjCObjectPointerType>())
9761       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9762         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9763           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9764                                                 FromPtrTy->getPointeeType()) &&
9765               FromIface->isSuperClassOf(ToIface))
9766             BaseToDerivedConversion = 2;
9767   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9768     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9769         !FromTy->isIncompleteType() &&
9770         !ToRefTy->getPointeeType()->isIncompleteType() &&
9771         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9772       BaseToDerivedConversion = 3;
9773     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9774                ToTy.getNonReferenceType().getCanonicalType() ==
9775                FromTy.getNonReferenceType().getCanonicalType()) {
9776       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9777           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9778           << (unsigned)isObjectArgument << I + 1
9779           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9780       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9781       return;
9782     }
9783   }
9784 
9785   if (BaseToDerivedConversion) {
9786     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9787         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9788         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9789         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9790     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9791     return;
9792   }
9793 
9794   if (isa<ObjCObjectPointerType>(CFromTy) &&
9795       isa<PointerType>(CToTy)) {
9796       Qualifiers FromQs = CFromTy.getQualifiers();
9797       Qualifiers ToQs = CToTy.getQualifiers();
9798       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9799         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9800             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9801             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9802             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9803         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9804         return;
9805       }
9806   }
9807 
9808   if (TakingCandidateAddress &&
9809       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9810     return;
9811 
9812   // Emit the generic diagnostic and, optionally, add the hints to it.
9813   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9814   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9815         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9816         << ToTy << (unsigned)isObjectArgument << I + 1
9817         << (unsigned)(Cand->Fix.Kind);
9818 
9819   // If we can fix the conversion, suggest the FixIts.
9820   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9821        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9822     FDiag << *HI;
9823   S.Diag(Fn->getLocation(), FDiag);
9824 
9825   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9826 }
9827 
9828 /// Additional arity mismatch diagnosis specific to a function overload
9829 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9830 /// over a candidate in any candidate set.
9831 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9832                                unsigned NumArgs) {
9833   FunctionDecl *Fn = Cand->Function;
9834   unsigned MinParams = Fn->getMinRequiredArguments();
9835 
9836   // With invalid overloaded operators, it's possible that we think we
9837   // have an arity mismatch when in fact it looks like we have the
9838   // right number of arguments, because only overloaded operators have
9839   // the weird behavior of overloading member and non-member functions.
9840   // Just don't report anything.
9841   if (Fn->isInvalidDecl() &&
9842       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9843     return true;
9844 
9845   if (NumArgs < MinParams) {
9846     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9847            (Cand->FailureKind == ovl_fail_bad_deduction &&
9848             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9849   } else {
9850     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9851            (Cand->FailureKind == ovl_fail_bad_deduction &&
9852             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9853   }
9854 
9855   return false;
9856 }
9857 
9858 /// General arity mismatch diagnosis over a candidate in a candidate set.
9859 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9860                                   unsigned NumFormalArgs) {
9861   assert(isa<FunctionDecl>(D) &&
9862       "The templated declaration should at least be a function"
9863       " when diagnosing bad template argument deduction due to too many"
9864       " or too few arguments");
9865 
9866   FunctionDecl *Fn = cast<FunctionDecl>(D);
9867 
9868   // TODO: treat calls to a missing default constructor as a special case
9869   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9870   unsigned MinParams = Fn->getMinRequiredArguments();
9871 
9872   // at least / at most / exactly
9873   unsigned mode, modeCount;
9874   if (NumFormalArgs < MinParams) {
9875     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9876         FnTy->isTemplateVariadic())
9877       mode = 0; // "at least"
9878     else
9879       mode = 2; // "exactly"
9880     modeCount = MinParams;
9881   } else {
9882     if (MinParams != FnTy->getNumParams())
9883       mode = 1; // "at most"
9884     else
9885       mode = 2; // "exactly"
9886     modeCount = FnTy->getNumParams();
9887   }
9888 
9889   std::string Description;
9890   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9891       ClassifyOverloadCandidate(S, Found, Fn, Description);
9892 
9893   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9894     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9895         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9896         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9897   else
9898     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9899         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9900         << Description << mode << modeCount << NumFormalArgs;
9901 
9902   MaybeEmitInheritedConstructorNote(S, Found);
9903 }
9904 
9905 /// Arity mismatch diagnosis specific to a function overload candidate.
9906 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9907                                   unsigned NumFormalArgs) {
9908   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9909     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9910 }
9911 
9912 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9913   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9914     return TD;
9915   llvm_unreachable("Unsupported: Getting the described template declaration"
9916                    " for bad deduction diagnosis");
9917 }
9918 
9919 /// Diagnose a failed template-argument deduction.
9920 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9921                                  DeductionFailureInfo &DeductionFailure,
9922                                  unsigned NumArgs,
9923                                  bool TakingCandidateAddress) {
9924   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9925   NamedDecl *ParamD;
9926   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9927   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9928   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9929   switch (DeductionFailure.Result) {
9930   case Sema::TDK_Success:
9931     llvm_unreachable("TDK_success while diagnosing bad deduction");
9932 
9933   case Sema::TDK_Incomplete: {
9934     assert(ParamD && "no parameter found for incomplete deduction result");
9935     S.Diag(Templated->getLocation(),
9936            diag::note_ovl_candidate_incomplete_deduction)
9937         << ParamD->getDeclName();
9938     MaybeEmitInheritedConstructorNote(S, Found);
9939     return;
9940   }
9941 
9942   case Sema::TDK_IncompletePack: {
9943     assert(ParamD && "no parameter found for incomplete deduction result");
9944     S.Diag(Templated->getLocation(),
9945            diag::note_ovl_candidate_incomplete_deduction_pack)
9946         << ParamD->getDeclName()
9947         << (DeductionFailure.getFirstArg()->pack_size() + 1)
9948         << *DeductionFailure.getFirstArg();
9949     MaybeEmitInheritedConstructorNote(S, Found);
9950     return;
9951   }
9952 
9953   case Sema::TDK_Underqualified: {
9954     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9955     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9956 
9957     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9958 
9959     // Param will have been canonicalized, but it should just be a
9960     // qualified version of ParamD, so move the qualifiers to that.
9961     QualifierCollector Qs;
9962     Qs.strip(Param);
9963     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9964     assert(S.Context.hasSameType(Param, NonCanonParam));
9965 
9966     // Arg has also been canonicalized, but there's nothing we can do
9967     // about that.  It also doesn't matter as much, because it won't
9968     // have any template parameters in it (because deduction isn't
9969     // done on dependent types).
9970     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9971 
9972     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9973         << ParamD->getDeclName() << Arg << NonCanonParam;
9974     MaybeEmitInheritedConstructorNote(S, Found);
9975     return;
9976   }
9977 
9978   case Sema::TDK_Inconsistent: {
9979     assert(ParamD && "no parameter found for inconsistent deduction result");
9980     int which = 0;
9981     if (isa<TemplateTypeParmDecl>(ParamD))
9982       which = 0;
9983     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9984       // Deduction might have failed because we deduced arguments of two
9985       // different types for a non-type template parameter.
9986       // FIXME: Use a different TDK value for this.
9987       QualType T1 =
9988           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9989       QualType T2 =
9990           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9991       if (!S.Context.hasSameType(T1, T2)) {
9992         S.Diag(Templated->getLocation(),
9993                diag::note_ovl_candidate_inconsistent_deduction_types)
9994           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9995           << *DeductionFailure.getSecondArg() << T2;
9996         MaybeEmitInheritedConstructorNote(S, Found);
9997         return;
9998       }
9999 
10000       which = 1;
10001     } else {
10002       which = 2;
10003     }
10004 
10005     S.Diag(Templated->getLocation(),
10006            diag::note_ovl_candidate_inconsistent_deduction)
10007         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10008         << *DeductionFailure.getSecondArg();
10009     MaybeEmitInheritedConstructorNote(S, Found);
10010     return;
10011   }
10012 
10013   case Sema::TDK_InvalidExplicitArguments:
10014     assert(ParamD && "no parameter found for invalid explicit arguments");
10015     if (ParamD->getDeclName())
10016       S.Diag(Templated->getLocation(),
10017              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10018           << ParamD->getDeclName();
10019     else {
10020       int index = 0;
10021       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10022         index = TTP->getIndex();
10023       else if (NonTypeTemplateParmDecl *NTTP
10024                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10025         index = NTTP->getIndex();
10026       else
10027         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10028       S.Diag(Templated->getLocation(),
10029              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10030           << (index + 1);
10031     }
10032     MaybeEmitInheritedConstructorNote(S, Found);
10033     return;
10034 
10035   case Sema::TDK_TooManyArguments:
10036   case Sema::TDK_TooFewArguments:
10037     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10038     return;
10039 
10040   case Sema::TDK_InstantiationDepth:
10041     S.Diag(Templated->getLocation(),
10042            diag::note_ovl_candidate_instantiation_depth);
10043     MaybeEmitInheritedConstructorNote(S, Found);
10044     return;
10045 
10046   case Sema::TDK_SubstitutionFailure: {
10047     // Format the template argument list into the argument string.
10048     SmallString<128> TemplateArgString;
10049     if (TemplateArgumentList *Args =
10050             DeductionFailure.getTemplateArgumentList()) {
10051       TemplateArgString = " ";
10052       TemplateArgString += S.getTemplateArgumentBindingsText(
10053           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10054     }
10055 
10056     // If this candidate was disabled by enable_if, say so.
10057     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10058     if (PDiag && PDiag->second.getDiagID() ==
10059           diag::err_typename_nested_not_found_enable_if) {
10060       // FIXME: Use the source range of the condition, and the fully-qualified
10061       //        name of the enable_if template. These are both present in PDiag.
10062       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10063         << "'enable_if'" << TemplateArgString;
10064       return;
10065     }
10066 
10067     // We found a specific requirement that disabled the enable_if.
10068     if (PDiag && PDiag->second.getDiagID() ==
10069         diag::err_typename_nested_not_found_requirement) {
10070       S.Diag(Templated->getLocation(),
10071              diag::note_ovl_candidate_disabled_by_requirement)
10072         << PDiag->second.getStringArg(0) << TemplateArgString;
10073       return;
10074     }
10075 
10076     // Format the SFINAE diagnostic into the argument string.
10077     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10078     //        formatted message in another diagnostic.
10079     SmallString<128> SFINAEArgString;
10080     SourceRange R;
10081     if (PDiag) {
10082       SFINAEArgString = ": ";
10083       R = SourceRange(PDiag->first, PDiag->first);
10084       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10085     }
10086 
10087     S.Diag(Templated->getLocation(),
10088            diag::note_ovl_candidate_substitution_failure)
10089         << TemplateArgString << SFINAEArgString << R;
10090     MaybeEmitInheritedConstructorNote(S, Found);
10091     return;
10092   }
10093 
10094   case Sema::TDK_DeducedMismatch:
10095   case Sema::TDK_DeducedMismatchNested: {
10096     // Format the template argument list into the argument string.
10097     SmallString<128> TemplateArgString;
10098     if (TemplateArgumentList *Args =
10099             DeductionFailure.getTemplateArgumentList()) {
10100       TemplateArgString = " ";
10101       TemplateArgString += S.getTemplateArgumentBindingsText(
10102           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10103     }
10104 
10105     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10106         << (*DeductionFailure.getCallArgIndex() + 1)
10107         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10108         << TemplateArgString
10109         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10110     break;
10111   }
10112 
10113   case Sema::TDK_NonDeducedMismatch: {
10114     // FIXME: Provide a source location to indicate what we couldn't match.
10115     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10116     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10117     if (FirstTA.getKind() == TemplateArgument::Template &&
10118         SecondTA.getKind() == TemplateArgument::Template) {
10119       TemplateName FirstTN = FirstTA.getAsTemplate();
10120       TemplateName SecondTN = SecondTA.getAsTemplate();
10121       if (FirstTN.getKind() == TemplateName::Template &&
10122           SecondTN.getKind() == TemplateName::Template) {
10123         if (FirstTN.getAsTemplateDecl()->getName() ==
10124             SecondTN.getAsTemplateDecl()->getName()) {
10125           // FIXME: This fixes a bad diagnostic where both templates are named
10126           // the same.  This particular case is a bit difficult since:
10127           // 1) It is passed as a string to the diagnostic printer.
10128           // 2) The diagnostic printer only attempts to find a better
10129           //    name for types, not decls.
10130           // Ideally, this should folded into the diagnostic printer.
10131           S.Diag(Templated->getLocation(),
10132                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10133               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10134           return;
10135         }
10136       }
10137     }
10138 
10139     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10140         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10141       return;
10142 
10143     // FIXME: For generic lambda parameters, check if the function is a lambda
10144     // call operator, and if so, emit a prettier and more informative
10145     // diagnostic that mentions 'auto' and lambda in addition to
10146     // (or instead of?) the canonical template type parameters.
10147     S.Diag(Templated->getLocation(),
10148            diag::note_ovl_candidate_non_deduced_mismatch)
10149         << FirstTA << SecondTA;
10150     return;
10151   }
10152   // TODO: diagnose these individually, then kill off
10153   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10154   case Sema::TDK_MiscellaneousDeductionFailure:
10155     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10156     MaybeEmitInheritedConstructorNote(S, Found);
10157     return;
10158   case Sema::TDK_CUDATargetMismatch:
10159     S.Diag(Templated->getLocation(),
10160            diag::note_cuda_ovl_candidate_target_mismatch);
10161     return;
10162   }
10163 }
10164 
10165 /// Diagnose a failed template-argument deduction, for function calls.
10166 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10167                                  unsigned NumArgs,
10168                                  bool TakingCandidateAddress) {
10169   unsigned TDK = Cand->DeductionFailure.Result;
10170   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10171     if (CheckArityMismatch(S, Cand, NumArgs))
10172       return;
10173   }
10174   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10175                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10176 }
10177 
10178 /// CUDA: diagnose an invalid call across targets.
10179 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10180   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10181   FunctionDecl *Callee = Cand->Function;
10182 
10183   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10184                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10185 
10186   std::string FnDesc;
10187   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10188       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10189 
10190   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10191       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10192       << FnDesc /* Ignored */
10193       << CalleeTarget << CallerTarget;
10194 
10195   // This could be an implicit constructor for which we could not infer the
10196   // target due to a collsion. Diagnose that case.
10197   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10198   if (Meth != nullptr && Meth->isImplicit()) {
10199     CXXRecordDecl *ParentClass = Meth->getParent();
10200     Sema::CXXSpecialMember CSM;
10201 
10202     switch (FnKindPair.first) {
10203     default:
10204       return;
10205     case oc_implicit_default_constructor:
10206       CSM = Sema::CXXDefaultConstructor;
10207       break;
10208     case oc_implicit_copy_constructor:
10209       CSM = Sema::CXXCopyConstructor;
10210       break;
10211     case oc_implicit_move_constructor:
10212       CSM = Sema::CXXMoveConstructor;
10213       break;
10214     case oc_implicit_copy_assignment:
10215       CSM = Sema::CXXCopyAssignment;
10216       break;
10217     case oc_implicit_move_assignment:
10218       CSM = Sema::CXXMoveAssignment;
10219       break;
10220     };
10221 
10222     bool ConstRHS = false;
10223     if (Meth->getNumParams()) {
10224       if (const ReferenceType *RT =
10225               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10226         ConstRHS = RT->getPointeeType().isConstQualified();
10227       }
10228     }
10229 
10230     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10231                                               /* ConstRHS */ ConstRHS,
10232                                               /* Diagnose */ true);
10233   }
10234 }
10235 
10236 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10237   FunctionDecl *Callee = Cand->Function;
10238   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10239 
10240   S.Diag(Callee->getLocation(),
10241          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10242       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10243 }
10244 
10245 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10246   FunctionDecl *Callee = Cand->Function;
10247 
10248   S.Diag(Callee->getLocation(),
10249          diag::note_ovl_candidate_disabled_by_extension);
10250 }
10251 
10252 /// Generates a 'note' diagnostic for an overload candidate.  We've
10253 /// already generated a primary error at the call site.
10254 ///
10255 /// It really does need to be a single diagnostic with its caret
10256 /// pointed at the candidate declaration.  Yes, this creates some
10257 /// major challenges of technical writing.  Yes, this makes pointing
10258 /// out problems with specific arguments quite awkward.  It's still
10259 /// better than generating twenty screens of text for every failed
10260 /// overload.
10261 ///
10262 /// It would be great to be able to express per-candidate problems
10263 /// more richly for those diagnostic clients that cared, but we'd
10264 /// still have to be just as careful with the default diagnostics.
10265 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10266                                   unsigned NumArgs,
10267                                   bool TakingCandidateAddress) {
10268   FunctionDecl *Fn = Cand->Function;
10269 
10270   // Note deleted candidates, but only if they're viable.
10271   if (Cand->Viable) {
10272     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10273       std::string FnDesc;
10274       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10275           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10276 
10277       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10278           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10279           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10280       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10281       return;
10282     }
10283 
10284     // We don't really have anything else to say about viable candidates.
10285     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10286     return;
10287   }
10288 
10289   switch (Cand->FailureKind) {
10290   case ovl_fail_too_many_arguments:
10291   case ovl_fail_too_few_arguments:
10292     return DiagnoseArityMismatch(S, Cand, NumArgs);
10293 
10294   case ovl_fail_bad_deduction:
10295     return DiagnoseBadDeduction(S, Cand, NumArgs,
10296                                 TakingCandidateAddress);
10297 
10298   case ovl_fail_illegal_constructor: {
10299     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10300       << (Fn->getPrimaryTemplate() ? 1 : 0);
10301     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10302     return;
10303   }
10304 
10305   case ovl_fail_trivial_conversion:
10306   case ovl_fail_bad_final_conversion:
10307   case ovl_fail_final_conversion_not_exact:
10308     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10309 
10310   case ovl_fail_bad_conversion: {
10311     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10312     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10313       if (Cand->Conversions[I].isBad())
10314         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10315 
10316     // FIXME: this currently happens when we're called from SemaInit
10317     // when user-conversion overload fails.  Figure out how to handle
10318     // those conditions and diagnose them well.
10319     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10320   }
10321 
10322   case ovl_fail_bad_target:
10323     return DiagnoseBadTarget(S, Cand);
10324 
10325   case ovl_fail_enable_if:
10326     return DiagnoseFailedEnableIfAttr(S, Cand);
10327 
10328   case ovl_fail_ext_disabled:
10329     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10330 
10331   case ovl_fail_inhctor_slice:
10332     // It's generally not interesting to note copy/move constructors here.
10333     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10334       return;
10335     S.Diag(Fn->getLocation(),
10336            diag::note_ovl_candidate_inherited_constructor_slice)
10337       << (Fn->getPrimaryTemplate() ? 1 : 0)
10338       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10339     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10340     return;
10341 
10342   case ovl_fail_addr_not_available: {
10343     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10344     (void)Available;
10345     assert(!Available);
10346     break;
10347   }
10348   case ovl_non_default_multiversion_function:
10349     // Do nothing, these should simply be ignored.
10350     break;
10351   }
10352 }
10353 
10354 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10355   // Desugar the type of the surrogate down to a function type,
10356   // retaining as many typedefs as possible while still showing
10357   // the function type (and, therefore, its parameter types).
10358   QualType FnType = Cand->Surrogate->getConversionType();
10359   bool isLValueReference = false;
10360   bool isRValueReference = false;
10361   bool isPointer = false;
10362   if (const LValueReferenceType *FnTypeRef =
10363         FnType->getAs<LValueReferenceType>()) {
10364     FnType = FnTypeRef->getPointeeType();
10365     isLValueReference = true;
10366   } else if (const RValueReferenceType *FnTypeRef =
10367                FnType->getAs<RValueReferenceType>()) {
10368     FnType = FnTypeRef->getPointeeType();
10369     isRValueReference = true;
10370   }
10371   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10372     FnType = FnTypePtr->getPointeeType();
10373     isPointer = true;
10374   }
10375   // Desugar down to a function type.
10376   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10377   // Reconstruct the pointer/reference as appropriate.
10378   if (isPointer) FnType = S.Context.getPointerType(FnType);
10379   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10380   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10381 
10382   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10383     << FnType;
10384 }
10385 
10386 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10387                                          SourceLocation OpLoc,
10388                                          OverloadCandidate *Cand) {
10389   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10390   std::string TypeStr("operator");
10391   TypeStr += Opc;
10392   TypeStr += "(";
10393   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10394   if (Cand->Conversions.size() == 1) {
10395     TypeStr += ")";
10396     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10397   } else {
10398     TypeStr += ", ";
10399     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10400     TypeStr += ")";
10401     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10402   }
10403 }
10404 
10405 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10406                                          OverloadCandidate *Cand) {
10407   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10408     if (ICS.isBad()) break; // all meaningless after first invalid
10409     if (!ICS.isAmbiguous()) continue;
10410 
10411     ICS.DiagnoseAmbiguousConversion(
10412         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10413   }
10414 }
10415 
10416 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10417   if (Cand->Function)
10418     return Cand->Function->getLocation();
10419   if (Cand->IsSurrogate)
10420     return Cand->Surrogate->getLocation();
10421   return SourceLocation();
10422 }
10423 
10424 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10425   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10426   case Sema::TDK_Success:
10427   case Sema::TDK_NonDependentConversionFailure:
10428     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10429 
10430   case Sema::TDK_Invalid:
10431   case Sema::TDK_Incomplete:
10432   case Sema::TDK_IncompletePack:
10433     return 1;
10434 
10435   case Sema::TDK_Underqualified:
10436   case Sema::TDK_Inconsistent:
10437     return 2;
10438 
10439   case Sema::TDK_SubstitutionFailure:
10440   case Sema::TDK_DeducedMismatch:
10441   case Sema::TDK_DeducedMismatchNested:
10442   case Sema::TDK_NonDeducedMismatch:
10443   case Sema::TDK_MiscellaneousDeductionFailure:
10444   case Sema::TDK_CUDATargetMismatch:
10445     return 3;
10446 
10447   case Sema::TDK_InstantiationDepth:
10448     return 4;
10449 
10450   case Sema::TDK_InvalidExplicitArguments:
10451     return 5;
10452 
10453   case Sema::TDK_TooManyArguments:
10454   case Sema::TDK_TooFewArguments:
10455     return 6;
10456   }
10457   llvm_unreachable("Unhandled deduction result");
10458 }
10459 
10460 namespace {
10461 struct CompareOverloadCandidatesForDisplay {
10462   Sema &S;
10463   SourceLocation Loc;
10464   size_t NumArgs;
10465   OverloadCandidateSet::CandidateSetKind CSK;
10466 
10467   CompareOverloadCandidatesForDisplay(
10468       Sema &S, SourceLocation Loc, size_t NArgs,
10469       OverloadCandidateSet::CandidateSetKind CSK)
10470       : S(S), NumArgs(NArgs), CSK(CSK) {}
10471 
10472   bool operator()(const OverloadCandidate *L,
10473                   const OverloadCandidate *R) {
10474     // Fast-path this check.
10475     if (L == R) return false;
10476 
10477     // Order first by viability.
10478     if (L->Viable) {
10479       if (!R->Viable) return true;
10480 
10481       // TODO: introduce a tri-valued comparison for overload
10482       // candidates.  Would be more worthwhile if we had a sort
10483       // that could exploit it.
10484       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10485         return true;
10486       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10487         return false;
10488     } else if (R->Viable)
10489       return false;
10490 
10491     assert(L->Viable == R->Viable);
10492 
10493     // Criteria by which we can sort non-viable candidates:
10494     if (!L->Viable) {
10495       // 1. Arity mismatches come after other candidates.
10496       if (L->FailureKind == ovl_fail_too_many_arguments ||
10497           L->FailureKind == ovl_fail_too_few_arguments) {
10498         if (R->FailureKind == ovl_fail_too_many_arguments ||
10499             R->FailureKind == ovl_fail_too_few_arguments) {
10500           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10501           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10502           if (LDist == RDist) {
10503             if (L->FailureKind == R->FailureKind)
10504               // Sort non-surrogates before surrogates.
10505               return !L->IsSurrogate && R->IsSurrogate;
10506             // Sort candidates requiring fewer parameters than there were
10507             // arguments given after candidates requiring more parameters
10508             // than there were arguments given.
10509             return L->FailureKind == ovl_fail_too_many_arguments;
10510           }
10511           return LDist < RDist;
10512         }
10513         return false;
10514       }
10515       if (R->FailureKind == ovl_fail_too_many_arguments ||
10516           R->FailureKind == ovl_fail_too_few_arguments)
10517         return true;
10518 
10519       // 2. Bad conversions come first and are ordered by the number
10520       // of bad conversions and quality of good conversions.
10521       if (L->FailureKind == ovl_fail_bad_conversion) {
10522         if (R->FailureKind != ovl_fail_bad_conversion)
10523           return true;
10524 
10525         // The conversion that can be fixed with a smaller number of changes,
10526         // comes first.
10527         unsigned numLFixes = L->Fix.NumConversionsFixed;
10528         unsigned numRFixes = R->Fix.NumConversionsFixed;
10529         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10530         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10531         if (numLFixes != numRFixes) {
10532           return numLFixes < numRFixes;
10533         }
10534 
10535         // If there's any ordering between the defined conversions...
10536         // FIXME: this might not be transitive.
10537         assert(L->Conversions.size() == R->Conversions.size());
10538 
10539         int leftBetter = 0;
10540         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10541         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10542           switch (CompareImplicitConversionSequences(S, Loc,
10543                                                      L->Conversions[I],
10544                                                      R->Conversions[I])) {
10545           case ImplicitConversionSequence::Better:
10546             leftBetter++;
10547             break;
10548 
10549           case ImplicitConversionSequence::Worse:
10550             leftBetter--;
10551             break;
10552 
10553           case ImplicitConversionSequence::Indistinguishable:
10554             break;
10555           }
10556         }
10557         if (leftBetter > 0) return true;
10558         if (leftBetter < 0) return false;
10559 
10560       } else if (R->FailureKind == ovl_fail_bad_conversion)
10561         return false;
10562 
10563       if (L->FailureKind == ovl_fail_bad_deduction) {
10564         if (R->FailureKind != ovl_fail_bad_deduction)
10565           return true;
10566 
10567         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10568           return RankDeductionFailure(L->DeductionFailure)
10569                < RankDeductionFailure(R->DeductionFailure);
10570       } else if (R->FailureKind == ovl_fail_bad_deduction)
10571         return false;
10572 
10573       // TODO: others?
10574     }
10575 
10576     // Sort everything else by location.
10577     SourceLocation LLoc = GetLocationForCandidate(L);
10578     SourceLocation RLoc = GetLocationForCandidate(R);
10579 
10580     // Put candidates without locations (e.g. builtins) at the end.
10581     if (LLoc.isInvalid()) return false;
10582     if (RLoc.isInvalid()) return true;
10583 
10584     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10585   }
10586 };
10587 }
10588 
10589 /// CompleteNonViableCandidate - Normally, overload resolution only
10590 /// computes up to the first bad conversion. Produces the FixIt set if
10591 /// possible.
10592 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10593                                        ArrayRef<Expr *> Args) {
10594   assert(!Cand->Viable);
10595 
10596   // Don't do anything on failures other than bad conversion.
10597   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10598 
10599   // We only want the FixIts if all the arguments can be corrected.
10600   bool Unfixable = false;
10601   // Use a implicit copy initialization to check conversion fixes.
10602   Cand->Fix.setConversionChecker(TryCopyInitialization);
10603 
10604   // Attempt to fix the bad conversion.
10605   unsigned ConvCount = Cand->Conversions.size();
10606   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10607        ++ConvIdx) {
10608     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10609     if (Cand->Conversions[ConvIdx].isInitialized() &&
10610         Cand->Conversions[ConvIdx].isBad()) {
10611       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10612       break;
10613     }
10614   }
10615 
10616   // FIXME: this should probably be preserved from the overload
10617   // operation somehow.
10618   bool SuppressUserConversions = false;
10619 
10620   unsigned ConvIdx = 0;
10621   ArrayRef<QualType> ParamTypes;
10622 
10623   if (Cand->IsSurrogate) {
10624     QualType ConvType
10625       = Cand->Surrogate->getConversionType().getNonReferenceType();
10626     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10627       ConvType = ConvPtrType->getPointeeType();
10628     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10629     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10630     ConvIdx = 1;
10631   } else if (Cand->Function) {
10632     ParamTypes =
10633         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10634     if (isa<CXXMethodDecl>(Cand->Function) &&
10635         !isa<CXXConstructorDecl>(Cand->Function)) {
10636       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10637       ConvIdx = 1;
10638     }
10639   } else {
10640     // Builtin operator.
10641     assert(ConvCount <= 3);
10642     ParamTypes = Cand->BuiltinParamTypes;
10643   }
10644 
10645   // Fill in the rest of the conversions.
10646   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10647     if (Cand->Conversions[ConvIdx].isInitialized()) {
10648       // We've already checked this conversion.
10649     } else if (ArgIdx < ParamTypes.size()) {
10650       if (ParamTypes[ArgIdx]->isDependentType())
10651         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10652             Args[ArgIdx]->getType());
10653       else {
10654         Cand->Conversions[ConvIdx] =
10655             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10656                                   SuppressUserConversions,
10657                                   /*InOverloadResolution=*/true,
10658                                   /*AllowObjCWritebackConversion=*/
10659                                   S.getLangOpts().ObjCAutoRefCount);
10660         // Store the FixIt in the candidate if it exists.
10661         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10662           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10663       }
10664     } else
10665       Cand->Conversions[ConvIdx].setEllipsis();
10666   }
10667 }
10668 
10669 /// When overload resolution fails, prints diagnostic messages containing the
10670 /// candidates in the candidate set.
10671 void OverloadCandidateSet::NoteCandidates(
10672     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10673     StringRef Opc, SourceLocation OpLoc,
10674     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10675   // Sort the candidates by viability and position.  Sorting directly would
10676   // be prohibitive, so we make a set of pointers and sort those.
10677   SmallVector<OverloadCandidate*, 32> Cands;
10678   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10679   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10680     if (!Filter(*Cand))
10681       continue;
10682     if (Cand->Viable)
10683       Cands.push_back(Cand);
10684     else if (OCD == OCD_AllCandidates) {
10685       CompleteNonViableCandidate(S, Cand, Args);
10686       if (Cand->Function || Cand->IsSurrogate)
10687         Cands.push_back(Cand);
10688       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10689       // want to list every possible builtin candidate.
10690     }
10691   }
10692 
10693   std::stable_sort(Cands.begin(), Cands.end(),
10694             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10695 
10696   bool ReportedAmbiguousConversions = false;
10697 
10698   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10699   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10700   unsigned CandsShown = 0;
10701   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10702     OverloadCandidate *Cand = *I;
10703 
10704     // Set an arbitrary limit on the number of candidate functions we'll spam
10705     // the user with.  FIXME: This limit should depend on details of the
10706     // candidate list.
10707     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10708       break;
10709     }
10710     ++CandsShown;
10711 
10712     if (Cand->Function)
10713       NoteFunctionCandidate(S, Cand, Args.size(),
10714                             /*TakingCandidateAddress=*/false);
10715     else if (Cand->IsSurrogate)
10716       NoteSurrogateCandidate(S, Cand);
10717     else {
10718       assert(Cand->Viable &&
10719              "Non-viable built-in candidates are not added to Cands.");
10720       // Generally we only see ambiguities including viable builtin
10721       // operators if overload resolution got screwed up by an
10722       // ambiguous user-defined conversion.
10723       //
10724       // FIXME: It's quite possible for different conversions to see
10725       // different ambiguities, though.
10726       if (!ReportedAmbiguousConversions) {
10727         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10728         ReportedAmbiguousConversions = true;
10729       }
10730 
10731       // If this is a viable builtin, print it.
10732       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10733     }
10734   }
10735 
10736   if (I != E)
10737     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10738 }
10739 
10740 static SourceLocation
10741 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10742   return Cand->Specialization ? Cand->Specialization->getLocation()
10743                               : SourceLocation();
10744 }
10745 
10746 namespace {
10747 struct CompareTemplateSpecCandidatesForDisplay {
10748   Sema &S;
10749   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10750 
10751   bool operator()(const TemplateSpecCandidate *L,
10752                   const TemplateSpecCandidate *R) {
10753     // Fast-path this check.
10754     if (L == R)
10755       return false;
10756 
10757     // Assuming that both candidates are not matches...
10758 
10759     // Sort by the ranking of deduction failures.
10760     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10761       return RankDeductionFailure(L->DeductionFailure) <
10762              RankDeductionFailure(R->DeductionFailure);
10763 
10764     // Sort everything else by location.
10765     SourceLocation LLoc = GetLocationForCandidate(L);
10766     SourceLocation RLoc = GetLocationForCandidate(R);
10767 
10768     // Put candidates without locations (e.g. builtins) at the end.
10769     if (LLoc.isInvalid())
10770       return false;
10771     if (RLoc.isInvalid())
10772       return true;
10773 
10774     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10775   }
10776 };
10777 }
10778 
10779 /// Diagnose a template argument deduction failure.
10780 /// We are treating these failures as overload failures due to bad
10781 /// deductions.
10782 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10783                                                  bool ForTakingAddress) {
10784   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10785                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10786 }
10787 
10788 void TemplateSpecCandidateSet::destroyCandidates() {
10789   for (iterator i = begin(), e = end(); i != e; ++i) {
10790     i->DeductionFailure.Destroy();
10791   }
10792 }
10793 
10794 void TemplateSpecCandidateSet::clear() {
10795   destroyCandidates();
10796   Candidates.clear();
10797 }
10798 
10799 /// NoteCandidates - When no template specialization match is found, prints
10800 /// diagnostic messages containing the non-matching specializations that form
10801 /// the candidate set.
10802 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10803 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10804 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10805   // Sort the candidates by position (assuming no candidate is a match).
10806   // Sorting directly would be prohibitive, so we make a set of pointers
10807   // and sort those.
10808   SmallVector<TemplateSpecCandidate *, 32> Cands;
10809   Cands.reserve(size());
10810   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10811     if (Cand->Specialization)
10812       Cands.push_back(Cand);
10813     // Otherwise, this is a non-matching builtin candidate.  We do not,
10814     // in general, want to list every possible builtin candidate.
10815   }
10816 
10817   llvm::sort(Cands.begin(), Cands.end(),
10818              CompareTemplateSpecCandidatesForDisplay(S));
10819 
10820   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10821   // for generalization purposes (?).
10822   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10823 
10824   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10825   unsigned CandsShown = 0;
10826   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10827     TemplateSpecCandidate *Cand = *I;
10828 
10829     // Set an arbitrary limit on the number of candidates we'll spam
10830     // the user with.  FIXME: This limit should depend on details of the
10831     // candidate list.
10832     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10833       break;
10834     ++CandsShown;
10835 
10836     assert(Cand->Specialization &&
10837            "Non-matching built-in candidates are not added to Cands.");
10838     Cand->NoteDeductionFailure(S, ForTakingAddress);
10839   }
10840 
10841   if (I != E)
10842     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10843 }
10844 
10845 // [PossiblyAFunctionType]  -->   [Return]
10846 // NonFunctionType --> NonFunctionType
10847 // R (A) --> R(A)
10848 // R (*)(A) --> R (A)
10849 // R (&)(A) --> R (A)
10850 // R (S::*)(A) --> R (A)
10851 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10852   QualType Ret = PossiblyAFunctionType;
10853   if (const PointerType *ToTypePtr =
10854     PossiblyAFunctionType->getAs<PointerType>())
10855     Ret = ToTypePtr->getPointeeType();
10856   else if (const ReferenceType *ToTypeRef =
10857     PossiblyAFunctionType->getAs<ReferenceType>())
10858     Ret = ToTypeRef->getPointeeType();
10859   else if (const MemberPointerType *MemTypePtr =
10860     PossiblyAFunctionType->getAs<MemberPointerType>())
10861     Ret = MemTypePtr->getPointeeType();
10862   Ret =
10863     Context.getCanonicalType(Ret).getUnqualifiedType();
10864   return Ret;
10865 }
10866 
10867 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10868                                  bool Complain = true) {
10869   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10870       S.DeduceReturnType(FD, Loc, Complain))
10871     return true;
10872 
10873   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10874   if (S.getLangOpts().CPlusPlus17 &&
10875       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10876       !S.ResolveExceptionSpec(Loc, FPT))
10877     return true;
10878 
10879   return false;
10880 }
10881 
10882 namespace {
10883 // A helper class to help with address of function resolution
10884 // - allows us to avoid passing around all those ugly parameters
10885 class AddressOfFunctionResolver {
10886   Sema& S;
10887   Expr* SourceExpr;
10888   const QualType& TargetType;
10889   QualType TargetFunctionType; // Extracted function type from target type
10890 
10891   bool Complain;
10892   //DeclAccessPair& ResultFunctionAccessPair;
10893   ASTContext& Context;
10894 
10895   bool TargetTypeIsNonStaticMemberFunction;
10896   bool FoundNonTemplateFunction;
10897   bool StaticMemberFunctionFromBoundPointer;
10898   bool HasComplained;
10899 
10900   OverloadExpr::FindResult OvlExprInfo;
10901   OverloadExpr *OvlExpr;
10902   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10903   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10904   TemplateSpecCandidateSet FailedCandidates;
10905 
10906 public:
10907   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10908                             const QualType &TargetType, bool Complain)
10909       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10910         Complain(Complain), Context(S.getASTContext()),
10911         TargetTypeIsNonStaticMemberFunction(
10912             !!TargetType->getAs<MemberPointerType>()),
10913         FoundNonTemplateFunction(false),
10914         StaticMemberFunctionFromBoundPointer(false),
10915         HasComplained(false),
10916         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10917         OvlExpr(OvlExprInfo.Expression),
10918         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10919     ExtractUnqualifiedFunctionTypeFromTargetType();
10920 
10921     if (TargetFunctionType->isFunctionType()) {
10922       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10923         if (!UME->isImplicitAccess() &&
10924             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10925           StaticMemberFunctionFromBoundPointer = true;
10926     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10927       DeclAccessPair dap;
10928       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10929               OvlExpr, false, &dap)) {
10930         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10931           if (!Method->isStatic()) {
10932             // If the target type is a non-function type and the function found
10933             // is a non-static member function, pretend as if that was the
10934             // target, it's the only possible type to end up with.
10935             TargetTypeIsNonStaticMemberFunction = true;
10936 
10937             // And skip adding the function if its not in the proper form.
10938             // We'll diagnose this due to an empty set of functions.
10939             if (!OvlExprInfo.HasFormOfMemberPointer)
10940               return;
10941           }
10942 
10943         Matches.push_back(std::make_pair(dap, Fn));
10944       }
10945       return;
10946     }
10947 
10948     if (OvlExpr->hasExplicitTemplateArgs())
10949       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10950 
10951     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10952       // C++ [over.over]p4:
10953       //   If more than one function is selected, [...]
10954       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10955         if (FoundNonTemplateFunction)
10956           EliminateAllTemplateMatches();
10957         else
10958           EliminateAllExceptMostSpecializedTemplate();
10959       }
10960     }
10961 
10962     if (S.getLangOpts().CUDA && Matches.size() > 1)
10963       EliminateSuboptimalCudaMatches();
10964   }
10965 
10966   bool hasComplained() const { return HasComplained; }
10967 
10968 private:
10969   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10970     QualType Discard;
10971     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10972            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10973   }
10974 
10975   /// \return true if A is considered a better overload candidate for the
10976   /// desired type than B.
10977   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10978     // If A doesn't have exactly the correct type, we don't want to classify it
10979     // as "better" than anything else. This way, the user is required to
10980     // disambiguate for us if there are multiple candidates and no exact match.
10981     return candidateHasExactlyCorrectType(A) &&
10982            (!candidateHasExactlyCorrectType(B) ||
10983             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10984   }
10985 
10986   /// \return true if we were able to eliminate all but one overload candidate,
10987   /// false otherwise.
10988   bool eliminiateSuboptimalOverloadCandidates() {
10989     // Same algorithm as overload resolution -- one pass to pick the "best",
10990     // another pass to be sure that nothing is better than the best.
10991     auto Best = Matches.begin();
10992     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10993       if (isBetterCandidate(I->second, Best->second))
10994         Best = I;
10995 
10996     const FunctionDecl *BestFn = Best->second;
10997     auto IsBestOrInferiorToBest = [this, BestFn](
10998         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10999       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11000     };
11001 
11002     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11003     // option, so we can potentially give the user a better error
11004     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
11005       return false;
11006     Matches[0] = *Best;
11007     Matches.resize(1);
11008     return true;
11009   }
11010 
11011   bool isTargetTypeAFunction() const {
11012     return TargetFunctionType->isFunctionType();
11013   }
11014 
11015   // [ToType]     [Return]
11016 
11017   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11018   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11019   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11020   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11021     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11022   }
11023 
11024   // return true if any matching specializations were found
11025   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11026                                    const DeclAccessPair& CurAccessFunPair) {
11027     if (CXXMethodDecl *Method
11028               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11029       // Skip non-static function templates when converting to pointer, and
11030       // static when converting to member pointer.
11031       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11032         return false;
11033     }
11034     else if (TargetTypeIsNonStaticMemberFunction)
11035       return false;
11036 
11037     // C++ [over.over]p2:
11038     //   If the name is a function template, template argument deduction is
11039     //   done (14.8.2.2), and if the argument deduction succeeds, the
11040     //   resulting template argument list is used to generate a single
11041     //   function template specialization, which is added to the set of
11042     //   overloaded functions considered.
11043     FunctionDecl *Specialization = nullptr;
11044     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11045     if (Sema::TemplateDeductionResult Result
11046           = S.DeduceTemplateArguments(FunctionTemplate,
11047                                       &OvlExplicitTemplateArgs,
11048                                       TargetFunctionType, Specialization,
11049                                       Info, /*IsAddressOfFunction*/true)) {
11050       // Make a note of the failed deduction for diagnostics.
11051       FailedCandidates.addCandidate()
11052           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11053                MakeDeductionFailureInfo(Context, Result, Info));
11054       return false;
11055     }
11056 
11057     // Template argument deduction ensures that we have an exact match or
11058     // compatible pointer-to-function arguments that would be adjusted by ICS.
11059     // This function template specicalization works.
11060     assert(S.isSameOrCompatibleFunctionType(
11061               Context.getCanonicalType(Specialization->getType()),
11062               Context.getCanonicalType(TargetFunctionType)));
11063 
11064     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11065       return false;
11066 
11067     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11068     return true;
11069   }
11070 
11071   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11072                                       const DeclAccessPair& CurAccessFunPair) {
11073     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11074       // Skip non-static functions when converting to pointer, and static
11075       // when converting to member pointer.
11076       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11077         return false;
11078     }
11079     else if (TargetTypeIsNonStaticMemberFunction)
11080       return false;
11081 
11082     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11083       if (S.getLangOpts().CUDA)
11084         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11085           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11086             return false;
11087       if (FunDecl->isMultiVersion()) {
11088         const auto *TA = FunDecl->getAttr<TargetAttr>();
11089         if (TA && !TA->isDefaultVersion())
11090           return false;
11091       }
11092 
11093       // If any candidate has a placeholder return type, trigger its deduction
11094       // now.
11095       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11096                                Complain)) {
11097         HasComplained |= Complain;
11098         return false;
11099       }
11100 
11101       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11102         return false;
11103 
11104       // If we're in C, we need to support types that aren't exactly identical.
11105       if (!S.getLangOpts().CPlusPlus ||
11106           candidateHasExactlyCorrectType(FunDecl)) {
11107         Matches.push_back(std::make_pair(
11108             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11109         FoundNonTemplateFunction = true;
11110         return true;
11111       }
11112     }
11113 
11114     return false;
11115   }
11116 
11117   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11118     bool Ret = false;
11119 
11120     // If the overload expression doesn't have the form of a pointer to
11121     // member, don't try to convert it to a pointer-to-member type.
11122     if (IsInvalidFormOfPointerToMemberFunction())
11123       return false;
11124 
11125     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11126                                E = OvlExpr->decls_end();
11127          I != E; ++I) {
11128       // Look through any using declarations to find the underlying function.
11129       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11130 
11131       // C++ [over.over]p3:
11132       //   Non-member functions and static member functions match
11133       //   targets of type "pointer-to-function" or "reference-to-function."
11134       //   Nonstatic member functions match targets of
11135       //   type "pointer-to-member-function."
11136       // Note that according to DR 247, the containing class does not matter.
11137       if (FunctionTemplateDecl *FunctionTemplate
11138                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11139         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11140           Ret = true;
11141       }
11142       // If we have explicit template arguments supplied, skip non-templates.
11143       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11144                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11145         Ret = true;
11146     }
11147     assert(Ret || Matches.empty());
11148     return Ret;
11149   }
11150 
11151   void EliminateAllExceptMostSpecializedTemplate() {
11152     //   [...] and any given function template specialization F1 is
11153     //   eliminated if the set contains a second function template
11154     //   specialization whose function template is more specialized
11155     //   than the function template of F1 according to the partial
11156     //   ordering rules of 14.5.5.2.
11157 
11158     // The algorithm specified above is quadratic. We instead use a
11159     // two-pass algorithm (similar to the one used to identify the
11160     // best viable function in an overload set) that identifies the
11161     // best function template (if it exists).
11162 
11163     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11164     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11165       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11166 
11167     // TODO: It looks like FailedCandidates does not serve much purpose
11168     // here, since the no_viable diagnostic has index 0.
11169     UnresolvedSetIterator Result = S.getMostSpecialized(
11170         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11171         SourceExpr->getLocStart(), S.PDiag(),
11172         S.PDiag(diag::err_addr_ovl_ambiguous)
11173             << Matches[0].second->getDeclName(),
11174         S.PDiag(diag::note_ovl_candidate)
11175             << (unsigned)oc_function << (unsigned)ocs_described_template,
11176         Complain, TargetFunctionType);
11177 
11178     if (Result != MatchesCopy.end()) {
11179       // Make it the first and only element
11180       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11181       Matches[0].second = cast<FunctionDecl>(*Result);
11182       Matches.resize(1);
11183     } else
11184       HasComplained |= Complain;
11185   }
11186 
11187   void EliminateAllTemplateMatches() {
11188     //   [...] any function template specializations in the set are
11189     //   eliminated if the set also contains a non-template function, [...]
11190     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11191       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11192         ++I;
11193       else {
11194         Matches[I] = Matches[--N];
11195         Matches.resize(N);
11196       }
11197     }
11198   }
11199 
11200   void EliminateSuboptimalCudaMatches() {
11201     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11202   }
11203 
11204 public:
11205   void ComplainNoMatchesFound() const {
11206     assert(Matches.empty());
11207     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11208         << OvlExpr->getName() << TargetFunctionType
11209         << OvlExpr->getSourceRange();
11210     if (FailedCandidates.empty())
11211       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11212                                   /*TakingAddress=*/true);
11213     else {
11214       // We have some deduction failure messages. Use them to diagnose
11215       // the function templates, and diagnose the non-template candidates
11216       // normally.
11217       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11218                                  IEnd = OvlExpr->decls_end();
11219            I != IEnd; ++I)
11220         if (FunctionDecl *Fun =
11221                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11222           if (!functionHasPassObjectSizeParams(Fun))
11223             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11224                                     /*TakingAddress=*/true);
11225       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11226     }
11227   }
11228 
11229   bool IsInvalidFormOfPointerToMemberFunction() const {
11230     return TargetTypeIsNonStaticMemberFunction &&
11231       !OvlExprInfo.HasFormOfMemberPointer;
11232   }
11233 
11234   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11235       // TODO: Should we condition this on whether any functions might
11236       // have matched, or is it more appropriate to do that in callers?
11237       // TODO: a fixit wouldn't hurt.
11238       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11239         << TargetType << OvlExpr->getSourceRange();
11240   }
11241 
11242   bool IsStaticMemberFunctionFromBoundPointer() const {
11243     return StaticMemberFunctionFromBoundPointer;
11244   }
11245 
11246   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11247     S.Diag(OvlExpr->getLocStart(),
11248            diag::err_invalid_form_pointer_member_function)
11249       << OvlExpr->getSourceRange();
11250   }
11251 
11252   void ComplainOfInvalidConversion() const {
11253     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11254       << OvlExpr->getName() << TargetType;
11255   }
11256 
11257   void ComplainMultipleMatchesFound() const {
11258     assert(Matches.size() > 1);
11259     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11260       << OvlExpr->getName()
11261       << OvlExpr->getSourceRange();
11262     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11263                                 /*TakingAddress=*/true);
11264   }
11265 
11266   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11267 
11268   int getNumMatches() const { return Matches.size(); }
11269 
11270   FunctionDecl* getMatchingFunctionDecl() const {
11271     if (Matches.size() != 1) return nullptr;
11272     return Matches[0].second;
11273   }
11274 
11275   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11276     if (Matches.size() != 1) return nullptr;
11277     return &Matches[0].first;
11278   }
11279 };
11280 }
11281 
11282 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11283 /// an overloaded function (C++ [over.over]), where @p From is an
11284 /// expression with overloaded function type and @p ToType is the type
11285 /// we're trying to resolve to. For example:
11286 ///
11287 /// @code
11288 /// int f(double);
11289 /// int f(int);
11290 ///
11291 /// int (*pfd)(double) = f; // selects f(double)
11292 /// @endcode
11293 ///
11294 /// This routine returns the resulting FunctionDecl if it could be
11295 /// resolved, and NULL otherwise. When @p Complain is true, this
11296 /// routine will emit diagnostics if there is an error.
11297 FunctionDecl *
11298 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11299                                          QualType TargetType,
11300                                          bool Complain,
11301                                          DeclAccessPair &FoundResult,
11302                                          bool *pHadMultipleCandidates) {
11303   assert(AddressOfExpr->getType() == Context.OverloadTy);
11304 
11305   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11306                                      Complain);
11307   int NumMatches = Resolver.getNumMatches();
11308   FunctionDecl *Fn = nullptr;
11309   bool ShouldComplain = Complain && !Resolver.hasComplained();
11310   if (NumMatches == 0 && ShouldComplain) {
11311     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11312       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11313     else
11314       Resolver.ComplainNoMatchesFound();
11315   }
11316   else if (NumMatches > 1 && ShouldComplain)
11317     Resolver.ComplainMultipleMatchesFound();
11318   else if (NumMatches == 1) {
11319     Fn = Resolver.getMatchingFunctionDecl();
11320     assert(Fn);
11321     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11322       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11323     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11324     if (Complain) {
11325       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11326         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11327       else
11328         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11329     }
11330   }
11331 
11332   if (pHadMultipleCandidates)
11333     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11334   return Fn;
11335 }
11336 
11337 /// Given an expression that refers to an overloaded function, try to
11338 /// resolve that function to a single function that can have its address taken.
11339 /// This will modify `Pair` iff it returns non-null.
11340 ///
11341 /// This routine can only realistically succeed if all but one candidates in the
11342 /// overload set for SrcExpr cannot have their addresses taken.
11343 FunctionDecl *
11344 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11345                                                   DeclAccessPair &Pair) {
11346   OverloadExpr::FindResult R = OverloadExpr::find(E);
11347   OverloadExpr *Ovl = R.Expression;
11348   FunctionDecl *Result = nullptr;
11349   DeclAccessPair DAP;
11350   // Don't use the AddressOfResolver because we're specifically looking for
11351   // cases where we have one overload candidate that lacks
11352   // enable_if/pass_object_size/...
11353   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11354     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11355     if (!FD)
11356       return nullptr;
11357 
11358     if (!checkAddressOfFunctionIsAvailable(FD))
11359       continue;
11360 
11361     // We have more than one result; quit.
11362     if (Result)
11363       return nullptr;
11364     DAP = I.getPair();
11365     Result = FD;
11366   }
11367 
11368   if (Result)
11369     Pair = DAP;
11370   return Result;
11371 }
11372 
11373 /// Given an overloaded function, tries to turn it into a non-overloaded
11374 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11375 /// will perform access checks, diagnose the use of the resultant decl, and, if
11376 /// requested, potentially perform a function-to-pointer decay.
11377 ///
11378 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11379 /// Otherwise, returns true. This may emit diagnostics and return true.
11380 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11381     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11382   Expr *E = SrcExpr.get();
11383   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11384 
11385   DeclAccessPair DAP;
11386   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11387   if (!Found || Found->isCPUDispatchMultiVersion() ||
11388       Found->isCPUSpecificMultiVersion())
11389     return false;
11390 
11391   // Emitting multiple diagnostics for a function that is both inaccessible and
11392   // unavailable is consistent with our behavior elsewhere. So, always check
11393   // for both.
11394   DiagnoseUseOfDecl(Found, E->getExprLoc());
11395   CheckAddressOfMemberAccess(E, DAP);
11396   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11397   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11398     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11399   else
11400     SrcExpr = Fixed;
11401   return true;
11402 }
11403 
11404 /// Given an expression that refers to an overloaded function, try to
11405 /// resolve that overloaded function expression down to a single function.
11406 ///
11407 /// This routine can only resolve template-ids that refer to a single function
11408 /// template, where that template-id refers to a single template whose template
11409 /// arguments are either provided by the template-id or have defaults,
11410 /// as described in C++0x [temp.arg.explicit]p3.
11411 ///
11412 /// If no template-ids are found, no diagnostics are emitted and NULL is
11413 /// returned.
11414 FunctionDecl *
11415 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11416                                                   bool Complain,
11417                                                   DeclAccessPair *FoundResult) {
11418   // C++ [over.over]p1:
11419   //   [...] [Note: any redundant set of parentheses surrounding the
11420   //   overloaded function name is ignored (5.1). ]
11421   // C++ [over.over]p1:
11422   //   [...] The overloaded function name can be preceded by the &
11423   //   operator.
11424 
11425   // If we didn't actually find any template-ids, we're done.
11426   if (!ovl->hasExplicitTemplateArgs())
11427     return nullptr;
11428 
11429   TemplateArgumentListInfo ExplicitTemplateArgs;
11430   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11431   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11432 
11433   // Look through all of the overloaded functions, searching for one
11434   // whose type matches exactly.
11435   FunctionDecl *Matched = nullptr;
11436   for (UnresolvedSetIterator I = ovl->decls_begin(),
11437          E = ovl->decls_end(); I != E; ++I) {
11438     // C++0x [temp.arg.explicit]p3:
11439     //   [...] In contexts where deduction is done and fails, or in contexts
11440     //   where deduction is not done, if a template argument list is
11441     //   specified and it, along with any default template arguments,
11442     //   identifies a single function template specialization, then the
11443     //   template-id is an lvalue for the function template specialization.
11444     FunctionTemplateDecl *FunctionTemplate
11445       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11446 
11447     // C++ [over.over]p2:
11448     //   If the name is a function template, template argument deduction is
11449     //   done (14.8.2.2), and if the argument deduction succeeds, the
11450     //   resulting template argument list is used to generate a single
11451     //   function template specialization, which is added to the set of
11452     //   overloaded functions considered.
11453     FunctionDecl *Specialization = nullptr;
11454     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11455     if (TemplateDeductionResult Result
11456           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11457                                     Specialization, Info,
11458                                     /*IsAddressOfFunction*/true)) {
11459       // Make a note of the failed deduction for diagnostics.
11460       // TODO: Actually use the failed-deduction info?
11461       FailedCandidates.addCandidate()
11462           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11463                MakeDeductionFailureInfo(Context, Result, Info));
11464       continue;
11465     }
11466 
11467     assert(Specialization && "no specialization and no error?");
11468 
11469     // Multiple matches; we can't resolve to a single declaration.
11470     if (Matched) {
11471       if (Complain) {
11472         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11473           << ovl->getName();
11474         NoteAllOverloadCandidates(ovl);
11475       }
11476       return nullptr;
11477     }
11478 
11479     Matched = Specialization;
11480     if (FoundResult) *FoundResult = I.getPair();
11481   }
11482 
11483   if (Matched &&
11484       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11485     return nullptr;
11486 
11487   return Matched;
11488 }
11489 
11490 // Resolve and fix an overloaded expression that can be resolved
11491 // because it identifies a single function template specialization.
11492 //
11493 // Last three arguments should only be supplied if Complain = true
11494 //
11495 // Return true if it was logically possible to so resolve the
11496 // expression, regardless of whether or not it succeeded.  Always
11497 // returns true if 'complain' is set.
11498 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11499                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11500                       bool complain, SourceRange OpRangeForComplaining,
11501                                            QualType DestTypeForComplaining,
11502                                             unsigned DiagIDForComplaining) {
11503   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11504 
11505   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11506 
11507   DeclAccessPair found;
11508   ExprResult SingleFunctionExpression;
11509   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11510                            ovl.Expression, /*complain*/ false, &found)) {
11511     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11512       SrcExpr = ExprError();
11513       return true;
11514     }
11515 
11516     // It is only correct to resolve to an instance method if we're
11517     // resolving a form that's permitted to be a pointer to member.
11518     // Otherwise we'll end up making a bound member expression, which
11519     // is illegal in all the contexts we resolve like this.
11520     if (!ovl.HasFormOfMemberPointer &&
11521         isa<CXXMethodDecl>(fn) &&
11522         cast<CXXMethodDecl>(fn)->isInstance()) {
11523       if (!complain) return false;
11524 
11525       Diag(ovl.Expression->getExprLoc(),
11526            diag::err_bound_member_function)
11527         << 0 << ovl.Expression->getSourceRange();
11528 
11529       // TODO: I believe we only end up here if there's a mix of
11530       // static and non-static candidates (otherwise the expression
11531       // would have 'bound member' type, not 'overload' type).
11532       // Ideally we would note which candidate was chosen and why
11533       // the static candidates were rejected.
11534       SrcExpr = ExprError();
11535       return true;
11536     }
11537 
11538     // Fix the expression to refer to 'fn'.
11539     SingleFunctionExpression =
11540         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11541 
11542     // If desired, do function-to-pointer decay.
11543     if (doFunctionPointerConverion) {
11544       SingleFunctionExpression =
11545         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11546       if (SingleFunctionExpression.isInvalid()) {
11547         SrcExpr = ExprError();
11548         return true;
11549       }
11550     }
11551   }
11552 
11553   if (!SingleFunctionExpression.isUsable()) {
11554     if (complain) {
11555       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11556         << ovl.Expression->getName()
11557         << DestTypeForComplaining
11558         << OpRangeForComplaining
11559         << ovl.Expression->getQualifierLoc().getSourceRange();
11560       NoteAllOverloadCandidates(SrcExpr.get());
11561 
11562       SrcExpr = ExprError();
11563       return true;
11564     }
11565 
11566     return false;
11567   }
11568 
11569   SrcExpr = SingleFunctionExpression;
11570   return true;
11571 }
11572 
11573 /// Add a single candidate to the overload set.
11574 static void AddOverloadedCallCandidate(Sema &S,
11575                                        DeclAccessPair FoundDecl,
11576                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11577                                        ArrayRef<Expr *> Args,
11578                                        OverloadCandidateSet &CandidateSet,
11579                                        bool PartialOverloading,
11580                                        bool KnownValid) {
11581   NamedDecl *Callee = FoundDecl.getDecl();
11582   if (isa<UsingShadowDecl>(Callee))
11583     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11584 
11585   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11586     if (ExplicitTemplateArgs) {
11587       assert(!KnownValid && "Explicit template arguments?");
11588       return;
11589     }
11590     // Prevent ill-formed function decls to be added as overload candidates.
11591     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11592       return;
11593 
11594     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11595                            /*SuppressUsedConversions=*/false,
11596                            PartialOverloading);
11597     return;
11598   }
11599 
11600   if (FunctionTemplateDecl *FuncTemplate
11601       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11602     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11603                                    ExplicitTemplateArgs, Args, CandidateSet,
11604                                    /*SuppressUsedConversions=*/false,
11605                                    PartialOverloading);
11606     return;
11607   }
11608 
11609   assert(!KnownValid && "unhandled case in overloaded call candidate");
11610 }
11611 
11612 /// Add the overload candidates named by callee and/or found by argument
11613 /// dependent lookup to the given overload set.
11614 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11615                                        ArrayRef<Expr *> Args,
11616                                        OverloadCandidateSet &CandidateSet,
11617                                        bool PartialOverloading) {
11618 
11619 #ifndef NDEBUG
11620   // Verify that ArgumentDependentLookup is consistent with the rules
11621   // in C++0x [basic.lookup.argdep]p3:
11622   //
11623   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11624   //   and let Y be the lookup set produced by argument dependent
11625   //   lookup (defined as follows). If X contains
11626   //
11627   //     -- a declaration of a class member, or
11628   //
11629   //     -- a block-scope function declaration that is not a
11630   //        using-declaration, or
11631   //
11632   //     -- a declaration that is neither a function or a function
11633   //        template
11634   //
11635   //   then Y is empty.
11636 
11637   if (ULE->requiresADL()) {
11638     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11639            E = ULE->decls_end(); I != E; ++I) {
11640       assert(!(*I)->getDeclContext()->isRecord());
11641       assert(isa<UsingShadowDecl>(*I) ||
11642              !(*I)->getDeclContext()->isFunctionOrMethod());
11643       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11644     }
11645   }
11646 #endif
11647 
11648   // It would be nice to avoid this copy.
11649   TemplateArgumentListInfo TABuffer;
11650   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11651   if (ULE->hasExplicitTemplateArgs()) {
11652     ULE->copyTemplateArgumentsInto(TABuffer);
11653     ExplicitTemplateArgs = &TABuffer;
11654   }
11655 
11656   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11657          E = ULE->decls_end(); I != E; ++I)
11658     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11659                                CandidateSet, PartialOverloading,
11660                                /*KnownValid*/ true);
11661 
11662   if (ULE->requiresADL())
11663     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11664                                          Args, ExplicitTemplateArgs,
11665                                          CandidateSet, PartialOverloading);
11666 }
11667 
11668 /// Determine whether a declaration with the specified name could be moved into
11669 /// a different namespace.
11670 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11671   switch (Name.getCXXOverloadedOperator()) {
11672   case OO_New: case OO_Array_New:
11673   case OO_Delete: case OO_Array_Delete:
11674     return false;
11675 
11676   default:
11677     return true;
11678   }
11679 }
11680 
11681 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11682 /// template, where the non-dependent name was declared after the template
11683 /// was defined. This is common in code written for a compilers which do not
11684 /// correctly implement two-stage name lookup.
11685 ///
11686 /// Returns true if a viable candidate was found and a diagnostic was issued.
11687 static bool
11688 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11689                        const CXXScopeSpec &SS, LookupResult &R,
11690                        OverloadCandidateSet::CandidateSetKind CSK,
11691                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11692                        ArrayRef<Expr *> Args,
11693                        bool *DoDiagnoseEmptyLookup = nullptr) {
11694   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11695     return false;
11696 
11697   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11698     if (DC->isTransparentContext())
11699       continue;
11700 
11701     SemaRef.LookupQualifiedName(R, DC);
11702 
11703     if (!R.empty()) {
11704       R.suppressDiagnostics();
11705 
11706       if (isa<CXXRecordDecl>(DC)) {
11707         // Don't diagnose names we find in classes; we get much better
11708         // diagnostics for these from DiagnoseEmptyLookup.
11709         R.clear();
11710         if (DoDiagnoseEmptyLookup)
11711           *DoDiagnoseEmptyLookup = true;
11712         return false;
11713       }
11714 
11715       OverloadCandidateSet Candidates(FnLoc, CSK);
11716       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11717         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11718                                    ExplicitTemplateArgs, Args,
11719                                    Candidates, false, /*KnownValid*/ false);
11720 
11721       OverloadCandidateSet::iterator Best;
11722       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11723         // No viable functions. Don't bother the user with notes for functions
11724         // which don't work and shouldn't be found anyway.
11725         R.clear();
11726         return false;
11727       }
11728 
11729       // Find the namespaces where ADL would have looked, and suggest
11730       // declaring the function there instead.
11731       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11732       Sema::AssociatedClassSet AssociatedClasses;
11733       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11734                                                  AssociatedNamespaces,
11735                                                  AssociatedClasses);
11736       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11737       if (canBeDeclaredInNamespace(R.getLookupName())) {
11738         DeclContext *Std = SemaRef.getStdNamespace();
11739         for (Sema::AssociatedNamespaceSet::iterator
11740                it = AssociatedNamespaces.begin(),
11741                end = AssociatedNamespaces.end(); it != end; ++it) {
11742           // Never suggest declaring a function within namespace 'std'.
11743           if (Std && Std->Encloses(*it))
11744             continue;
11745 
11746           // Never suggest declaring a function within a namespace with a
11747           // reserved name, like __gnu_cxx.
11748           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11749           if (NS &&
11750               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11751             continue;
11752 
11753           SuggestedNamespaces.insert(*it);
11754         }
11755       }
11756 
11757       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11758         << R.getLookupName();
11759       if (SuggestedNamespaces.empty()) {
11760         SemaRef.Diag(Best->Function->getLocation(),
11761                      diag::note_not_found_by_two_phase_lookup)
11762           << R.getLookupName() << 0;
11763       } else if (SuggestedNamespaces.size() == 1) {
11764         SemaRef.Diag(Best->Function->getLocation(),
11765                      diag::note_not_found_by_two_phase_lookup)
11766           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11767       } else {
11768         // FIXME: It would be useful to list the associated namespaces here,
11769         // but the diagnostics infrastructure doesn't provide a way to produce
11770         // a localized representation of a list of items.
11771         SemaRef.Diag(Best->Function->getLocation(),
11772                      diag::note_not_found_by_two_phase_lookup)
11773           << R.getLookupName() << 2;
11774       }
11775 
11776       // Try to recover by calling this function.
11777       return true;
11778     }
11779 
11780     R.clear();
11781   }
11782 
11783   return false;
11784 }
11785 
11786 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11787 /// template, where the non-dependent operator was declared after the template
11788 /// was defined.
11789 ///
11790 /// Returns true if a viable candidate was found and a diagnostic was issued.
11791 static bool
11792 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11793                                SourceLocation OpLoc,
11794                                ArrayRef<Expr *> Args) {
11795   DeclarationName OpName =
11796     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11797   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11798   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11799                                 OverloadCandidateSet::CSK_Operator,
11800                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11801 }
11802 
11803 namespace {
11804 class BuildRecoveryCallExprRAII {
11805   Sema &SemaRef;
11806 public:
11807   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11808     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11809     SemaRef.IsBuildingRecoveryCallExpr = true;
11810   }
11811 
11812   ~BuildRecoveryCallExprRAII() {
11813     SemaRef.IsBuildingRecoveryCallExpr = false;
11814   }
11815 };
11816 
11817 }
11818 
11819 static std::unique_ptr<CorrectionCandidateCallback>
11820 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11821               bool HasTemplateArgs, bool AllowTypoCorrection) {
11822   if (!AllowTypoCorrection)
11823     return llvm::make_unique<NoTypoCorrectionCCC>();
11824   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11825                                                   HasTemplateArgs, ME);
11826 }
11827 
11828 /// Attempts to recover from a call where no functions were found.
11829 ///
11830 /// Returns true if new candidates were found.
11831 static ExprResult
11832 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11833                       UnresolvedLookupExpr *ULE,
11834                       SourceLocation LParenLoc,
11835                       MutableArrayRef<Expr *> Args,
11836                       SourceLocation RParenLoc,
11837                       bool EmptyLookup, bool AllowTypoCorrection) {
11838   // Do not try to recover if it is already building a recovery call.
11839   // This stops infinite loops for template instantiations like
11840   //
11841   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11842   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11843   //
11844   if (SemaRef.IsBuildingRecoveryCallExpr)
11845     return ExprError();
11846   BuildRecoveryCallExprRAII RCE(SemaRef);
11847 
11848   CXXScopeSpec SS;
11849   SS.Adopt(ULE->getQualifierLoc());
11850   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11851 
11852   TemplateArgumentListInfo TABuffer;
11853   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11854   if (ULE->hasExplicitTemplateArgs()) {
11855     ULE->copyTemplateArgumentsInto(TABuffer);
11856     ExplicitTemplateArgs = &TABuffer;
11857   }
11858 
11859   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11860                  Sema::LookupOrdinaryName);
11861   bool DoDiagnoseEmptyLookup = EmptyLookup;
11862   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11863                               OverloadCandidateSet::CSK_Normal,
11864                               ExplicitTemplateArgs, Args,
11865                               &DoDiagnoseEmptyLookup) &&
11866     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11867         S, SS, R,
11868         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11869                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11870         ExplicitTemplateArgs, Args)))
11871     return ExprError();
11872 
11873   assert(!R.empty() && "lookup results empty despite recovery");
11874 
11875   // If recovery created an ambiguity, just bail out.
11876   if (R.isAmbiguous()) {
11877     R.suppressDiagnostics();
11878     return ExprError();
11879   }
11880 
11881   // Build an implicit member call if appropriate.  Just drop the
11882   // casts and such from the call, we don't really care.
11883   ExprResult NewFn = ExprError();
11884   if ((*R.begin())->isCXXClassMember())
11885     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11886                                                     ExplicitTemplateArgs, S);
11887   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11888     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11889                                         ExplicitTemplateArgs);
11890   else
11891     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11892 
11893   if (NewFn.isInvalid())
11894     return ExprError();
11895 
11896   // This shouldn't cause an infinite loop because we're giving it
11897   // an expression with viable lookup results, which should never
11898   // end up here.
11899   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11900                                MultiExprArg(Args.data(), Args.size()),
11901                                RParenLoc);
11902 }
11903 
11904 /// Constructs and populates an OverloadedCandidateSet from
11905 /// the given function.
11906 /// \returns true when an the ExprResult output parameter has been set.
11907 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11908                                   UnresolvedLookupExpr *ULE,
11909                                   MultiExprArg Args,
11910                                   SourceLocation RParenLoc,
11911                                   OverloadCandidateSet *CandidateSet,
11912                                   ExprResult *Result) {
11913 #ifndef NDEBUG
11914   if (ULE->requiresADL()) {
11915     // To do ADL, we must have found an unqualified name.
11916     assert(!ULE->getQualifier() && "qualified name with ADL");
11917 
11918     // We don't perform ADL for implicit declarations of builtins.
11919     // Verify that this was correctly set up.
11920     FunctionDecl *F;
11921     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11922         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11923         F->getBuiltinID() && F->isImplicit())
11924       llvm_unreachable("performing ADL for builtin");
11925 
11926     // We don't perform ADL in C.
11927     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11928   }
11929 #endif
11930 
11931   UnbridgedCastsSet UnbridgedCasts;
11932   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11933     *Result = ExprError();
11934     return true;
11935   }
11936 
11937   // Add the functions denoted by the callee to the set of candidate
11938   // functions, including those from argument-dependent lookup.
11939   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11940 
11941   if (getLangOpts().MSVCCompat &&
11942       CurContext->isDependentContext() && !isSFINAEContext() &&
11943       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11944 
11945     OverloadCandidateSet::iterator Best;
11946     if (CandidateSet->empty() ||
11947         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11948             OR_No_Viable_Function) {
11949       // In Microsoft mode, if we are inside a template class member function then
11950       // create a type dependent CallExpr. The goal is to postpone name lookup
11951       // to instantiation time to be able to search into type dependent base
11952       // classes.
11953       CallExpr *CE = new (Context) CallExpr(
11954           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11955       CE->setTypeDependent(true);
11956       CE->setValueDependent(true);
11957       CE->setInstantiationDependent(true);
11958       *Result = CE;
11959       return true;
11960     }
11961   }
11962 
11963   if (CandidateSet->empty())
11964     return false;
11965 
11966   UnbridgedCasts.restore();
11967   return false;
11968 }
11969 
11970 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11971 /// the completed call expression. If overload resolution fails, emits
11972 /// diagnostics and returns ExprError()
11973 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11974                                            UnresolvedLookupExpr *ULE,
11975                                            SourceLocation LParenLoc,
11976                                            MultiExprArg Args,
11977                                            SourceLocation RParenLoc,
11978                                            Expr *ExecConfig,
11979                                            OverloadCandidateSet *CandidateSet,
11980                                            OverloadCandidateSet::iterator *Best,
11981                                            OverloadingResult OverloadResult,
11982                                            bool AllowTypoCorrection) {
11983   if (CandidateSet->empty())
11984     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11985                                  RParenLoc, /*EmptyLookup=*/true,
11986                                  AllowTypoCorrection);
11987 
11988   switch (OverloadResult) {
11989   case OR_Success: {
11990     FunctionDecl *FDecl = (*Best)->Function;
11991     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11992     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11993       return ExprError();
11994     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11995     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11996                                          ExecConfig);
11997   }
11998 
11999   case OR_No_Viable_Function: {
12000     // Try to recover by looking for viable functions which the user might
12001     // have meant to call.
12002     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12003                                                 Args, RParenLoc,
12004                                                 /*EmptyLookup=*/false,
12005                                                 AllowTypoCorrection);
12006     if (!Recovery.isInvalid())
12007       return Recovery;
12008 
12009     // If the user passes in a function that we can't take the address of, we
12010     // generally end up emitting really bad error messages. Here, we attempt to
12011     // emit better ones.
12012     for (const Expr *Arg : Args) {
12013       if (!Arg->getType()->isFunctionType())
12014         continue;
12015       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12016         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12017         if (FD &&
12018             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12019                                                        Arg->getExprLoc()))
12020           return ExprError();
12021       }
12022     }
12023 
12024     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
12025         << ULE->getName() << Fn->getSourceRange();
12026     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12027     break;
12028   }
12029 
12030   case OR_Ambiguous:
12031     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
12032       << ULE->getName() << Fn->getSourceRange();
12033     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12034     break;
12035 
12036   case OR_Deleted: {
12037     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
12038       << (*Best)->Function->isDeleted()
12039       << ULE->getName()
12040       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12041       << Fn->getSourceRange();
12042     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12043 
12044     // We emitted an error for the unavailable/deleted function call but keep
12045     // the call in the AST.
12046     FunctionDecl *FDecl = (*Best)->Function;
12047     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12048     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12049                                          ExecConfig);
12050   }
12051   }
12052 
12053   // Overload resolution failed.
12054   return ExprError();
12055 }
12056 
12057 static void markUnaddressableCandidatesUnviable(Sema &S,
12058                                                 OverloadCandidateSet &CS) {
12059   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12060     if (I->Viable &&
12061         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12062       I->Viable = false;
12063       I->FailureKind = ovl_fail_addr_not_available;
12064     }
12065   }
12066 }
12067 
12068 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12069 /// (which eventually refers to the declaration Func) and the call
12070 /// arguments Args/NumArgs, attempt to resolve the function call down
12071 /// to a specific function. If overload resolution succeeds, returns
12072 /// the call expression produced by overload resolution.
12073 /// Otherwise, emits diagnostics and returns ExprError.
12074 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12075                                          UnresolvedLookupExpr *ULE,
12076                                          SourceLocation LParenLoc,
12077                                          MultiExprArg Args,
12078                                          SourceLocation RParenLoc,
12079                                          Expr *ExecConfig,
12080                                          bool AllowTypoCorrection,
12081                                          bool CalleesAddressIsTaken) {
12082   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12083                                     OverloadCandidateSet::CSK_Normal);
12084   ExprResult result;
12085 
12086   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12087                              &result))
12088     return result;
12089 
12090   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12091   // functions that aren't addressible are considered unviable.
12092   if (CalleesAddressIsTaken)
12093     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12094 
12095   OverloadCandidateSet::iterator Best;
12096   OverloadingResult OverloadResult =
12097       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12098 
12099   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12100                                   RParenLoc, ExecConfig, &CandidateSet,
12101                                   &Best, OverloadResult,
12102                                   AllowTypoCorrection);
12103 }
12104 
12105 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12106   return Functions.size() > 1 ||
12107     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12108 }
12109 
12110 /// Create a unary operation that may resolve to an overloaded
12111 /// operator.
12112 ///
12113 /// \param OpLoc The location of the operator itself (e.g., '*').
12114 ///
12115 /// \param Opc The UnaryOperatorKind that describes this operator.
12116 ///
12117 /// \param Fns The set of non-member functions that will be
12118 /// considered by overload resolution. The caller needs to build this
12119 /// set based on the context using, e.g.,
12120 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12121 /// set should not contain any member functions; those will be added
12122 /// by CreateOverloadedUnaryOp().
12123 ///
12124 /// \param Input The input argument.
12125 ExprResult
12126 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12127                               const UnresolvedSetImpl &Fns,
12128                               Expr *Input, bool PerformADL) {
12129   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12130   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12131   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12132   // TODO: provide better source location info.
12133   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12134 
12135   if (checkPlaceholderForOverload(*this, Input))
12136     return ExprError();
12137 
12138   Expr *Args[2] = { Input, nullptr };
12139   unsigned NumArgs = 1;
12140 
12141   // For post-increment and post-decrement, add the implicit '0' as
12142   // the second argument, so that we know this is a post-increment or
12143   // post-decrement.
12144   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12145     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12146     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12147                                      SourceLocation());
12148     NumArgs = 2;
12149   }
12150 
12151   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12152 
12153   if (Input->isTypeDependent()) {
12154     if (Fns.empty())
12155       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12156                                          VK_RValue, OK_Ordinary, OpLoc, false);
12157 
12158     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12159     UnresolvedLookupExpr *Fn
12160       = UnresolvedLookupExpr::Create(Context, NamingClass,
12161                                      NestedNameSpecifierLoc(), OpNameInfo,
12162                                      /*ADL*/ true, IsOverloaded(Fns),
12163                                      Fns.begin(), Fns.end());
12164     return new (Context)
12165         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12166                             VK_RValue, OpLoc, FPOptions());
12167   }
12168 
12169   // Build an empty overload set.
12170   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12171 
12172   // Add the candidates from the given function set.
12173   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12174 
12175   // Add operator candidates that are member functions.
12176   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12177 
12178   // Add candidates from ADL.
12179   if (PerformADL) {
12180     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12181                                          /*ExplicitTemplateArgs*/nullptr,
12182                                          CandidateSet);
12183   }
12184 
12185   // Add builtin operator candidates.
12186   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12187 
12188   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12189 
12190   // Perform overload resolution.
12191   OverloadCandidateSet::iterator Best;
12192   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12193   case OR_Success: {
12194     // We found a built-in operator or an overloaded operator.
12195     FunctionDecl *FnDecl = Best->Function;
12196 
12197     if (FnDecl) {
12198       Expr *Base = nullptr;
12199       // We matched an overloaded operator. Build a call to that
12200       // operator.
12201 
12202       // Convert the arguments.
12203       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12204         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12205 
12206         ExprResult InputRes =
12207           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12208                                               Best->FoundDecl, Method);
12209         if (InputRes.isInvalid())
12210           return ExprError();
12211         Base = Input = InputRes.get();
12212       } else {
12213         // Convert the arguments.
12214         ExprResult InputInit
12215           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12216                                                       Context,
12217                                                       FnDecl->getParamDecl(0)),
12218                                       SourceLocation(),
12219                                       Input);
12220         if (InputInit.isInvalid())
12221           return ExprError();
12222         Input = InputInit.get();
12223       }
12224 
12225       // Build the actual expression node.
12226       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12227                                                 Base, HadMultipleCandidates,
12228                                                 OpLoc);
12229       if (FnExpr.isInvalid())
12230         return ExprError();
12231 
12232       // Determine the result type.
12233       QualType ResultTy = FnDecl->getReturnType();
12234       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12235       ResultTy = ResultTy.getNonLValueExprType(Context);
12236 
12237       Args[0] = Input;
12238       CallExpr *TheCall =
12239         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12240                                           ResultTy, VK, OpLoc, FPOptions());
12241 
12242       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12243         return ExprError();
12244 
12245       if (CheckFunctionCall(FnDecl, TheCall,
12246                             FnDecl->getType()->castAs<FunctionProtoType>()))
12247         return ExprError();
12248 
12249       return MaybeBindToTemporary(TheCall);
12250     } else {
12251       // We matched a built-in operator. Convert the arguments, then
12252       // break out so that we will build the appropriate built-in
12253       // operator node.
12254       ExprResult InputRes = PerformImplicitConversion(
12255           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12256           CCK_ForBuiltinOverloadedOp);
12257       if (InputRes.isInvalid())
12258         return ExprError();
12259       Input = InputRes.get();
12260       break;
12261     }
12262   }
12263 
12264   case OR_No_Viable_Function:
12265     // This is an erroneous use of an operator which can be overloaded by
12266     // a non-member function. Check for non-member operators which were
12267     // defined too late to be candidates.
12268     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12269       // FIXME: Recover by calling the found function.
12270       return ExprError();
12271 
12272     // No viable function; fall through to handling this as a
12273     // built-in operator, which will produce an error message for us.
12274     break;
12275 
12276   case OR_Ambiguous:
12277     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12278         << UnaryOperator::getOpcodeStr(Opc)
12279         << Input->getType()
12280         << Input->getSourceRange();
12281     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12282                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12283     return ExprError();
12284 
12285   case OR_Deleted:
12286     Diag(OpLoc, diag::err_ovl_deleted_oper)
12287       << Best->Function->isDeleted()
12288       << UnaryOperator::getOpcodeStr(Opc)
12289       << getDeletedOrUnavailableSuffix(Best->Function)
12290       << Input->getSourceRange();
12291     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12292                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12293     return ExprError();
12294   }
12295 
12296   // Either we found no viable overloaded operator or we matched a
12297   // built-in operator. In either case, fall through to trying to
12298   // build a built-in operation.
12299   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12300 }
12301 
12302 /// Create a binary operation that may resolve to an overloaded
12303 /// operator.
12304 ///
12305 /// \param OpLoc The location of the operator itself (e.g., '+').
12306 ///
12307 /// \param Opc The BinaryOperatorKind that describes this operator.
12308 ///
12309 /// \param Fns The set of non-member functions that will be
12310 /// considered by overload resolution. The caller needs to build this
12311 /// set based on the context using, e.g.,
12312 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12313 /// set should not contain any member functions; those will be added
12314 /// by CreateOverloadedBinOp().
12315 ///
12316 /// \param LHS Left-hand argument.
12317 /// \param RHS Right-hand argument.
12318 ExprResult
12319 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12320                             BinaryOperatorKind Opc,
12321                             const UnresolvedSetImpl &Fns,
12322                             Expr *LHS, Expr *RHS, bool PerformADL) {
12323   Expr *Args[2] = { LHS, RHS };
12324   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12325 
12326   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12327   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12328 
12329   // If either side is type-dependent, create an appropriate dependent
12330   // expression.
12331   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12332     if (Fns.empty()) {
12333       // If there are no functions to store, just build a dependent
12334       // BinaryOperator or CompoundAssignment.
12335       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12336         return new (Context) BinaryOperator(
12337             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12338             OpLoc, FPFeatures);
12339 
12340       return new (Context) CompoundAssignOperator(
12341           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12342           Context.DependentTy, Context.DependentTy, OpLoc,
12343           FPFeatures);
12344     }
12345 
12346     // FIXME: save results of ADL from here?
12347     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12348     // TODO: provide better source location info in DNLoc component.
12349     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12350     UnresolvedLookupExpr *Fn
12351       = UnresolvedLookupExpr::Create(Context, NamingClass,
12352                                      NestedNameSpecifierLoc(), OpNameInfo,
12353                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12354                                      Fns.begin(), Fns.end());
12355     return new (Context)
12356         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12357                             VK_RValue, OpLoc, FPFeatures);
12358   }
12359 
12360   // Always do placeholder-like conversions on the RHS.
12361   if (checkPlaceholderForOverload(*this, Args[1]))
12362     return ExprError();
12363 
12364   // Do placeholder-like conversion on the LHS; note that we should
12365   // not get here with a PseudoObject LHS.
12366   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12367   if (checkPlaceholderForOverload(*this, Args[0]))
12368     return ExprError();
12369 
12370   // If this is the assignment operator, we only perform overload resolution
12371   // if the left-hand side is a class or enumeration type. This is actually
12372   // a hack. The standard requires that we do overload resolution between the
12373   // various built-in candidates, but as DR507 points out, this can lead to
12374   // problems. So we do it this way, which pretty much follows what GCC does.
12375   // Note that we go the traditional code path for compound assignment forms.
12376   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12377     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12378 
12379   // If this is the .* operator, which is not overloadable, just
12380   // create a built-in binary operator.
12381   if (Opc == BO_PtrMemD)
12382     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12383 
12384   // Build an empty overload set.
12385   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12386 
12387   // Add the candidates from the given function set.
12388   AddFunctionCandidates(Fns, Args, CandidateSet);
12389 
12390   // Add operator candidates that are member functions.
12391   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12392 
12393   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12394   // performed for an assignment operator (nor for operator[] nor operator->,
12395   // which don't get here).
12396   if (Opc != BO_Assign && PerformADL)
12397     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12398                                          /*ExplicitTemplateArgs*/ nullptr,
12399                                          CandidateSet);
12400 
12401   // Add builtin operator candidates.
12402   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12403 
12404   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12405 
12406   // Perform overload resolution.
12407   OverloadCandidateSet::iterator Best;
12408   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12409     case OR_Success: {
12410       // We found a built-in operator or an overloaded operator.
12411       FunctionDecl *FnDecl = Best->Function;
12412 
12413       if (FnDecl) {
12414         Expr *Base = nullptr;
12415         // We matched an overloaded operator. Build a call to that
12416         // operator.
12417 
12418         // Convert the arguments.
12419         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12420           // Best->Access is only meaningful for class members.
12421           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12422 
12423           ExprResult Arg1 =
12424             PerformCopyInitialization(
12425               InitializedEntity::InitializeParameter(Context,
12426                                                      FnDecl->getParamDecl(0)),
12427               SourceLocation(), Args[1]);
12428           if (Arg1.isInvalid())
12429             return ExprError();
12430 
12431           ExprResult Arg0 =
12432             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12433                                                 Best->FoundDecl, Method);
12434           if (Arg0.isInvalid())
12435             return ExprError();
12436           Base = Args[0] = Arg0.getAs<Expr>();
12437           Args[1] = RHS = Arg1.getAs<Expr>();
12438         } else {
12439           // Convert the arguments.
12440           ExprResult Arg0 = PerformCopyInitialization(
12441             InitializedEntity::InitializeParameter(Context,
12442                                                    FnDecl->getParamDecl(0)),
12443             SourceLocation(), Args[0]);
12444           if (Arg0.isInvalid())
12445             return ExprError();
12446 
12447           ExprResult Arg1 =
12448             PerformCopyInitialization(
12449               InitializedEntity::InitializeParameter(Context,
12450                                                      FnDecl->getParamDecl(1)),
12451               SourceLocation(), Args[1]);
12452           if (Arg1.isInvalid())
12453             return ExprError();
12454           Args[0] = LHS = Arg0.getAs<Expr>();
12455           Args[1] = RHS = Arg1.getAs<Expr>();
12456         }
12457 
12458         // Build the actual expression node.
12459         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12460                                                   Best->FoundDecl, Base,
12461                                                   HadMultipleCandidates, OpLoc);
12462         if (FnExpr.isInvalid())
12463           return ExprError();
12464 
12465         // Determine the result type.
12466         QualType ResultTy = FnDecl->getReturnType();
12467         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12468         ResultTy = ResultTy.getNonLValueExprType(Context);
12469 
12470         CXXOperatorCallExpr *TheCall =
12471           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12472                                             Args, ResultTy, VK, OpLoc,
12473                                             FPFeatures);
12474 
12475         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12476                                 FnDecl))
12477           return ExprError();
12478 
12479         ArrayRef<const Expr *> ArgsArray(Args, 2);
12480         const Expr *ImplicitThis = nullptr;
12481         // Cut off the implicit 'this'.
12482         if (isa<CXXMethodDecl>(FnDecl)) {
12483           ImplicitThis = ArgsArray[0];
12484           ArgsArray = ArgsArray.slice(1);
12485         }
12486 
12487         // Check for a self move.
12488         if (Op == OO_Equal)
12489           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12490 
12491         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12492                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12493                   VariadicDoesNotApply);
12494 
12495         return MaybeBindToTemporary(TheCall);
12496       } else {
12497         // We matched a built-in operator. Convert the arguments, then
12498         // break out so that we will build the appropriate built-in
12499         // operator node.
12500         ExprResult ArgsRes0 = PerformImplicitConversion(
12501             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12502             AA_Passing, CCK_ForBuiltinOverloadedOp);
12503         if (ArgsRes0.isInvalid())
12504           return ExprError();
12505         Args[0] = ArgsRes0.get();
12506 
12507         ExprResult ArgsRes1 = PerformImplicitConversion(
12508             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12509             AA_Passing, CCK_ForBuiltinOverloadedOp);
12510         if (ArgsRes1.isInvalid())
12511           return ExprError();
12512         Args[1] = ArgsRes1.get();
12513         break;
12514       }
12515     }
12516 
12517     case OR_No_Viable_Function: {
12518       // C++ [over.match.oper]p9:
12519       //   If the operator is the operator , [...] and there are no
12520       //   viable functions, then the operator is assumed to be the
12521       //   built-in operator and interpreted according to clause 5.
12522       if (Opc == BO_Comma)
12523         break;
12524 
12525       // For class as left operand for assignment or compound assignment
12526       // operator do not fall through to handling in built-in, but report that
12527       // no overloaded assignment operator found
12528       ExprResult Result = ExprError();
12529       if (Args[0]->getType()->isRecordType() &&
12530           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12531         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12532              << BinaryOperator::getOpcodeStr(Opc)
12533              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12534         if (Args[0]->getType()->isIncompleteType()) {
12535           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12536             << Args[0]->getType()
12537             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12538         }
12539       } else {
12540         // This is an erroneous use of an operator which can be overloaded by
12541         // a non-member function. Check for non-member operators which were
12542         // defined too late to be candidates.
12543         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12544           // FIXME: Recover by calling the found function.
12545           return ExprError();
12546 
12547         // No viable function; try to create a built-in operation, which will
12548         // produce an error. Then, show the non-viable candidates.
12549         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12550       }
12551       assert(Result.isInvalid() &&
12552              "C++ binary operator overloading is missing candidates!");
12553       if (Result.isInvalid())
12554         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12555                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12556       return Result;
12557     }
12558 
12559     case OR_Ambiguous:
12560       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12561           << BinaryOperator::getOpcodeStr(Opc)
12562           << Args[0]->getType() << Args[1]->getType()
12563           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12564       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12565                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12566       return ExprError();
12567 
12568     case OR_Deleted:
12569       if (isImplicitlyDeleted(Best->Function)) {
12570         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12571         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12572           << Context.getRecordType(Method->getParent())
12573           << getSpecialMember(Method);
12574 
12575         // The user probably meant to call this special member. Just
12576         // explain why it's deleted.
12577         NoteDeletedFunction(Method);
12578         return ExprError();
12579       } else {
12580         Diag(OpLoc, diag::err_ovl_deleted_oper)
12581           << Best->Function->isDeleted()
12582           << BinaryOperator::getOpcodeStr(Opc)
12583           << getDeletedOrUnavailableSuffix(Best->Function)
12584           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12585       }
12586       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12587                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12588       return ExprError();
12589   }
12590 
12591   // We matched a built-in operator; build it.
12592   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12593 }
12594 
12595 ExprResult
12596 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12597                                          SourceLocation RLoc,
12598                                          Expr *Base, Expr *Idx) {
12599   Expr *Args[2] = { Base, Idx };
12600   DeclarationName OpName =
12601       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12602 
12603   // If either side is type-dependent, create an appropriate dependent
12604   // expression.
12605   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12606 
12607     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12608     // CHECKME: no 'operator' keyword?
12609     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12610     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12611     UnresolvedLookupExpr *Fn
12612       = UnresolvedLookupExpr::Create(Context, NamingClass,
12613                                      NestedNameSpecifierLoc(), OpNameInfo,
12614                                      /*ADL*/ true, /*Overloaded*/ false,
12615                                      UnresolvedSetIterator(),
12616                                      UnresolvedSetIterator());
12617     // Can't add any actual overloads yet
12618 
12619     return new (Context)
12620         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12621                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12622   }
12623 
12624   // Handle placeholders on both operands.
12625   if (checkPlaceholderForOverload(*this, Args[0]))
12626     return ExprError();
12627   if (checkPlaceholderForOverload(*this, Args[1]))
12628     return ExprError();
12629 
12630   // Build an empty overload set.
12631   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12632 
12633   // Subscript can only be overloaded as a member function.
12634 
12635   // Add operator candidates that are member functions.
12636   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12637 
12638   // Add builtin operator candidates.
12639   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12640 
12641   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12642 
12643   // Perform overload resolution.
12644   OverloadCandidateSet::iterator Best;
12645   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12646     case OR_Success: {
12647       // We found a built-in operator or an overloaded operator.
12648       FunctionDecl *FnDecl = Best->Function;
12649 
12650       if (FnDecl) {
12651         // We matched an overloaded operator. Build a call to that
12652         // operator.
12653 
12654         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12655 
12656         // Convert the arguments.
12657         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12658         ExprResult Arg0 =
12659           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12660                                               Best->FoundDecl, Method);
12661         if (Arg0.isInvalid())
12662           return ExprError();
12663         Args[0] = Arg0.get();
12664 
12665         // Convert the arguments.
12666         ExprResult InputInit
12667           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12668                                                       Context,
12669                                                       FnDecl->getParamDecl(0)),
12670                                       SourceLocation(),
12671                                       Args[1]);
12672         if (InputInit.isInvalid())
12673           return ExprError();
12674 
12675         Args[1] = InputInit.getAs<Expr>();
12676 
12677         // Build the actual expression node.
12678         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12679         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12680         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12681                                                   Best->FoundDecl,
12682                                                   Base,
12683                                                   HadMultipleCandidates,
12684                                                   OpLocInfo.getLoc(),
12685                                                   OpLocInfo.getInfo());
12686         if (FnExpr.isInvalid())
12687           return ExprError();
12688 
12689         // Determine the result type
12690         QualType ResultTy = FnDecl->getReturnType();
12691         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12692         ResultTy = ResultTy.getNonLValueExprType(Context);
12693 
12694         CXXOperatorCallExpr *TheCall =
12695           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12696                                             FnExpr.get(), Args,
12697                                             ResultTy, VK, RLoc,
12698                                             FPOptions());
12699 
12700         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12701           return ExprError();
12702 
12703         if (CheckFunctionCall(Method, TheCall,
12704                               Method->getType()->castAs<FunctionProtoType>()))
12705           return ExprError();
12706 
12707         return MaybeBindToTemporary(TheCall);
12708       } else {
12709         // We matched a built-in operator. Convert the arguments, then
12710         // break out so that we will build the appropriate built-in
12711         // operator node.
12712         ExprResult ArgsRes0 = PerformImplicitConversion(
12713             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12714             AA_Passing, CCK_ForBuiltinOverloadedOp);
12715         if (ArgsRes0.isInvalid())
12716           return ExprError();
12717         Args[0] = ArgsRes0.get();
12718 
12719         ExprResult ArgsRes1 = PerformImplicitConversion(
12720             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12721             AA_Passing, CCK_ForBuiltinOverloadedOp);
12722         if (ArgsRes1.isInvalid())
12723           return ExprError();
12724         Args[1] = ArgsRes1.get();
12725 
12726         break;
12727       }
12728     }
12729 
12730     case OR_No_Viable_Function: {
12731       if (CandidateSet.empty())
12732         Diag(LLoc, diag::err_ovl_no_oper)
12733           << Args[0]->getType() << /*subscript*/ 0
12734           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12735       else
12736         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12737           << Args[0]->getType()
12738           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12739       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12740                                   "[]", LLoc);
12741       return ExprError();
12742     }
12743 
12744     case OR_Ambiguous:
12745       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12746           << "[]"
12747           << Args[0]->getType() << Args[1]->getType()
12748           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12749       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12750                                   "[]", LLoc);
12751       return ExprError();
12752 
12753     case OR_Deleted:
12754       Diag(LLoc, diag::err_ovl_deleted_oper)
12755         << Best->Function->isDeleted() << "[]"
12756         << getDeletedOrUnavailableSuffix(Best->Function)
12757         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12758       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12759                                   "[]", LLoc);
12760       return ExprError();
12761     }
12762 
12763   // We matched a built-in operator; build it.
12764   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12765 }
12766 
12767 /// BuildCallToMemberFunction - Build a call to a member
12768 /// function. MemExpr is the expression that refers to the member
12769 /// function (and includes the object parameter), Args/NumArgs are the
12770 /// arguments to the function call (not including the object
12771 /// parameter). The caller needs to validate that the member
12772 /// expression refers to a non-static member function or an overloaded
12773 /// member function.
12774 ExprResult
12775 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12776                                 SourceLocation LParenLoc,
12777                                 MultiExprArg Args,
12778                                 SourceLocation RParenLoc) {
12779   assert(MemExprE->getType() == Context.BoundMemberTy ||
12780          MemExprE->getType() == Context.OverloadTy);
12781 
12782   // Dig out the member expression. This holds both the object
12783   // argument and the member function we're referring to.
12784   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12785 
12786   // Determine whether this is a call to a pointer-to-member function.
12787   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12788     assert(op->getType() == Context.BoundMemberTy);
12789     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12790 
12791     QualType fnType =
12792       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12793 
12794     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12795     QualType resultType = proto->getCallResultType(Context);
12796     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12797 
12798     // Check that the object type isn't more qualified than the
12799     // member function we're calling.
12800     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12801 
12802     QualType objectType = op->getLHS()->getType();
12803     if (op->getOpcode() == BO_PtrMemI)
12804       objectType = objectType->castAs<PointerType>()->getPointeeType();
12805     Qualifiers objectQuals = objectType.getQualifiers();
12806 
12807     Qualifiers difference = objectQuals - funcQuals;
12808     difference.removeObjCGCAttr();
12809     difference.removeAddressSpace();
12810     if (difference) {
12811       std::string qualsString = difference.getAsString();
12812       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12813         << fnType.getUnqualifiedType()
12814         << qualsString
12815         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12816     }
12817 
12818     CXXMemberCallExpr *call
12819       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12820                                         resultType, valueKind, RParenLoc);
12821 
12822     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12823                             call, nullptr))
12824       return ExprError();
12825 
12826     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12827       return ExprError();
12828 
12829     if (CheckOtherCall(call, proto))
12830       return ExprError();
12831 
12832     return MaybeBindToTemporary(call);
12833   }
12834 
12835   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12836     return new (Context)
12837         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12838 
12839   UnbridgedCastsSet UnbridgedCasts;
12840   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12841     return ExprError();
12842 
12843   MemberExpr *MemExpr;
12844   CXXMethodDecl *Method = nullptr;
12845   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12846   NestedNameSpecifier *Qualifier = nullptr;
12847   if (isa<MemberExpr>(NakedMemExpr)) {
12848     MemExpr = cast<MemberExpr>(NakedMemExpr);
12849     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12850     FoundDecl = MemExpr->getFoundDecl();
12851     Qualifier = MemExpr->getQualifier();
12852     UnbridgedCasts.restore();
12853   } else {
12854     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12855     Qualifier = UnresExpr->getQualifier();
12856 
12857     QualType ObjectType = UnresExpr->getBaseType();
12858     Expr::Classification ObjectClassification
12859       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12860                             : UnresExpr->getBase()->Classify(Context);
12861 
12862     // Add overload candidates
12863     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12864                                       OverloadCandidateSet::CSK_Normal);
12865 
12866     // FIXME: avoid copy.
12867     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12868     if (UnresExpr->hasExplicitTemplateArgs()) {
12869       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12870       TemplateArgs = &TemplateArgsBuffer;
12871     }
12872 
12873     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12874            E = UnresExpr->decls_end(); I != E; ++I) {
12875 
12876       NamedDecl *Func = *I;
12877       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12878       if (isa<UsingShadowDecl>(Func))
12879         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12880 
12881 
12882       // Microsoft supports direct constructor calls.
12883       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12884         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12885                              Args, CandidateSet);
12886       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12887         // If explicit template arguments were provided, we can't call a
12888         // non-template member function.
12889         if (TemplateArgs)
12890           continue;
12891 
12892         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12893                            ObjectClassification, Args, CandidateSet,
12894                            /*SuppressUserConversions=*/false);
12895       } else {
12896         AddMethodTemplateCandidate(
12897             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12898             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12899             /*SuppressUsedConversions=*/false);
12900       }
12901     }
12902 
12903     DeclarationName DeclName = UnresExpr->getMemberName();
12904 
12905     UnbridgedCasts.restore();
12906 
12907     OverloadCandidateSet::iterator Best;
12908     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12909                                             Best)) {
12910     case OR_Success:
12911       Method = cast<CXXMethodDecl>(Best->Function);
12912       FoundDecl = Best->FoundDecl;
12913       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12914       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12915         return ExprError();
12916       // If FoundDecl is different from Method (such as if one is a template
12917       // and the other a specialization), make sure DiagnoseUseOfDecl is
12918       // called on both.
12919       // FIXME: This would be more comprehensively addressed by modifying
12920       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12921       // being used.
12922       if (Method != FoundDecl.getDecl() &&
12923                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12924         return ExprError();
12925       break;
12926 
12927     case OR_No_Viable_Function:
12928       Diag(UnresExpr->getMemberLoc(),
12929            diag::err_ovl_no_viable_member_function_in_call)
12930         << DeclName << MemExprE->getSourceRange();
12931       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12932       // FIXME: Leaking incoming expressions!
12933       return ExprError();
12934 
12935     case OR_Ambiguous:
12936       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12937         << DeclName << MemExprE->getSourceRange();
12938       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12939       // FIXME: Leaking incoming expressions!
12940       return ExprError();
12941 
12942     case OR_Deleted:
12943       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12944         << Best->Function->isDeleted()
12945         << DeclName
12946         << getDeletedOrUnavailableSuffix(Best->Function)
12947         << MemExprE->getSourceRange();
12948       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12949       // FIXME: Leaking incoming expressions!
12950       return ExprError();
12951     }
12952 
12953     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12954 
12955     // If overload resolution picked a static member, build a
12956     // non-member call based on that function.
12957     if (Method->isStatic()) {
12958       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12959                                    RParenLoc);
12960     }
12961 
12962     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12963   }
12964 
12965   QualType ResultType = Method->getReturnType();
12966   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12967   ResultType = ResultType.getNonLValueExprType(Context);
12968 
12969   assert(Method && "Member call to something that isn't a method?");
12970   CXXMemberCallExpr *TheCall =
12971     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12972                                     ResultType, VK, RParenLoc);
12973 
12974   // Check for a valid return type.
12975   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12976                           TheCall, Method))
12977     return ExprError();
12978 
12979   // Convert the object argument (for a non-static member function call).
12980   // We only need to do this if there was actually an overload; otherwise
12981   // it was done at lookup.
12982   if (!Method->isStatic()) {
12983     ExprResult ObjectArg =
12984       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12985                                           FoundDecl, Method);
12986     if (ObjectArg.isInvalid())
12987       return ExprError();
12988     MemExpr->setBase(ObjectArg.get());
12989   }
12990 
12991   // Convert the rest of the arguments
12992   const FunctionProtoType *Proto =
12993     Method->getType()->getAs<FunctionProtoType>();
12994   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12995                               RParenLoc))
12996     return ExprError();
12997 
12998   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12999 
13000   if (CheckFunctionCall(Method, TheCall, Proto))
13001     return ExprError();
13002 
13003   // In the case the method to call was not selected by the overloading
13004   // resolution process, we still need to handle the enable_if attribute. Do
13005   // that here, so it will not hide previous -- and more relevant -- errors.
13006   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13007     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13008       Diag(MemE->getMemberLoc(),
13009            diag::err_ovl_no_viable_member_function_in_call)
13010           << Method << Method->getSourceRange();
13011       Diag(Method->getLocation(),
13012            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13013           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13014       return ExprError();
13015     }
13016   }
13017 
13018   if ((isa<CXXConstructorDecl>(CurContext) ||
13019        isa<CXXDestructorDecl>(CurContext)) &&
13020       TheCall->getMethodDecl()->isPure()) {
13021     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13022 
13023     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13024         MemExpr->performsVirtualDispatch(getLangOpts())) {
13025       Diag(MemExpr->getLocStart(),
13026            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13027         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13028         << MD->getParent()->getDeclName();
13029 
13030       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
13031       if (getLangOpts().AppleKext)
13032         Diag(MemExpr->getLocStart(),
13033              diag::note_pure_qualified_call_kext)
13034              << MD->getParent()->getDeclName()
13035              << MD->getDeclName();
13036     }
13037   }
13038 
13039   if (CXXDestructorDecl *DD =
13040           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13041     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13042     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13043     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
13044                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13045                          MemExpr->getMemberLoc());
13046   }
13047 
13048   return MaybeBindToTemporary(TheCall);
13049 }
13050 
13051 /// BuildCallToObjectOfClassType - Build a call to an object of class
13052 /// type (C++ [over.call.object]), which can end up invoking an
13053 /// overloaded function call operator (@c operator()) or performing a
13054 /// user-defined conversion on the object argument.
13055 ExprResult
13056 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13057                                    SourceLocation LParenLoc,
13058                                    MultiExprArg Args,
13059                                    SourceLocation RParenLoc) {
13060   if (checkPlaceholderForOverload(*this, Obj))
13061     return ExprError();
13062   ExprResult Object = Obj;
13063 
13064   UnbridgedCastsSet UnbridgedCasts;
13065   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13066     return ExprError();
13067 
13068   assert(Object.get()->getType()->isRecordType() &&
13069          "Requires object type argument");
13070   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13071 
13072   // C++ [over.call.object]p1:
13073   //  If the primary-expression E in the function call syntax
13074   //  evaluates to a class object of type "cv T", then the set of
13075   //  candidate functions includes at least the function call
13076   //  operators of T. The function call operators of T are obtained by
13077   //  ordinary lookup of the name operator() in the context of
13078   //  (E).operator().
13079   OverloadCandidateSet CandidateSet(LParenLoc,
13080                                     OverloadCandidateSet::CSK_Operator);
13081   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13082 
13083   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13084                           diag::err_incomplete_object_call, Object.get()))
13085     return true;
13086 
13087   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13088   LookupQualifiedName(R, Record->getDecl());
13089   R.suppressDiagnostics();
13090 
13091   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13092        Oper != OperEnd; ++Oper) {
13093     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13094                        Object.get()->Classify(Context), Args, CandidateSet,
13095                        /*SuppressUserConversions=*/false);
13096   }
13097 
13098   // C++ [over.call.object]p2:
13099   //   In addition, for each (non-explicit in C++0x) conversion function
13100   //   declared in T of the form
13101   //
13102   //        operator conversion-type-id () cv-qualifier;
13103   //
13104   //   where cv-qualifier is the same cv-qualification as, or a
13105   //   greater cv-qualification than, cv, and where conversion-type-id
13106   //   denotes the type "pointer to function of (P1,...,Pn) returning
13107   //   R", or the type "reference to pointer to function of
13108   //   (P1,...,Pn) returning R", or the type "reference to function
13109   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13110   //   is also considered as a candidate function. Similarly,
13111   //   surrogate call functions are added to the set of candidate
13112   //   functions for each conversion function declared in an
13113   //   accessible base class provided the function is not hidden
13114   //   within T by another intervening declaration.
13115   const auto &Conversions =
13116       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13117   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13118     NamedDecl *D = *I;
13119     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13120     if (isa<UsingShadowDecl>(D))
13121       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13122 
13123     // Skip over templated conversion functions; they aren't
13124     // surrogates.
13125     if (isa<FunctionTemplateDecl>(D))
13126       continue;
13127 
13128     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13129     if (!Conv->isExplicit()) {
13130       // Strip the reference type (if any) and then the pointer type (if
13131       // any) to get down to what might be a function type.
13132       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13133       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13134         ConvType = ConvPtrType->getPointeeType();
13135 
13136       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13137       {
13138         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13139                               Object.get(), Args, CandidateSet);
13140       }
13141     }
13142   }
13143 
13144   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13145 
13146   // Perform overload resolution.
13147   OverloadCandidateSet::iterator Best;
13148   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13149                                           Best)) {
13150   case OR_Success:
13151     // Overload resolution succeeded; we'll build the appropriate call
13152     // below.
13153     break;
13154 
13155   case OR_No_Viable_Function:
13156     if (CandidateSet.empty())
13157       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13158         << Object.get()->getType() << /*call*/ 1
13159         << Object.get()->getSourceRange();
13160     else
13161       Diag(Object.get()->getLocStart(),
13162            diag::err_ovl_no_viable_object_call)
13163         << Object.get()->getType() << Object.get()->getSourceRange();
13164     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13165     break;
13166 
13167   case OR_Ambiguous:
13168     Diag(Object.get()->getLocStart(),
13169          diag::err_ovl_ambiguous_object_call)
13170       << Object.get()->getType() << Object.get()->getSourceRange();
13171     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13172     break;
13173 
13174   case OR_Deleted:
13175     Diag(Object.get()->getLocStart(),
13176          diag::err_ovl_deleted_object_call)
13177       << Best->Function->isDeleted()
13178       << Object.get()->getType()
13179       << getDeletedOrUnavailableSuffix(Best->Function)
13180       << Object.get()->getSourceRange();
13181     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13182     break;
13183   }
13184 
13185   if (Best == CandidateSet.end())
13186     return true;
13187 
13188   UnbridgedCasts.restore();
13189 
13190   if (Best->Function == nullptr) {
13191     // Since there is no function declaration, this is one of the
13192     // surrogate candidates. Dig out the conversion function.
13193     CXXConversionDecl *Conv
13194       = cast<CXXConversionDecl>(
13195                          Best->Conversions[0].UserDefined.ConversionFunction);
13196 
13197     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13198                               Best->FoundDecl);
13199     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13200       return ExprError();
13201     assert(Conv == Best->FoundDecl.getDecl() &&
13202              "Found Decl & conversion-to-functionptr should be same, right?!");
13203     // We selected one of the surrogate functions that converts the
13204     // object parameter to a function pointer. Perform the conversion
13205     // on the object argument, then let ActOnCallExpr finish the job.
13206 
13207     // Create an implicit member expr to refer to the conversion operator.
13208     // and then call it.
13209     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13210                                              Conv, HadMultipleCandidates);
13211     if (Call.isInvalid())
13212       return ExprError();
13213     // Record usage of conversion in an implicit cast.
13214     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13215                                     CK_UserDefinedConversion, Call.get(),
13216                                     nullptr, VK_RValue);
13217 
13218     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13219   }
13220 
13221   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13222 
13223   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13224   // that calls this method, using Object for the implicit object
13225   // parameter and passing along the remaining arguments.
13226   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13227 
13228   // An error diagnostic has already been printed when parsing the declaration.
13229   if (Method->isInvalidDecl())
13230     return ExprError();
13231 
13232   const FunctionProtoType *Proto =
13233     Method->getType()->getAs<FunctionProtoType>();
13234 
13235   unsigned NumParams = Proto->getNumParams();
13236 
13237   DeclarationNameInfo OpLocInfo(
13238                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13239   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13240   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13241                                            Obj, HadMultipleCandidates,
13242                                            OpLocInfo.getLoc(),
13243                                            OpLocInfo.getInfo());
13244   if (NewFn.isInvalid())
13245     return true;
13246 
13247   // Build the full argument list for the method call (the implicit object
13248   // parameter is placed at the beginning of the list).
13249   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13250   MethodArgs[0] = Object.get();
13251   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13252 
13253   // Once we've built TheCall, all of the expressions are properly
13254   // owned.
13255   QualType ResultTy = Method->getReturnType();
13256   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13257   ResultTy = ResultTy.getNonLValueExprType(Context);
13258 
13259   CXXOperatorCallExpr *TheCall = new (Context)
13260       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13261                           VK, RParenLoc, FPOptions());
13262 
13263   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13264     return true;
13265 
13266   // We may have default arguments. If so, we need to allocate more
13267   // slots in the call for them.
13268   if (Args.size() < NumParams)
13269     TheCall->setNumArgs(Context, NumParams + 1);
13270 
13271   bool IsError = false;
13272 
13273   // Initialize the implicit object parameter.
13274   ExprResult ObjRes =
13275     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13276                                         Best->FoundDecl, Method);
13277   if (ObjRes.isInvalid())
13278     IsError = true;
13279   else
13280     Object = ObjRes;
13281   TheCall->setArg(0, Object.get());
13282 
13283   // Check the argument types.
13284   for (unsigned i = 0; i != NumParams; i++) {
13285     Expr *Arg;
13286     if (i < Args.size()) {
13287       Arg = Args[i];
13288 
13289       // Pass the argument.
13290 
13291       ExprResult InputInit
13292         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13293                                                     Context,
13294                                                     Method->getParamDecl(i)),
13295                                     SourceLocation(), Arg);
13296 
13297       IsError |= InputInit.isInvalid();
13298       Arg = InputInit.getAs<Expr>();
13299     } else {
13300       ExprResult DefArg
13301         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13302       if (DefArg.isInvalid()) {
13303         IsError = true;
13304         break;
13305       }
13306 
13307       Arg = DefArg.getAs<Expr>();
13308     }
13309 
13310     TheCall->setArg(i + 1, Arg);
13311   }
13312 
13313   // If this is a variadic call, handle args passed through "...".
13314   if (Proto->isVariadic()) {
13315     // Promote the arguments (C99 6.5.2.2p7).
13316     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13317       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13318                                                         nullptr);
13319       IsError |= Arg.isInvalid();
13320       TheCall->setArg(i + 1, Arg.get());
13321     }
13322   }
13323 
13324   if (IsError) return true;
13325 
13326   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13327 
13328   if (CheckFunctionCall(Method, TheCall, Proto))
13329     return true;
13330 
13331   return MaybeBindToTemporary(TheCall);
13332 }
13333 
13334 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13335 ///  (if one exists), where @c Base is an expression of class type and
13336 /// @c Member is the name of the member we're trying to find.
13337 ExprResult
13338 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13339                                bool *NoArrowOperatorFound) {
13340   assert(Base->getType()->isRecordType() &&
13341          "left-hand side must have class type");
13342 
13343   if (checkPlaceholderForOverload(*this, Base))
13344     return ExprError();
13345 
13346   SourceLocation Loc = Base->getExprLoc();
13347 
13348   // C++ [over.ref]p1:
13349   //
13350   //   [...] An expression x->m is interpreted as (x.operator->())->m
13351   //   for a class object x of type T if T::operator->() exists and if
13352   //   the operator is selected as the best match function by the
13353   //   overload resolution mechanism (13.3).
13354   DeclarationName OpName =
13355     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13356   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13357   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13358 
13359   if (RequireCompleteType(Loc, Base->getType(),
13360                           diag::err_typecheck_incomplete_tag, Base))
13361     return ExprError();
13362 
13363   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13364   LookupQualifiedName(R, BaseRecord->getDecl());
13365   R.suppressDiagnostics();
13366 
13367   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13368        Oper != OperEnd; ++Oper) {
13369     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13370                        None, CandidateSet, /*SuppressUserConversions=*/false);
13371   }
13372 
13373   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13374 
13375   // Perform overload resolution.
13376   OverloadCandidateSet::iterator Best;
13377   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13378   case OR_Success:
13379     // Overload resolution succeeded; we'll build the call below.
13380     break;
13381 
13382   case OR_No_Viable_Function:
13383     if (CandidateSet.empty()) {
13384       QualType BaseType = Base->getType();
13385       if (NoArrowOperatorFound) {
13386         // Report this specific error to the caller instead of emitting a
13387         // diagnostic, as requested.
13388         *NoArrowOperatorFound = true;
13389         return ExprError();
13390       }
13391       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13392         << BaseType << Base->getSourceRange();
13393       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13394         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13395           << FixItHint::CreateReplacement(OpLoc, ".");
13396       }
13397     } else
13398       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13399         << "operator->" << Base->getSourceRange();
13400     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13401     return ExprError();
13402 
13403   case OR_Ambiguous:
13404     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13405       << "->" << Base->getType() << Base->getSourceRange();
13406     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13407     return ExprError();
13408 
13409   case OR_Deleted:
13410     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13411       << Best->Function->isDeleted()
13412       << "->"
13413       << getDeletedOrUnavailableSuffix(Best->Function)
13414       << Base->getSourceRange();
13415     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13416     return ExprError();
13417   }
13418 
13419   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13420 
13421   // Convert the object parameter.
13422   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13423   ExprResult BaseResult =
13424     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13425                                         Best->FoundDecl, Method);
13426   if (BaseResult.isInvalid())
13427     return ExprError();
13428   Base = BaseResult.get();
13429 
13430   // Build the operator call.
13431   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13432                                             Base, HadMultipleCandidates, OpLoc);
13433   if (FnExpr.isInvalid())
13434     return ExprError();
13435 
13436   QualType ResultTy = Method->getReturnType();
13437   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13438   ResultTy = ResultTy.getNonLValueExprType(Context);
13439   CXXOperatorCallExpr *TheCall =
13440     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13441                                       Base, ResultTy, VK, OpLoc, FPOptions());
13442 
13443   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13444     return ExprError();
13445 
13446   if (CheckFunctionCall(Method, TheCall,
13447                         Method->getType()->castAs<FunctionProtoType>()))
13448     return ExprError();
13449 
13450   return MaybeBindToTemporary(TheCall);
13451 }
13452 
13453 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13454 /// a literal operator described by the provided lookup results.
13455 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13456                                           DeclarationNameInfo &SuffixInfo,
13457                                           ArrayRef<Expr*> Args,
13458                                           SourceLocation LitEndLoc,
13459                                        TemplateArgumentListInfo *TemplateArgs) {
13460   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13461 
13462   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13463                                     OverloadCandidateSet::CSK_Normal);
13464   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13465                         /*SuppressUserConversions=*/true);
13466 
13467   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13468 
13469   // Perform overload resolution. This will usually be trivial, but might need
13470   // to perform substitutions for a literal operator template.
13471   OverloadCandidateSet::iterator Best;
13472   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13473   case OR_Success:
13474   case OR_Deleted:
13475     break;
13476 
13477   case OR_No_Viable_Function:
13478     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13479       << R.getLookupName();
13480     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13481     return ExprError();
13482 
13483   case OR_Ambiguous:
13484     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13485     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13486     return ExprError();
13487   }
13488 
13489   FunctionDecl *FD = Best->Function;
13490   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13491                                         nullptr, HadMultipleCandidates,
13492                                         SuffixInfo.getLoc(),
13493                                         SuffixInfo.getInfo());
13494   if (Fn.isInvalid())
13495     return true;
13496 
13497   // Check the argument types. This should almost always be a no-op, except
13498   // that array-to-pointer decay is applied to string literals.
13499   Expr *ConvArgs[2];
13500   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13501     ExprResult InputInit = PerformCopyInitialization(
13502       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13503       SourceLocation(), Args[ArgIdx]);
13504     if (InputInit.isInvalid())
13505       return true;
13506     ConvArgs[ArgIdx] = InputInit.get();
13507   }
13508 
13509   QualType ResultTy = FD->getReturnType();
13510   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13511   ResultTy = ResultTy.getNonLValueExprType(Context);
13512 
13513   UserDefinedLiteral *UDL =
13514     new (Context) UserDefinedLiteral(Context, Fn.get(),
13515                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13516                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13517 
13518   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13519     return ExprError();
13520 
13521   if (CheckFunctionCall(FD, UDL, nullptr))
13522     return ExprError();
13523 
13524   return MaybeBindToTemporary(UDL);
13525 }
13526 
13527 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13528 /// given LookupResult is non-empty, it is assumed to describe a member which
13529 /// will be invoked. Otherwise, the function will be found via argument
13530 /// dependent lookup.
13531 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13532 /// otherwise CallExpr is set to ExprError() and some non-success value
13533 /// is returned.
13534 Sema::ForRangeStatus
13535 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13536                                 SourceLocation RangeLoc,
13537                                 const DeclarationNameInfo &NameInfo,
13538                                 LookupResult &MemberLookup,
13539                                 OverloadCandidateSet *CandidateSet,
13540                                 Expr *Range, ExprResult *CallExpr) {
13541   Scope *S = nullptr;
13542 
13543   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13544   if (!MemberLookup.empty()) {
13545     ExprResult MemberRef =
13546         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13547                                  /*IsPtr=*/false, CXXScopeSpec(),
13548                                  /*TemplateKWLoc=*/SourceLocation(),
13549                                  /*FirstQualifierInScope=*/nullptr,
13550                                  MemberLookup,
13551                                  /*TemplateArgs=*/nullptr, S);
13552     if (MemberRef.isInvalid()) {
13553       *CallExpr = ExprError();
13554       return FRS_DiagnosticIssued;
13555     }
13556     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13557     if (CallExpr->isInvalid()) {
13558       *CallExpr = ExprError();
13559       return FRS_DiagnosticIssued;
13560     }
13561   } else {
13562     UnresolvedSet<0> FoundNames;
13563     UnresolvedLookupExpr *Fn =
13564       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13565                                    NestedNameSpecifierLoc(), NameInfo,
13566                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13567                                    FoundNames.begin(), FoundNames.end());
13568 
13569     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13570                                                     CandidateSet, CallExpr);
13571     if (CandidateSet->empty() || CandidateSetError) {
13572       *CallExpr = ExprError();
13573       return FRS_NoViableFunction;
13574     }
13575     OverloadCandidateSet::iterator Best;
13576     OverloadingResult OverloadResult =
13577         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13578 
13579     if (OverloadResult == OR_No_Viable_Function) {
13580       *CallExpr = ExprError();
13581       return FRS_NoViableFunction;
13582     }
13583     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13584                                          Loc, nullptr, CandidateSet, &Best,
13585                                          OverloadResult,
13586                                          /*AllowTypoCorrection=*/false);
13587     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13588       *CallExpr = ExprError();
13589       return FRS_DiagnosticIssued;
13590     }
13591   }
13592   return FRS_Success;
13593 }
13594 
13595 
13596 /// FixOverloadedFunctionReference - E is an expression that refers to
13597 /// a C++ overloaded function (possibly with some parentheses and
13598 /// perhaps a '&' around it). We have resolved the overloaded function
13599 /// to the function declaration Fn, so patch up the expression E to
13600 /// refer (possibly indirectly) to Fn. Returns the new expr.
13601 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13602                                            FunctionDecl *Fn) {
13603   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13604     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13605                                                    Found, Fn);
13606     if (SubExpr == PE->getSubExpr())
13607       return PE;
13608 
13609     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13610   }
13611 
13612   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13613     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13614                                                    Found, Fn);
13615     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13616                                SubExpr->getType()) &&
13617            "Implicit cast type cannot be determined from overload");
13618     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13619     if (SubExpr == ICE->getSubExpr())
13620       return ICE;
13621 
13622     return ImplicitCastExpr::Create(Context, ICE->getType(),
13623                                     ICE->getCastKind(),
13624                                     SubExpr, nullptr,
13625                                     ICE->getValueKind());
13626   }
13627 
13628   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13629     if (!GSE->isResultDependent()) {
13630       Expr *SubExpr =
13631           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13632       if (SubExpr == GSE->getResultExpr())
13633         return GSE;
13634 
13635       // Replace the resulting type information before rebuilding the generic
13636       // selection expression.
13637       ArrayRef<Expr *> A = GSE->getAssocExprs();
13638       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13639       unsigned ResultIdx = GSE->getResultIndex();
13640       AssocExprs[ResultIdx] = SubExpr;
13641 
13642       return new (Context) GenericSelectionExpr(
13643           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13644           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13645           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13646           ResultIdx);
13647     }
13648     // Rather than fall through to the unreachable, return the original generic
13649     // selection expression.
13650     return GSE;
13651   }
13652 
13653   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13654     assert(UnOp->getOpcode() == UO_AddrOf &&
13655            "Can only take the address of an overloaded function");
13656     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13657       if (Method->isStatic()) {
13658         // Do nothing: static member functions aren't any different
13659         // from non-member functions.
13660       } else {
13661         // Fix the subexpression, which really has to be an
13662         // UnresolvedLookupExpr holding an overloaded member function
13663         // or template.
13664         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13665                                                        Found, Fn);
13666         if (SubExpr == UnOp->getSubExpr())
13667           return UnOp;
13668 
13669         assert(isa<DeclRefExpr>(SubExpr)
13670                && "fixed to something other than a decl ref");
13671         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13672                && "fixed to a member ref with no nested name qualifier");
13673 
13674         // We have taken the address of a pointer to member
13675         // function. Perform the computation here so that we get the
13676         // appropriate pointer to member type.
13677         QualType ClassType
13678           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13679         QualType MemPtrType
13680           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13681         // Under the MS ABI, lock down the inheritance model now.
13682         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13683           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13684 
13685         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13686                                            VK_RValue, OK_Ordinary,
13687                                            UnOp->getOperatorLoc(), false);
13688       }
13689     }
13690     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13691                                                    Found, Fn);
13692     if (SubExpr == UnOp->getSubExpr())
13693       return UnOp;
13694 
13695     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13696                                      Context.getPointerType(SubExpr->getType()),
13697                                        VK_RValue, OK_Ordinary,
13698                                        UnOp->getOperatorLoc(), false);
13699   }
13700 
13701   // C++ [except.spec]p17:
13702   //   An exception-specification is considered to be needed when:
13703   //   - in an expression the function is the unique lookup result or the
13704   //     selected member of a set of overloaded functions
13705   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13706     ResolveExceptionSpec(E->getExprLoc(), FPT);
13707 
13708   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13709     // FIXME: avoid copy.
13710     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13711     if (ULE->hasExplicitTemplateArgs()) {
13712       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13713       TemplateArgs = &TemplateArgsBuffer;
13714     }
13715 
13716     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13717                                            ULE->getQualifierLoc(),
13718                                            ULE->getTemplateKeywordLoc(),
13719                                            Fn,
13720                                            /*enclosing*/ false, // FIXME?
13721                                            ULE->getNameLoc(),
13722                                            Fn->getType(),
13723                                            VK_LValue,
13724                                            Found.getDecl(),
13725                                            TemplateArgs);
13726     MarkDeclRefReferenced(DRE);
13727     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13728     return DRE;
13729   }
13730 
13731   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13732     // FIXME: avoid copy.
13733     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13734     if (MemExpr->hasExplicitTemplateArgs()) {
13735       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13736       TemplateArgs = &TemplateArgsBuffer;
13737     }
13738 
13739     Expr *Base;
13740 
13741     // If we're filling in a static method where we used to have an
13742     // implicit member access, rewrite to a simple decl ref.
13743     if (MemExpr->isImplicitAccess()) {
13744       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13745         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13746                                                MemExpr->getQualifierLoc(),
13747                                                MemExpr->getTemplateKeywordLoc(),
13748                                                Fn,
13749                                                /*enclosing*/ false,
13750                                                MemExpr->getMemberLoc(),
13751                                                Fn->getType(),
13752                                                VK_LValue,
13753                                                Found.getDecl(),
13754                                                TemplateArgs);
13755         MarkDeclRefReferenced(DRE);
13756         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13757         return DRE;
13758       } else {
13759         SourceLocation Loc = MemExpr->getMemberLoc();
13760         if (MemExpr->getQualifier())
13761           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13762         CheckCXXThisCapture(Loc);
13763         Base = new (Context) CXXThisExpr(Loc,
13764                                          MemExpr->getBaseType(),
13765                                          /*isImplicit=*/true);
13766       }
13767     } else
13768       Base = MemExpr->getBase();
13769 
13770     ExprValueKind valueKind;
13771     QualType type;
13772     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13773       valueKind = VK_LValue;
13774       type = Fn->getType();
13775     } else {
13776       valueKind = VK_RValue;
13777       type = Context.BoundMemberTy;
13778     }
13779 
13780     MemberExpr *ME = MemberExpr::Create(
13781         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13782         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13783         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13784         OK_Ordinary);
13785     ME->setHadMultipleCandidates(true);
13786     MarkMemberReferenced(ME);
13787     return ME;
13788   }
13789 
13790   llvm_unreachable("Invalid reference to overloaded function");
13791 }
13792 
13793 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13794                                                 DeclAccessPair Found,
13795                                                 FunctionDecl *Fn) {
13796   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13797 }
13798