1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331       llvm::APSInt IntConstantValue;
332       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333       assert(Initializer && "Unknown conversion expression");
334 
335       // If it's value-dependent, we can't tell whether it's narrowing.
336       if (Initializer->isValueDependent())
337         return NK_Dependent_Narrowing;
338 
339       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340         // Convert the integer to the floating type.
341         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343                                 llvm::APFloat::rmNearestTiesToEven);
344         // And back.
345         llvm::APSInt ConvertedValue = IntConstantValue;
346         bool ignored;
347         Result.convertToInteger(ConvertedValue,
348                                 llvm::APFloat::rmTowardZero, &ignored);
349         // If the resulting value is different, this was a narrowing conversion.
350         if (IntConstantValue != ConvertedValue) {
351           ConstantValue = APValue(IntConstantValue);
352           ConstantType = Initializer->getType();
353           return NK_Constant_Narrowing;
354         }
355       } else {
356         // Variables are always narrowings.
357         return NK_Variable_Narrowing;
358       }
359     }
360     return NK_Not_Narrowing;
361 
362   // -- from long double to double or float, or from double to float, except
363   //    where the source is a constant expression and the actual value after
364   //    conversion is within the range of values that can be represented (even
365   //    if it cannot be represented exactly), or
366   case ICK_Floating_Conversion:
367     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369       // FromType is larger than ToType.
370       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371 
372       // If it's value-dependent, we can't tell whether it's narrowing.
373       if (Initializer->isValueDependent())
374         return NK_Dependent_Narrowing;
375 
376       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377         // Constant!
378         assert(ConstantValue.isFloat());
379         llvm::APFloat FloatVal = ConstantValue.getFloat();
380         // Convert the source value into the target type.
381         bool ignored;
382         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383           Ctx.getFloatTypeSemantics(ToType),
384           llvm::APFloat::rmNearestTiesToEven, &ignored);
385         // If there was no overflow, the source value is within the range of
386         // values that can be represented.
387         if (ConvertStatus & llvm::APFloat::opOverflow) {
388           ConstantType = Initializer->getType();
389           return NK_Constant_Narrowing;
390         }
391       } else {
392         return NK_Variable_Narrowing;
393       }
394     }
395     return NK_Not_Narrowing;
396 
397   // -- from an integer type or unscoped enumeration type to an integer type
398   //    that cannot represent all the values of the original type, except where
399   //    the source is a constant expression and the actual value after
400   //    conversion will fit into the target type and will produce the original
401   //    value when converted back to the original type.
402   case ICK_Integral_Conversion:
403   IntegralConversion: {
404     assert(FromType->isIntegralOrUnscopedEnumerationType());
405     assert(ToType->isIntegralOrUnscopedEnumerationType());
406     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407     const unsigned FromWidth = Ctx.getIntWidth(FromType);
408     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409     const unsigned ToWidth = Ctx.getIntWidth(ToType);
410 
411     if (FromWidth > ToWidth ||
412         (FromWidth == ToWidth && FromSigned != ToSigned) ||
413         (FromSigned && !ToSigned)) {
414       // Not all values of FromType can be represented in ToType.
415       llvm::APSInt InitializerValue;
416       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417 
418       // If it's value-dependent, we can't tell whether it's narrowing.
419       if (Initializer->isValueDependent())
420         return NK_Dependent_Narrowing;
421 
422       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423         // Such conversions on variables are always narrowing.
424         return NK_Variable_Narrowing;
425       }
426       bool Narrowing = false;
427       if (FromWidth < ToWidth) {
428         // Negative -> unsigned is narrowing. Otherwise, more bits is never
429         // narrowing.
430         if (InitializerValue.isSigned() && InitializerValue.isNegative())
431           Narrowing = true;
432       } else {
433         // Add a bit to the InitializerValue so we don't have to worry about
434         // signed vs. unsigned comparisons.
435         InitializerValue = InitializerValue.extend(
436           InitializerValue.getBitWidth() + 1);
437         // Convert the initializer to and from the target width and signed-ness.
438         llvm::APSInt ConvertedValue = InitializerValue;
439         ConvertedValue = ConvertedValue.trunc(ToWidth);
440         ConvertedValue.setIsSigned(ToSigned);
441         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442         ConvertedValue.setIsSigned(InitializerValue.isSigned());
443         // If the result is different, this was a narrowing conversion.
444         if (ConvertedValue != InitializerValue)
445           Narrowing = true;
446       }
447       if (Narrowing) {
448         ConstantType = Initializer->getType();
449         ConstantValue = APValue(InitializerValue);
450         return NK_Constant_Narrowing;
451       }
452     }
453     return NK_Not_Narrowing;
454   }
455 
456   default:
457     // Other kinds of conversions are not narrowings.
458     return NK_Not_Narrowing;
459   }
460 }
461 
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465   raw_ostream &OS = llvm::errs();
466   bool PrintedSomething = false;
467   if (First != ICK_Identity) {
468     OS << GetImplicitConversionName(First);
469     PrintedSomething = true;
470   }
471 
472   if (Second != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Second);
477 
478     if (CopyConstructor) {
479       OS << " (by copy constructor)";
480     } else if (DirectBinding) {
481       OS << " (direct reference binding)";
482     } else if (ReferenceBinding) {
483       OS << " (reference binding)";
484     }
485     PrintedSomething = true;
486   }
487 
488   if (Third != ICK_Identity) {
489     if (PrintedSomething) {
490       OS << " -> ";
491     }
492     OS << GetImplicitConversionName(Third);
493     PrintedSomething = true;
494   }
495 
496   if (!PrintedSomething) {
497     OS << "No conversions required";
498   }
499 }
500 
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (Before.First || Before.Second || Before.Third) {
506     Before.dump();
507     OS << " -> ";
508   }
509   if (ConversionFunction)
510     OS << '\'' << *ConversionFunction << '\'';
511   else
512     OS << "aggregate initialization";
513   if (After.First || After.Second || After.Third) {
514     OS << " -> ";
515     After.dump();
516   }
517 }
518 
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (isStdInitializerListElement())
524     OS << "Worst std::initializer_list element conversion: ";
525   switch (ConversionKind) {
526   case StandardConversion:
527     OS << "Standard conversion: ";
528     Standard.dump();
529     break;
530   case UserDefinedConversion:
531     OS << "User-defined conversion: ";
532     UserDefined.dump();
533     break;
534   case EllipsisConversion:
535     OS << "Ellipsis conversion";
536     break;
537   case AmbiguousConversion:
538     OS << "Ambiguous conversion";
539     break;
540   case BadConversion:
541     OS << "Bad conversion";
542     break;
543   }
544 
545   OS << "\n";
546 }
547 
548 void AmbiguousConversionSequence::construct() {
549   new (&conversions()) ConversionSet();
550 }
551 
552 void AmbiguousConversionSequence::destruct() {
553   conversions().~ConversionSet();
554 }
555 
556 void
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558   FromTypePtr = O.FromTypePtr;
559   ToTypePtr = O.ToTypePtr;
560   new (&conversions()) ConversionSet(O.conversions());
561 }
562 
563 namespace {
564   // Structure used by DeductionFailureInfo to store
565   // template argument information.
566   struct DFIArguments {
567     TemplateArgument FirstArg;
568     TemplateArgument SecondArg;
569   };
570   // Structure used by DeductionFailureInfo to store
571   // template parameter and template argument information.
572   struct DFIParamWithArguments : DFIArguments {
573     TemplateParameter Param;
574   };
575   // Structure used by DeductionFailureInfo to store template argument
576   // information and the index of the problematic call argument.
577   struct DFIDeducedMismatchArgs : DFIArguments {
578     TemplateArgumentList *TemplateArgs;
579     unsigned CallArgIndex;
580   };
581 }
582 
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
585 DeductionFailureInfo
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587                                 Sema::TemplateDeductionResult TDK,
588                                 TemplateDeductionInfo &Info) {
589   DeductionFailureInfo Result;
590   Result.Result = static_cast<unsigned>(TDK);
591   Result.HasDiagnostic = false;
592   switch (TDK) {
593   case Sema::TDK_Invalid:
594   case Sema::TDK_InstantiationDepth:
595   case Sema::TDK_TooManyArguments:
596   case Sema::TDK_TooFewArguments:
597   case Sema::TDK_MiscellaneousDeductionFailure:
598   case Sema::TDK_CUDATargetMismatch:
599     Result.Data = nullptr;
600     break;
601 
602   case Sema::TDK_Incomplete:
603   case Sema::TDK_InvalidExplicitArguments:
604     Result.Data = Info.Param.getOpaqueValue();
605     break;
606 
607   case Sema::TDK_DeducedMismatch:
608   case Sema::TDK_DeducedMismatchNested: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     auto *Saved = new (Context) DFIDeducedMismatchArgs;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Saved->TemplateArgs = Info.take();
614     Saved->CallArgIndex = Info.CallArgIndex;
615     Result.Data = Saved;
616     break;
617   }
618 
619   case Sema::TDK_NonDeducedMismatch: {
620     // FIXME: Should allocate from normal heap so that we can free this later.
621     DFIArguments *Saved = new (Context) DFIArguments;
622     Saved->FirstArg = Info.FirstArg;
623     Saved->SecondArg = Info.SecondArg;
624     Result.Data = Saved;
625     break;
626   }
627 
628   case Sema::TDK_Inconsistent:
629   case Sema::TDK_Underqualified: {
630     // FIXME: Should allocate from normal heap so that we can free this later.
631     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632     Saved->Param = Info.Param;
633     Saved->FirstArg = Info.FirstArg;
634     Saved->SecondArg = Info.SecondArg;
635     Result.Data = Saved;
636     break;
637   }
638 
639   case Sema::TDK_SubstitutionFailure:
640     Result.Data = Info.take();
641     if (Info.hasSFINAEDiagnostic()) {
642       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643           SourceLocation(), PartialDiagnostic::NullDiagnostic());
644       Info.takeSFINAEDiagnostic(*Diag);
645       Result.HasDiagnostic = true;
646     }
647     break;
648 
649   case Sema::TDK_Success:
650   case Sema::TDK_NonDependentConversionFailure:
651     llvm_unreachable("not a deduction failure");
652   }
653 
654   return Result;
655 }
656 
657 void DeductionFailureInfo::Destroy() {
658   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659   case Sema::TDK_Success:
660   case Sema::TDK_Invalid:
661   case Sema::TDK_InstantiationDepth:
662   case Sema::TDK_Incomplete:
663   case Sema::TDK_TooManyArguments:
664   case Sema::TDK_TooFewArguments:
665   case Sema::TDK_InvalidExplicitArguments:
666   case Sema::TDK_CUDATargetMismatch:
667   case Sema::TDK_NonDependentConversionFailure:
668     break;
669 
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified:
672   case Sema::TDK_DeducedMismatch:
673   case Sema::TDK_DeducedMismatchNested:
674   case Sema::TDK_NonDeducedMismatch:
675     // FIXME: Destroy the data?
676     Data = nullptr;
677     break;
678 
679   case Sema::TDK_SubstitutionFailure:
680     // FIXME: Destroy the template argument list?
681     Data = nullptr;
682     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683       Diag->~PartialDiagnosticAt();
684       HasDiagnostic = false;
685     }
686     break;
687 
688   // Unhandled
689   case Sema::TDK_MiscellaneousDeductionFailure:
690     break;
691   }
692 }
693 
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695   if (HasDiagnostic)
696     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697   return nullptr;
698 }
699 
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_SubstitutionFailure:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711   case Sema::TDK_CUDATargetMismatch:
712   case Sema::TDK_NonDependentConversionFailure:
713     return TemplateParameter();
714 
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717     return TemplateParameter::getFromOpaqueValue(Data);
718 
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721     return static_cast<DFIParamWithArguments*>(Data)->Param;
722 
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727 
728   return TemplateParameter();
729 }
730 
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_TooManyArguments:
737   case Sema::TDK_TooFewArguments:
738   case Sema::TDK_Incomplete:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_Inconsistent:
741   case Sema::TDK_Underqualified:
742   case Sema::TDK_NonDeducedMismatch:
743   case Sema::TDK_CUDATargetMismatch:
744   case Sema::TDK_NonDependentConversionFailure:
745     return nullptr;
746 
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750 
751   case Sema::TDK_SubstitutionFailure:
752     return static_cast<TemplateArgumentList*>(Data);
753 
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758 
759   return nullptr;
760 }
761 
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_Incomplete:
768   case Sema::TDK_TooManyArguments:
769   case Sema::TDK_TooFewArguments:
770   case Sema::TDK_InvalidExplicitArguments:
771   case Sema::TDK_SubstitutionFailure:
772   case Sema::TDK_CUDATargetMismatch:
773   case Sema::TDK_NonDependentConversionFailure:
774     return nullptr;
775 
776   case Sema::TDK_Inconsistent:
777   case Sema::TDK_Underqualified:
778   case Sema::TDK_DeducedMismatch:
779   case Sema::TDK_DeducedMismatchNested:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->FirstArg;
782 
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787 
788   return nullptr;
789 }
790 
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793   case Sema::TDK_Success:
794   case Sema::TDK_Invalid:
795   case Sema::TDK_InstantiationDepth:
796   case Sema::TDK_Incomplete:
797   case Sema::TDK_TooManyArguments:
798   case Sema::TDK_TooFewArguments:
799   case Sema::TDK_InvalidExplicitArguments:
800   case Sema::TDK_SubstitutionFailure:
801   case Sema::TDK_CUDATargetMismatch:
802   case Sema::TDK_NonDependentConversionFailure:
803     return nullptr;
804 
805   case Sema::TDK_Inconsistent:
806   case Sema::TDK_Underqualified:
807   case Sema::TDK_DeducedMismatch:
808   case Sema::TDK_DeducedMismatchNested:
809   case Sema::TDK_NonDeducedMismatch:
810     return &static_cast<DFIArguments*>(Data)->SecondArg;
811 
812   // Unhandled
813   case Sema::TDK_MiscellaneousDeductionFailure:
814     break;
815   }
816 
817   return nullptr;
818 }
819 
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822   case Sema::TDK_DeducedMismatch:
823   case Sema::TDK_DeducedMismatchNested:
824     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825 
826   default:
827     return llvm::None;
828   }
829 }
830 
831 void OverloadCandidateSet::destroyCandidates() {
832   for (iterator i = begin(), e = end(); i != e; ++i) {
833     for (auto &C : i->Conversions)
834       C.~ImplicitConversionSequence();
835     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836       i->DeductionFailure.Destroy();
837   }
838 }
839 
840 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
841   destroyCandidates();
842   SlabAllocator.Reset();
843   NumInlineBytesUsed = 0;
844   Candidates.clear();
845   Functions.clear();
846   Kind = CSK;
847 }
848 
849 namespace {
850   class UnbridgedCastsSet {
851     struct Entry {
852       Expr **Addr;
853       Expr *Saved;
854     };
855     SmallVector<Entry, 2> Entries;
856 
857   public:
858     void save(Sema &S, Expr *&E) {
859       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
860       Entry entry = { &E, E };
861       Entries.push_back(entry);
862       E = S.stripARCUnbridgedCast(E);
863     }
864 
865     void restore() {
866       for (SmallVectorImpl<Entry>::iterator
867              i = Entries.begin(), e = Entries.end(); i != e; ++i)
868         *i->Addr = i->Saved;
869     }
870   };
871 }
872 
873 /// checkPlaceholderForOverload - Do any interesting placeholder-like
874 /// preprocessing on the given expression.
875 ///
876 /// \param unbridgedCasts a collection to which to add unbridged casts;
877 ///   without this, they will be immediately diagnosed as errors
878 ///
879 /// Return true on unrecoverable error.
880 static bool
881 checkPlaceholderForOverload(Sema &S, Expr *&E,
882                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
883   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
884     // We can't handle overloaded expressions here because overload
885     // resolution might reasonably tweak them.
886     if (placeholder->getKind() == BuiltinType::Overload) return false;
887 
888     // If the context potentially accepts unbridged ARC casts, strip
889     // the unbridged cast and add it to the collection for later restoration.
890     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891         unbridgedCasts) {
892       unbridgedCasts->save(S, E);
893       return false;
894     }
895 
896     // Go ahead and check everything else.
897     ExprResult result = S.CheckPlaceholderExpr(E);
898     if (result.isInvalid())
899       return true;
900 
901     E = result.get();
902     return false;
903   }
904 
905   // Nothing to do.
906   return false;
907 }
908 
909 /// checkArgPlaceholdersForOverload - Check a set of call operands for
910 /// placeholders.
911 static bool checkArgPlaceholdersForOverload(Sema &S,
912                                             MultiExprArg Args,
913                                             UnbridgedCastsSet &unbridged) {
914   for (unsigned i = 0, e = Args.size(); i != e; ++i)
915     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
916       return true;
917 
918   return false;
919 }
920 
921 /// Determine whether the given New declaration is an overload of the
922 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923 /// New and Old cannot be overloaded, e.g., if New has the same signature as
924 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925 /// functions (or function templates) at all. When it does return Ovl_Match or
926 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
928 /// declaration.
929 ///
930 /// Example: Given the following input:
931 ///
932 ///   void f(int, float); // #1
933 ///   void f(int, int); // #2
934 ///   int f(int, int); // #3
935 ///
936 /// When we process #1, there is no previous declaration of "f", so IsOverload
937 /// will not be used.
938 ///
939 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940 /// the parameter types, we see that #1 and #2 are overloaded (since they have
941 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
942 /// unchanged.
943 ///
944 /// When we process #3, Old is an overload set containing #1 and #2. We compare
945 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947 /// functions are not part of the signature), IsOverload returns Ovl_Match and
948 /// MatchedDecl will be set to point to the FunctionDecl for #2.
949 ///
950 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951 /// by a using declaration. The rules for whether to hide shadow declarations
952 /// ignore some properties which otherwise figure into a function template's
953 /// signature.
954 Sema::OverloadKind
955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956                     NamedDecl *&Match, bool NewIsUsingDecl) {
957   for (LookupResult::iterator I = Old.begin(), E = Old.end();
958          I != E; ++I) {
959     NamedDecl *OldD = *I;
960 
961     bool OldIsUsingDecl = false;
962     if (isa<UsingShadowDecl>(OldD)) {
963       OldIsUsingDecl = true;
964 
965       // We can always introduce two using declarations into the same
966       // context, even if they have identical signatures.
967       if (NewIsUsingDecl) continue;
968 
969       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970     }
971 
972     // A using-declaration does not conflict with another declaration
973     // if one of them is hidden.
974     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975       continue;
976 
977     // If either declaration was introduced by a using declaration,
978     // we'll need to use slightly different rules for matching.
979     // Essentially, these rules are the normal rules, except that
980     // function templates hide function templates with different
981     // return types or template parameter lists.
982     bool UseMemberUsingDeclRules =
983       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984       !New->getFriendObjectKind();
985 
986     if (FunctionDecl *OldF = OldD->getAsFunction()) {
987       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990           continue;
991         }
992 
993         if (!isa<FunctionTemplateDecl>(OldD) &&
994             !shouldLinkPossiblyHiddenDecl(*I, New))
995           continue;
996 
997         Match = *I;
998         return Ovl_Match;
999       }
1000     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001       // We can overload with these, which can show up when doing
1002       // redeclaration checks for UsingDecls.
1003       assert(Old.getLookupKind() == LookupUsingDeclName);
1004     } else if (isa<TagDecl>(OldD)) {
1005       // We can always overload with tags by hiding them.
1006     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007       // Optimistically assume that an unresolved using decl will
1008       // overload; if it doesn't, we'll have to diagnose during
1009       // template instantiation.
1010       //
1011       // Exception: if the scope is dependent and this is not a class
1012       // member, the using declaration can only introduce an enumerator.
1013       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else {
1018       // (C++ 13p1):
1019       //   Only function declarations can be overloaded; object and type
1020       //   declarations cannot be overloaded.
1021       Match = *I;
1022       return Ovl_NonFunction;
1023     }
1024   }
1025 
1026   return Ovl_Overload;
1027 }
1028 
1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031   // C++ [basic.start.main]p2: This function shall not be overloaded.
1032   if (New->isMain())
1033     return false;
1034 
1035   // MSVCRT user defined entry points cannot be overloaded.
1036   if (New->isMSVCRTEntryPoint())
1037     return false;
1038 
1039   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041 
1042   // C++ [temp.fct]p2:
1043   //   A function template can be overloaded with other function templates
1044   //   and with normal (non-template) functions.
1045   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1046     return true;
1047 
1048   // Is the function New an overload of the function Old?
1049   QualType OldQType = Context.getCanonicalType(Old->getType());
1050   QualType NewQType = Context.getCanonicalType(New->getType());
1051 
1052   // Compare the signatures (C++ 1.3.10) of the two functions to
1053   // determine whether they are overloads. If we find any mismatch
1054   // in the signature, they are overloads.
1055 
1056   // If either of these functions is a K&R-style function (no
1057   // prototype), then we consider them to have matching signatures.
1058   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060     return false;
1061 
1062   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064 
1065   // The signature of a function includes the types of its
1066   // parameters (C++ 1.3.10), which includes the presence or absence
1067   // of the ellipsis; see C++ DR 357).
1068   if (OldQType != NewQType &&
1069       (OldType->getNumParams() != NewType->getNumParams() ||
1070        OldType->isVariadic() != NewType->isVariadic() ||
1071        !FunctionParamTypesAreEqual(OldType, NewType)))
1072     return true;
1073 
1074   // C++ [temp.over.link]p4:
1075   //   The signature of a function template consists of its function
1076   //   signature, its return type and its template parameter list. The names
1077   //   of the template parameters are significant only for establishing the
1078   //   relationship between the template parameters and the rest of the
1079   //   signature.
1080   //
1081   // We check the return type and template parameter lists for function
1082   // templates first; the remaining checks follow.
1083   //
1084   // However, we don't consider either of these when deciding whether
1085   // a member introduced by a shadow declaration is hidden.
1086   if (!UseMemberUsingDeclRules && NewTemplate &&
1087       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088                                        OldTemplate->getTemplateParameters(),
1089                                        false, TPL_TemplateMatch) ||
1090        OldType->getReturnType() != NewType->getReturnType()))
1091     return true;
1092 
1093   // If the function is a class member, its signature includes the
1094   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095   //
1096   // As part of this, also check whether one of the member functions
1097   // is static, in which case they are not overloads (C++
1098   // 13.1p2). While not part of the definition of the signature,
1099   // this check is important to determine whether these functions
1100   // can be overloaded.
1101   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103   if (OldMethod && NewMethod &&
1104       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106       if (!UseMemberUsingDeclRules &&
1107           (OldMethod->getRefQualifier() == RQ_None ||
1108            NewMethod->getRefQualifier() == RQ_None)) {
1109         // C++0x [over.load]p2:
1110         //   - Member function declarations with the same name and the same
1111         //     parameter-type-list as well as member function template
1112         //     declarations with the same name, the same parameter-type-list, and
1113         //     the same template parameter lists cannot be overloaded if any of
1114         //     them, but not all, have a ref-qualifier (8.3.5).
1115         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1118       }
1119       return true;
1120     }
1121 
1122     // We may not have applied the implicit const for a constexpr member
1123     // function yet (because we haven't yet resolved whether this is a static
1124     // or non-static member function). Add it now, on the assumption that this
1125     // is a redeclaration of OldMethod.
1126     unsigned OldQuals = OldMethod->getTypeQualifiers();
1127     unsigned NewQuals = NewMethod->getTypeQualifiers();
1128     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129         !isa<CXXConstructorDecl>(NewMethod))
1130       NewQuals |= Qualifiers::Const;
1131 
1132     // We do not allow overloading based off of '__restrict'.
1133     OldQuals &= ~Qualifiers::Restrict;
1134     NewQuals &= ~Qualifiers::Restrict;
1135     if (OldQuals != NewQuals)
1136       return true;
1137   }
1138 
1139   // Though pass_object_size is placed on parameters and takes an argument, we
1140   // consider it to be a function-level modifier for the sake of function
1141   // identity. Either the function has one or more parameters with
1142   // pass_object_size or it doesn't.
1143   if (functionHasPassObjectSizeParams(New) !=
1144       functionHasPassObjectSizeParams(Old))
1145     return true;
1146 
1147   // enable_if attributes are an order-sensitive part of the signature.
1148   for (specific_attr_iterator<EnableIfAttr>
1149          NewI = New->specific_attr_begin<EnableIfAttr>(),
1150          NewE = New->specific_attr_end<EnableIfAttr>(),
1151          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152          OldE = Old->specific_attr_end<EnableIfAttr>();
1153        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154     if (NewI == NewE || OldI == OldE)
1155       return true;
1156     llvm::FoldingSetNodeID NewID, OldID;
1157     NewI->getCond()->Profile(NewID, Context, true);
1158     OldI->getCond()->Profile(OldID, Context, true);
1159     if (NewID != OldID)
1160       return true;
1161   }
1162 
1163   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164     // Don't allow overloading of destructors.  (In theory we could, but it
1165     // would be a giant change to clang.)
1166     if (isa<CXXDestructorDecl>(New))
1167       return false;
1168 
1169     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170                        OldTarget = IdentifyCUDATarget(Old);
1171     if (NewTarget == CFT_InvalidTarget)
1172       return false;
1173 
1174     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175 
1176     // Allow overloading of functions with same signature and different CUDA
1177     // target attributes.
1178     return NewTarget != OldTarget;
1179   }
1180 
1181   // The signatures match; this is not an overload.
1182   return false;
1183 }
1184 
1185 /// \brief Checks availability of the function depending on the current
1186 /// function context. Inside an unavailable function, unavailability is ignored.
1187 ///
1188 /// \returns true if \arg FD is unavailable and current context is inside
1189 /// an available function, false otherwise.
1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191   if (!FD->isUnavailable())
1192     return false;
1193 
1194   // Walk up the context of the caller.
1195   Decl *C = cast<Decl>(CurContext);
1196   do {
1197     if (C->isUnavailable())
1198       return false;
1199   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200   return true;
1201 }
1202 
1203 /// \brief Tries a user-defined conversion from From to ToType.
1204 ///
1205 /// Produces an implicit conversion sequence for when a standard conversion
1206 /// is not an option. See TryImplicitConversion for more information.
1207 static ImplicitConversionSequence
1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209                          bool SuppressUserConversions,
1210                          bool AllowExplicit,
1211                          bool InOverloadResolution,
1212                          bool CStyle,
1213                          bool AllowObjCWritebackConversion,
1214                          bool AllowObjCConversionOnExplicit) {
1215   ImplicitConversionSequence ICS;
1216 
1217   if (SuppressUserConversions) {
1218     // We're not in the case above, so there is no conversion that
1219     // we can perform.
1220     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221     return ICS;
1222   }
1223 
1224   // Attempt user-defined conversion.
1225   OverloadCandidateSet Conversions(From->getExprLoc(),
1226                                    OverloadCandidateSet::CSK_Normal);
1227   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228                                   Conversions, AllowExplicit,
1229                                   AllowObjCConversionOnExplicit)) {
1230   case OR_Success:
1231   case OR_Deleted:
1232     ICS.setUserDefined();
1233     // C++ [over.ics.user]p4:
1234     //   A conversion of an expression of class type to the same class
1235     //   type is given Exact Match rank, and a conversion of an
1236     //   expression of class type to a base class of that type is
1237     //   given Conversion rank, in spite of the fact that a copy
1238     //   constructor (i.e., a user-defined conversion function) is
1239     //   called for those cases.
1240     if (CXXConstructorDecl *Constructor
1241           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242       QualType FromCanon
1243         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244       QualType ToCanon
1245         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246       if (Constructor->isCopyConstructor() &&
1247           (FromCanon == ToCanon ||
1248            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249         // Turn this into a "standard" conversion sequence, so that it
1250         // gets ranked with standard conversion sequences.
1251         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252         ICS.setStandard();
1253         ICS.Standard.setAsIdentityConversion();
1254         ICS.Standard.setFromType(From->getType());
1255         ICS.Standard.setAllToTypes(ToType);
1256         ICS.Standard.CopyConstructor = Constructor;
1257         ICS.Standard.FoundCopyConstructor = Found;
1258         if (ToCanon != FromCanon)
1259           ICS.Standard.Second = ICK_Derived_To_Base;
1260       }
1261     }
1262     break;
1263 
1264   case OR_Ambiguous:
1265     ICS.setAmbiguous();
1266     ICS.Ambiguous.setFromType(From->getType());
1267     ICS.Ambiguous.setToType(ToType);
1268     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269          Cand != Conversions.end(); ++Cand)
1270       if (Cand->Viable)
1271         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1272     break;
1273 
1274     // Fall through.
1275   case OR_No_Viable_Function:
1276     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1277     break;
1278   }
1279 
1280   return ICS;
1281 }
1282 
1283 /// TryImplicitConversion - Attempt to perform an implicit conversion
1284 /// from the given expression (Expr) to the given type (ToType). This
1285 /// function returns an implicit conversion sequence that can be used
1286 /// to perform the initialization. Given
1287 ///
1288 ///   void f(float f);
1289 ///   void g(int i) { f(i); }
1290 ///
1291 /// this routine would produce an implicit conversion sequence to
1292 /// describe the initialization of f from i, which will be a standard
1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295 //
1296 /// Note that this routine only determines how the conversion can be
1297 /// performed; it does not actually perform the conversion. As such,
1298 /// it will not produce any diagnostics if no conversion is available,
1299 /// but will instead return an implicit conversion sequence of kind
1300 /// "BadConversion".
1301 ///
1302 /// If @p SuppressUserConversions, then user-defined conversions are
1303 /// not permitted.
1304 /// If @p AllowExplicit, then explicit user-defined conversions are
1305 /// permitted.
1306 ///
1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308 /// writeback conversion, which allows __autoreleasing id* parameters to
1309 /// be initialized with __strong id* or __weak id* arguments.
1310 static ImplicitConversionSequence
1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312                       bool SuppressUserConversions,
1313                       bool AllowExplicit,
1314                       bool InOverloadResolution,
1315                       bool CStyle,
1316                       bool AllowObjCWritebackConversion,
1317                       bool AllowObjCConversionOnExplicit) {
1318   ImplicitConversionSequence ICS;
1319   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1321     ICS.setStandard();
1322     return ICS;
1323   }
1324 
1325   if (!S.getLangOpts().CPlusPlus) {
1326     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327     return ICS;
1328   }
1329 
1330   // C++ [over.ics.user]p4:
1331   //   A conversion of an expression of class type to the same class
1332   //   type is given Exact Match rank, and a conversion of an
1333   //   expression of class type to a base class of that type is
1334   //   given Conversion rank, in spite of the fact that a copy/move
1335   //   constructor (i.e., a user-defined conversion function) is
1336   //   called for those cases.
1337   QualType FromType = From->getType();
1338   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341     ICS.setStandard();
1342     ICS.Standard.setAsIdentityConversion();
1343     ICS.Standard.setFromType(FromType);
1344     ICS.Standard.setAllToTypes(ToType);
1345 
1346     // We don't actually check at this point whether there is a valid
1347     // copy/move constructor, since overloading just assumes that it
1348     // exists. When we actually perform initialization, we'll find the
1349     // appropriate constructor to copy the returned object, if needed.
1350     ICS.Standard.CopyConstructor = nullptr;
1351 
1352     // Determine whether this is considered a derived-to-base conversion.
1353     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354       ICS.Standard.Second = ICK_Derived_To_Base;
1355 
1356     return ICS;
1357   }
1358 
1359   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360                                   AllowExplicit, InOverloadResolution, CStyle,
1361                                   AllowObjCWritebackConversion,
1362                                   AllowObjCConversionOnExplicit);
1363 }
1364 
1365 ImplicitConversionSequence
1366 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367                             bool SuppressUserConversions,
1368                             bool AllowExplicit,
1369                             bool InOverloadResolution,
1370                             bool CStyle,
1371                             bool AllowObjCWritebackConversion) {
1372   return ::TryImplicitConversion(*this, From, ToType,
1373                                  SuppressUserConversions, AllowExplicit,
1374                                  InOverloadResolution, CStyle,
1375                                  AllowObjCWritebackConversion,
1376                                  /*AllowObjCConversionOnExplicit=*/false);
1377 }
1378 
1379 /// PerformImplicitConversion - Perform an implicit conversion of the
1380 /// expression From to the type ToType. Returns the
1381 /// converted expression. Flavor is the kind of conversion we're
1382 /// performing, used in the error message. If @p AllowExplicit,
1383 /// explicit user-defined conversions are permitted.
1384 ExprResult
1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386                                 AssignmentAction Action, bool AllowExplicit) {
1387   ImplicitConversionSequence ICS;
1388   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1389 }
1390 
1391 ExprResult
1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393                                 AssignmentAction Action, bool AllowExplicit,
1394                                 ImplicitConversionSequence& ICS) {
1395   if (checkPlaceholderForOverload(*this, From))
1396     return ExprError();
1397 
1398   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399   bool AllowObjCWritebackConversion
1400     = getLangOpts().ObjCAutoRefCount &&
1401       (Action == AA_Passing || Action == AA_Sending);
1402   if (getLangOpts().ObjC1)
1403     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404                                       ToType, From->getType(), From);
1405   ICS = ::TryImplicitConversion(*this, From, ToType,
1406                                 /*SuppressUserConversions=*/false,
1407                                 AllowExplicit,
1408                                 /*InOverloadResolution=*/false,
1409                                 /*CStyle=*/false,
1410                                 AllowObjCWritebackConversion,
1411                                 /*AllowObjCConversionOnExplicit=*/false);
1412   return PerformImplicitConversion(From, ToType, ICS, Action);
1413 }
1414 
1415 /// \brief Determine whether the conversion from FromType to ToType is a valid
1416 /// conversion that strips "noexcept" or "noreturn" off the nested function
1417 /// type.
1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419                                 QualType &ResultTy) {
1420   if (Context.hasSameUnqualifiedType(FromType, ToType))
1421     return false;
1422 
1423   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424   //                    or F(t noexcept) -> F(t)
1425   // where F adds one of the following at most once:
1426   //   - a pointer
1427   //   - a member pointer
1428   //   - a block pointer
1429   // Changes here need matching changes in FindCompositePointerType.
1430   CanQualType CanTo = Context.getCanonicalType(ToType);
1431   CanQualType CanFrom = Context.getCanonicalType(FromType);
1432   Type::TypeClass TyClass = CanTo->getTypeClass();
1433   if (TyClass != CanFrom->getTypeClass()) return false;
1434   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435     if (TyClass == Type::Pointer) {
1436       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438     } else if (TyClass == Type::BlockPointer) {
1439       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441     } else if (TyClass == Type::MemberPointer) {
1442       auto ToMPT = CanTo.getAs<MemberPointerType>();
1443       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444       // A function pointer conversion cannot change the class of the function.
1445       if (ToMPT->getClass() != FromMPT->getClass())
1446         return false;
1447       CanTo = ToMPT->getPointeeType();
1448       CanFrom = FromMPT->getPointeeType();
1449     } else {
1450       return false;
1451     }
1452 
1453     TyClass = CanTo->getTypeClass();
1454     if (TyClass != CanFrom->getTypeClass()) return false;
1455     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456       return false;
1457   }
1458 
1459   const auto *FromFn = cast<FunctionType>(CanFrom);
1460   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461 
1462   const auto *ToFn = cast<FunctionType>(CanTo);
1463   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464 
1465   bool Changed = false;
1466 
1467   // Drop 'noreturn' if not present in target type.
1468   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470     Changed = true;
1471   }
1472 
1473   // Drop 'noexcept' if not present in target type.
1474   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477       FromFn = cast<FunctionType>(
1478           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1479                                                    EST_None)
1480                  .getTypePtr());
1481       Changed = true;
1482     }
1483 
1484     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1485     // only if the ExtParameterInfo lists of the two function prototypes can be
1486     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1487     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1488     bool CanUseToFPT, CanUseFromFPT;
1489     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1490                                       CanUseFromFPT, NewParamInfos) &&
1491         CanUseToFPT && !CanUseFromFPT) {
1492       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1493       ExtInfo.ExtParameterInfos =
1494           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1495       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1496                                             FromFPT->getParamTypes(), ExtInfo);
1497       FromFn = QT->getAs<FunctionType>();
1498       Changed = true;
1499     }
1500   }
1501 
1502   if (!Changed)
1503     return false;
1504 
1505   assert(QualType(FromFn, 0).isCanonical());
1506   if (QualType(FromFn, 0) != CanTo) return false;
1507 
1508   ResultTy = ToType;
1509   return true;
1510 }
1511 
1512 /// \brief Determine whether the conversion from FromType to ToType is a valid
1513 /// vector conversion.
1514 ///
1515 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1516 /// conversion.
1517 static bool IsVectorConversion(Sema &S, QualType FromType,
1518                                QualType ToType, ImplicitConversionKind &ICK) {
1519   // We need at least one of these types to be a vector type to have a vector
1520   // conversion.
1521   if (!ToType->isVectorType() && !FromType->isVectorType())
1522     return false;
1523 
1524   // Identical types require no conversions.
1525   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1526     return false;
1527 
1528   // There are no conversions between extended vector types, only identity.
1529   if (ToType->isExtVectorType()) {
1530     // There are no conversions between extended vector types other than the
1531     // identity conversion.
1532     if (FromType->isExtVectorType())
1533       return false;
1534 
1535     // Vector splat from any arithmetic type to a vector.
1536     if (FromType->isArithmeticType()) {
1537       ICK = ICK_Vector_Splat;
1538       return true;
1539     }
1540   }
1541 
1542   // We can perform the conversion between vector types in the following cases:
1543   // 1)vector types are equivalent AltiVec and GCC vector types
1544   // 2)lax vector conversions are permitted and the vector types are of the
1545   //   same size
1546   if (ToType->isVectorType() && FromType->isVectorType()) {
1547     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1548         S.isLaxVectorConversion(FromType, ToType)) {
1549       ICK = ICK_Vector_Conversion;
1550       return true;
1551     }
1552   }
1553 
1554   return false;
1555 }
1556 
1557 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1558                                 bool InOverloadResolution,
1559                                 StandardConversionSequence &SCS,
1560                                 bool CStyle);
1561 
1562 /// IsStandardConversion - Determines whether there is a standard
1563 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1564 /// expression From to the type ToType. Standard conversion sequences
1565 /// only consider non-class types; for conversions that involve class
1566 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1567 /// contain the standard conversion sequence required to perform this
1568 /// conversion and this routine will return true. Otherwise, this
1569 /// routine will return false and the value of SCS is unspecified.
1570 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1571                                  bool InOverloadResolution,
1572                                  StandardConversionSequence &SCS,
1573                                  bool CStyle,
1574                                  bool AllowObjCWritebackConversion) {
1575   QualType FromType = From->getType();
1576 
1577   // Standard conversions (C++ [conv])
1578   SCS.setAsIdentityConversion();
1579   SCS.IncompatibleObjC = false;
1580   SCS.setFromType(FromType);
1581   SCS.CopyConstructor = nullptr;
1582 
1583   // There are no standard conversions for class types in C++, so
1584   // abort early. When overloading in C, however, we do permit them.
1585   if (S.getLangOpts().CPlusPlus &&
1586       (FromType->isRecordType() || ToType->isRecordType()))
1587     return false;
1588 
1589   // The first conversion can be an lvalue-to-rvalue conversion,
1590   // array-to-pointer conversion, or function-to-pointer conversion
1591   // (C++ 4p1).
1592 
1593   if (FromType == S.Context.OverloadTy) {
1594     DeclAccessPair AccessPair;
1595     if (FunctionDecl *Fn
1596           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1597                                                  AccessPair)) {
1598       // We were able to resolve the address of the overloaded function,
1599       // so we can convert to the type of that function.
1600       FromType = Fn->getType();
1601       SCS.setFromType(FromType);
1602 
1603       // we can sometimes resolve &foo<int> regardless of ToType, so check
1604       // if the type matches (identity) or we are converting to bool
1605       if (!S.Context.hasSameUnqualifiedType(
1606                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1607         QualType resultTy;
1608         // if the function type matches except for [[noreturn]], it's ok
1609         if (!S.IsFunctionConversion(FromType,
1610               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1611           // otherwise, only a boolean conversion is standard
1612           if (!ToType->isBooleanType())
1613             return false;
1614       }
1615 
1616       // Check if the "from" expression is taking the address of an overloaded
1617       // function and recompute the FromType accordingly. Take advantage of the
1618       // fact that non-static member functions *must* have such an address-of
1619       // expression.
1620       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1621       if (Method && !Method->isStatic()) {
1622         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1623                "Non-unary operator on non-static member address");
1624         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1625                == UO_AddrOf &&
1626                "Non-address-of operator on non-static member address");
1627         const Type *ClassType
1628           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1629         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1630       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1631         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1632                UO_AddrOf &&
1633                "Non-address-of operator for overloaded function expression");
1634         FromType = S.Context.getPointerType(FromType);
1635       }
1636 
1637       // Check that we've computed the proper type after overload resolution.
1638       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1639       // be calling it from within an NDEBUG block.
1640       assert(S.Context.hasSameType(
1641         FromType,
1642         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1643     } else {
1644       return false;
1645     }
1646   }
1647   // Lvalue-to-rvalue conversion (C++11 4.1):
1648   //   A glvalue (3.10) of a non-function, non-array type T can
1649   //   be converted to a prvalue.
1650   bool argIsLValue = From->isGLValue();
1651   if (argIsLValue &&
1652       !FromType->isFunctionType() && !FromType->isArrayType() &&
1653       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1654     SCS.First = ICK_Lvalue_To_Rvalue;
1655 
1656     // C11 6.3.2.1p2:
1657     //   ... if the lvalue has atomic type, the value has the non-atomic version
1658     //   of the type of the lvalue ...
1659     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1660       FromType = Atomic->getValueType();
1661 
1662     // If T is a non-class type, the type of the rvalue is the
1663     // cv-unqualified version of T. Otherwise, the type of the rvalue
1664     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1665     // just strip the qualifiers because they don't matter.
1666     FromType = FromType.getUnqualifiedType();
1667   } else if (FromType->isArrayType()) {
1668     // Array-to-pointer conversion (C++ 4.2)
1669     SCS.First = ICK_Array_To_Pointer;
1670 
1671     // An lvalue or rvalue of type "array of N T" or "array of unknown
1672     // bound of T" can be converted to an rvalue of type "pointer to
1673     // T" (C++ 4.2p1).
1674     FromType = S.Context.getArrayDecayedType(FromType);
1675 
1676     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1677       // This conversion is deprecated in C++03 (D.4)
1678       SCS.DeprecatedStringLiteralToCharPtr = true;
1679 
1680       // For the purpose of ranking in overload resolution
1681       // (13.3.3.1.1), this conversion is considered an
1682       // array-to-pointer conversion followed by a qualification
1683       // conversion (4.4). (C++ 4.2p2)
1684       SCS.Second = ICK_Identity;
1685       SCS.Third = ICK_Qualification;
1686       SCS.QualificationIncludesObjCLifetime = false;
1687       SCS.setAllToTypes(FromType);
1688       return true;
1689     }
1690   } else if (FromType->isFunctionType() && argIsLValue) {
1691     // Function-to-pointer conversion (C++ 4.3).
1692     SCS.First = ICK_Function_To_Pointer;
1693 
1694     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1695       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1696         if (!S.checkAddressOfFunctionIsAvailable(FD))
1697           return false;
1698 
1699     // An lvalue of function type T can be converted to an rvalue of
1700     // type "pointer to T." The result is a pointer to the
1701     // function. (C++ 4.3p1).
1702     FromType = S.Context.getPointerType(FromType);
1703   } else {
1704     // We don't require any conversions for the first step.
1705     SCS.First = ICK_Identity;
1706   }
1707   SCS.setToType(0, FromType);
1708 
1709   // The second conversion can be an integral promotion, floating
1710   // point promotion, integral conversion, floating point conversion,
1711   // floating-integral conversion, pointer conversion,
1712   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1713   // For overloading in C, this can also be a "compatible-type"
1714   // conversion.
1715   bool IncompatibleObjC = false;
1716   ImplicitConversionKind SecondICK = ICK_Identity;
1717   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1718     // The unqualified versions of the types are the same: there's no
1719     // conversion to do.
1720     SCS.Second = ICK_Identity;
1721   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1722     // Integral promotion (C++ 4.5).
1723     SCS.Second = ICK_Integral_Promotion;
1724     FromType = ToType.getUnqualifiedType();
1725   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1726     // Floating point promotion (C++ 4.6).
1727     SCS.Second = ICK_Floating_Promotion;
1728     FromType = ToType.getUnqualifiedType();
1729   } else if (S.IsComplexPromotion(FromType, ToType)) {
1730     // Complex promotion (Clang extension)
1731     SCS.Second = ICK_Complex_Promotion;
1732     FromType = ToType.getUnqualifiedType();
1733   } else if (ToType->isBooleanType() &&
1734              (FromType->isArithmeticType() ||
1735               FromType->isAnyPointerType() ||
1736               FromType->isBlockPointerType() ||
1737               FromType->isMemberPointerType() ||
1738               FromType->isNullPtrType())) {
1739     // Boolean conversions (C++ 4.12).
1740     SCS.Second = ICK_Boolean_Conversion;
1741     FromType = S.Context.BoolTy;
1742   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1743              ToType->isIntegralType(S.Context)) {
1744     // Integral conversions (C++ 4.7).
1745     SCS.Second = ICK_Integral_Conversion;
1746     FromType = ToType.getUnqualifiedType();
1747   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1748     // Complex conversions (C99 6.3.1.6)
1749     SCS.Second = ICK_Complex_Conversion;
1750     FromType = ToType.getUnqualifiedType();
1751   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1752              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1753     // Complex-real conversions (C99 6.3.1.7)
1754     SCS.Second = ICK_Complex_Real;
1755     FromType = ToType.getUnqualifiedType();
1756   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1757     // FIXME: disable conversions between long double and __float128 if
1758     // their representation is different until there is back end support
1759     // We of course allow this conversion if long double is really double.
1760     if (&S.Context.getFloatTypeSemantics(FromType) !=
1761         &S.Context.getFloatTypeSemantics(ToType)) {
1762       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1763                                     ToType == S.Context.LongDoubleTy) ||
1764                                    (FromType == S.Context.LongDoubleTy &&
1765                                     ToType == S.Context.Float128Ty));
1766       if (Float128AndLongDouble &&
1767           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1768            &llvm::APFloat::PPCDoubleDouble()))
1769         return false;
1770     }
1771     // Floating point conversions (C++ 4.8).
1772     SCS.Second = ICK_Floating_Conversion;
1773     FromType = ToType.getUnqualifiedType();
1774   } else if ((FromType->isRealFloatingType() &&
1775               ToType->isIntegralType(S.Context)) ||
1776              (FromType->isIntegralOrUnscopedEnumerationType() &&
1777               ToType->isRealFloatingType())) {
1778     // Floating-integral conversions (C++ 4.9).
1779     SCS.Second = ICK_Floating_Integral;
1780     FromType = ToType.getUnqualifiedType();
1781   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1782     SCS.Second = ICK_Block_Pointer_Conversion;
1783   } else if (AllowObjCWritebackConversion &&
1784              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1785     SCS.Second = ICK_Writeback_Conversion;
1786   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1787                                    FromType, IncompatibleObjC)) {
1788     // Pointer conversions (C++ 4.10).
1789     SCS.Second = ICK_Pointer_Conversion;
1790     SCS.IncompatibleObjC = IncompatibleObjC;
1791     FromType = FromType.getUnqualifiedType();
1792   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1793                                          InOverloadResolution, FromType)) {
1794     // Pointer to member conversions (4.11).
1795     SCS.Second = ICK_Pointer_Member;
1796   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1797     SCS.Second = SecondICK;
1798     FromType = ToType.getUnqualifiedType();
1799   } else if (!S.getLangOpts().CPlusPlus &&
1800              S.Context.typesAreCompatible(ToType, FromType)) {
1801     // Compatible conversions (Clang extension for C function overloading)
1802     SCS.Second = ICK_Compatible_Conversion;
1803     FromType = ToType.getUnqualifiedType();
1804   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1805                                              InOverloadResolution,
1806                                              SCS, CStyle)) {
1807     SCS.Second = ICK_TransparentUnionConversion;
1808     FromType = ToType;
1809   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1810                                  CStyle)) {
1811     // tryAtomicConversion has updated the standard conversion sequence
1812     // appropriately.
1813     return true;
1814   } else if (ToType->isEventT() &&
1815              From->isIntegerConstantExpr(S.getASTContext()) &&
1816              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1817     SCS.Second = ICK_Zero_Event_Conversion;
1818     FromType = ToType;
1819   } else if (ToType->isQueueT() &&
1820              From->isIntegerConstantExpr(S.getASTContext()) &&
1821              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1822     SCS.Second = ICK_Zero_Queue_Conversion;
1823     FromType = ToType;
1824   } else {
1825     // No second conversion required.
1826     SCS.Second = ICK_Identity;
1827   }
1828   SCS.setToType(1, FromType);
1829 
1830   // The third conversion can be a function pointer conversion or a
1831   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1832   bool ObjCLifetimeConversion;
1833   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1834     // Function pointer conversions (removing 'noexcept') including removal of
1835     // 'noreturn' (Clang extension).
1836     SCS.Third = ICK_Function_Conversion;
1837   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1838                                          ObjCLifetimeConversion)) {
1839     SCS.Third = ICK_Qualification;
1840     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1841     FromType = ToType;
1842   } else {
1843     // No conversion required
1844     SCS.Third = ICK_Identity;
1845   }
1846 
1847   // C++ [over.best.ics]p6:
1848   //   [...] Any difference in top-level cv-qualification is
1849   //   subsumed by the initialization itself and does not constitute
1850   //   a conversion. [...]
1851   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1852   QualType CanonTo = S.Context.getCanonicalType(ToType);
1853   if (CanonFrom.getLocalUnqualifiedType()
1854                                      == CanonTo.getLocalUnqualifiedType() &&
1855       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1856     FromType = ToType;
1857     CanonFrom = CanonTo;
1858   }
1859 
1860   SCS.setToType(2, FromType);
1861 
1862   if (CanonFrom == CanonTo)
1863     return true;
1864 
1865   // If we have not converted the argument type to the parameter type,
1866   // this is a bad conversion sequence, unless we're resolving an overload in C.
1867   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1868     return false;
1869 
1870   ExprResult ER = ExprResult{From};
1871   Sema::AssignConvertType Conv =
1872       S.CheckSingleAssignmentConstraints(ToType, ER,
1873                                          /*Diagnose=*/false,
1874                                          /*DiagnoseCFAudited=*/false,
1875                                          /*ConvertRHS=*/false);
1876   ImplicitConversionKind SecondConv;
1877   switch (Conv) {
1878   case Sema::Compatible:
1879     SecondConv = ICK_C_Only_Conversion;
1880     break;
1881   // For our purposes, discarding qualifiers is just as bad as using an
1882   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1883   // qualifiers, as well.
1884   case Sema::CompatiblePointerDiscardsQualifiers:
1885   case Sema::IncompatiblePointer:
1886   case Sema::IncompatiblePointerSign:
1887     SecondConv = ICK_Incompatible_Pointer_Conversion;
1888     break;
1889   default:
1890     return false;
1891   }
1892 
1893   // First can only be an lvalue conversion, so we pretend that this was the
1894   // second conversion. First should already be valid from earlier in the
1895   // function.
1896   SCS.Second = SecondConv;
1897   SCS.setToType(1, ToType);
1898 
1899   // Third is Identity, because Second should rank us worse than any other
1900   // conversion. This could also be ICK_Qualification, but it's simpler to just
1901   // lump everything in with the second conversion, and we don't gain anything
1902   // from making this ICK_Qualification.
1903   SCS.Third = ICK_Identity;
1904   SCS.setToType(2, ToType);
1905   return true;
1906 }
1907 
1908 static bool
1909 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1910                                      QualType &ToType,
1911                                      bool InOverloadResolution,
1912                                      StandardConversionSequence &SCS,
1913                                      bool CStyle) {
1914 
1915   const RecordType *UT = ToType->getAsUnionType();
1916   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1917     return false;
1918   // The field to initialize within the transparent union.
1919   RecordDecl *UD = UT->getDecl();
1920   // It's compatible if the expression matches any of the fields.
1921   for (const auto *it : UD->fields()) {
1922     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1923                              CStyle, /*ObjCWritebackConversion=*/false)) {
1924       ToType = it->getType();
1925       return true;
1926     }
1927   }
1928   return false;
1929 }
1930 
1931 /// IsIntegralPromotion - Determines whether the conversion from the
1932 /// expression From (whose potentially-adjusted type is FromType) to
1933 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1934 /// sets PromotedType to the promoted type.
1935 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1936   const BuiltinType *To = ToType->getAs<BuiltinType>();
1937   // All integers are built-in.
1938   if (!To) {
1939     return false;
1940   }
1941 
1942   // An rvalue of type char, signed char, unsigned char, short int, or
1943   // unsigned short int can be converted to an rvalue of type int if
1944   // int can represent all the values of the source type; otherwise,
1945   // the source rvalue can be converted to an rvalue of type unsigned
1946   // int (C++ 4.5p1).
1947   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1948       !FromType->isEnumeralType()) {
1949     if (// We can promote any signed, promotable integer type to an int
1950         (FromType->isSignedIntegerType() ||
1951          // We can promote any unsigned integer type whose size is
1952          // less than int to an int.
1953          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1954       return To->getKind() == BuiltinType::Int;
1955     }
1956 
1957     return To->getKind() == BuiltinType::UInt;
1958   }
1959 
1960   // C++11 [conv.prom]p3:
1961   //   A prvalue of an unscoped enumeration type whose underlying type is not
1962   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1963   //   following types that can represent all the values of the enumeration
1964   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1965   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1966   //   long long int. If none of the types in that list can represent all the
1967   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1968   //   type can be converted to an rvalue a prvalue of the extended integer type
1969   //   with lowest integer conversion rank (4.13) greater than the rank of long
1970   //   long in which all the values of the enumeration can be represented. If
1971   //   there are two such extended types, the signed one is chosen.
1972   // C++11 [conv.prom]p4:
1973   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1974   //   can be converted to a prvalue of its underlying type. Moreover, if
1975   //   integral promotion can be applied to its underlying type, a prvalue of an
1976   //   unscoped enumeration type whose underlying type is fixed can also be
1977   //   converted to a prvalue of the promoted underlying type.
1978   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1979     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1980     // provided for a scoped enumeration.
1981     if (FromEnumType->getDecl()->isScoped())
1982       return false;
1983 
1984     // We can perform an integral promotion to the underlying type of the enum,
1985     // even if that's not the promoted type. Note that the check for promoting
1986     // the underlying type is based on the type alone, and does not consider
1987     // the bitfield-ness of the actual source expression.
1988     if (FromEnumType->getDecl()->isFixed()) {
1989       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1990       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1991              IsIntegralPromotion(nullptr, Underlying, ToType);
1992     }
1993 
1994     // We have already pre-calculated the promotion type, so this is trivial.
1995     if (ToType->isIntegerType() &&
1996         isCompleteType(From->getLocStart(), FromType))
1997       return Context.hasSameUnqualifiedType(
1998           ToType, FromEnumType->getDecl()->getPromotionType());
1999   }
2000 
2001   // C++0x [conv.prom]p2:
2002   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2003   //   to an rvalue a prvalue of the first of the following types that can
2004   //   represent all the values of its underlying type: int, unsigned int,
2005   //   long int, unsigned long int, long long int, or unsigned long long int.
2006   //   If none of the types in that list can represent all the values of its
2007   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2008   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2009   //   type.
2010   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2011       ToType->isIntegerType()) {
2012     // Determine whether the type we're converting from is signed or
2013     // unsigned.
2014     bool FromIsSigned = FromType->isSignedIntegerType();
2015     uint64_t FromSize = Context.getTypeSize(FromType);
2016 
2017     // The types we'll try to promote to, in the appropriate
2018     // order. Try each of these types.
2019     QualType PromoteTypes[6] = {
2020       Context.IntTy, Context.UnsignedIntTy,
2021       Context.LongTy, Context.UnsignedLongTy ,
2022       Context.LongLongTy, Context.UnsignedLongLongTy
2023     };
2024     for (int Idx = 0; Idx < 6; ++Idx) {
2025       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2026       if (FromSize < ToSize ||
2027           (FromSize == ToSize &&
2028            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2029         // We found the type that we can promote to. If this is the
2030         // type we wanted, we have a promotion. Otherwise, no
2031         // promotion.
2032         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2033       }
2034     }
2035   }
2036 
2037   // An rvalue for an integral bit-field (9.6) can be converted to an
2038   // rvalue of type int if int can represent all the values of the
2039   // bit-field; otherwise, it can be converted to unsigned int if
2040   // unsigned int can represent all the values of the bit-field. If
2041   // the bit-field is larger yet, no integral promotion applies to
2042   // it. If the bit-field has an enumerated type, it is treated as any
2043   // other value of that type for promotion purposes (C++ 4.5p3).
2044   // FIXME: We should delay checking of bit-fields until we actually perform the
2045   // conversion.
2046   if (From) {
2047     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2048       llvm::APSInt BitWidth;
2049       if (FromType->isIntegralType(Context) &&
2050           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2051         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2052         ToSize = Context.getTypeSize(ToType);
2053 
2054         // Are we promoting to an int from a bitfield that fits in an int?
2055         if (BitWidth < ToSize ||
2056             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2057           return To->getKind() == BuiltinType::Int;
2058         }
2059 
2060         // Are we promoting to an unsigned int from an unsigned bitfield
2061         // that fits into an unsigned int?
2062         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2063           return To->getKind() == BuiltinType::UInt;
2064         }
2065 
2066         return false;
2067       }
2068     }
2069   }
2070 
2071   // An rvalue of type bool can be converted to an rvalue of type int,
2072   // with false becoming zero and true becoming one (C++ 4.5p4).
2073   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2074     return true;
2075   }
2076 
2077   return false;
2078 }
2079 
2080 /// IsFloatingPointPromotion - Determines whether the conversion from
2081 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2082 /// returns true and sets PromotedType to the promoted type.
2083 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2084   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2085     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2086       /// An rvalue of type float can be converted to an rvalue of type
2087       /// double. (C++ 4.6p1).
2088       if (FromBuiltin->getKind() == BuiltinType::Float &&
2089           ToBuiltin->getKind() == BuiltinType::Double)
2090         return true;
2091 
2092       // C99 6.3.1.5p1:
2093       //   When a float is promoted to double or long double, or a
2094       //   double is promoted to long double [...].
2095       if (!getLangOpts().CPlusPlus &&
2096           (FromBuiltin->getKind() == BuiltinType::Float ||
2097            FromBuiltin->getKind() == BuiltinType::Double) &&
2098           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2099            ToBuiltin->getKind() == BuiltinType::Float128))
2100         return true;
2101 
2102       // Half can be promoted to float.
2103       if (!getLangOpts().NativeHalfType &&
2104            FromBuiltin->getKind() == BuiltinType::Half &&
2105           ToBuiltin->getKind() == BuiltinType::Float)
2106         return true;
2107     }
2108 
2109   return false;
2110 }
2111 
2112 /// \brief Determine if a conversion is a complex promotion.
2113 ///
2114 /// A complex promotion is defined as a complex -> complex conversion
2115 /// where the conversion between the underlying real types is a
2116 /// floating-point or integral promotion.
2117 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2118   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2119   if (!FromComplex)
2120     return false;
2121 
2122   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2123   if (!ToComplex)
2124     return false;
2125 
2126   return IsFloatingPointPromotion(FromComplex->getElementType(),
2127                                   ToComplex->getElementType()) ||
2128     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2129                         ToComplex->getElementType());
2130 }
2131 
2132 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2133 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2134 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2135 /// if non-empty, will be a pointer to ToType that may or may not have
2136 /// the right set of qualifiers on its pointee.
2137 ///
2138 static QualType
2139 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2140                                    QualType ToPointee, QualType ToType,
2141                                    ASTContext &Context,
2142                                    bool StripObjCLifetime = false) {
2143   assert((FromPtr->getTypeClass() == Type::Pointer ||
2144           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2145          "Invalid similarly-qualified pointer type");
2146 
2147   /// Conversions to 'id' subsume cv-qualifier conversions.
2148   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2149     return ToType.getUnqualifiedType();
2150 
2151   QualType CanonFromPointee
2152     = Context.getCanonicalType(FromPtr->getPointeeType());
2153   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2154   Qualifiers Quals = CanonFromPointee.getQualifiers();
2155 
2156   if (StripObjCLifetime)
2157     Quals.removeObjCLifetime();
2158 
2159   // Exact qualifier match -> return the pointer type we're converting to.
2160   if (CanonToPointee.getLocalQualifiers() == Quals) {
2161     // ToType is exactly what we need. Return it.
2162     if (!ToType.isNull())
2163       return ToType.getUnqualifiedType();
2164 
2165     // Build a pointer to ToPointee. It has the right qualifiers
2166     // already.
2167     if (isa<ObjCObjectPointerType>(ToType))
2168       return Context.getObjCObjectPointerType(ToPointee);
2169     return Context.getPointerType(ToPointee);
2170   }
2171 
2172   // Just build a canonical type that has the right qualifiers.
2173   QualType QualifiedCanonToPointee
2174     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2175 
2176   if (isa<ObjCObjectPointerType>(ToType))
2177     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2178   return Context.getPointerType(QualifiedCanonToPointee);
2179 }
2180 
2181 static bool isNullPointerConstantForConversion(Expr *Expr,
2182                                                bool InOverloadResolution,
2183                                                ASTContext &Context) {
2184   // Handle value-dependent integral null pointer constants correctly.
2185   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2186   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2187       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2188     return !InOverloadResolution;
2189 
2190   return Expr->isNullPointerConstant(Context,
2191                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2192                                         : Expr::NPC_ValueDependentIsNull);
2193 }
2194 
2195 /// IsPointerConversion - Determines whether the conversion of the
2196 /// expression From, which has the (possibly adjusted) type FromType,
2197 /// can be converted to the type ToType via a pointer conversion (C++
2198 /// 4.10). If so, returns true and places the converted type (that
2199 /// might differ from ToType in its cv-qualifiers at some level) into
2200 /// ConvertedType.
2201 ///
2202 /// This routine also supports conversions to and from block pointers
2203 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2204 /// pointers to interfaces. FIXME: Once we've determined the
2205 /// appropriate overloading rules for Objective-C, we may want to
2206 /// split the Objective-C checks into a different routine; however,
2207 /// GCC seems to consider all of these conversions to be pointer
2208 /// conversions, so for now they live here. IncompatibleObjC will be
2209 /// set if the conversion is an allowed Objective-C conversion that
2210 /// should result in a warning.
2211 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2212                                bool InOverloadResolution,
2213                                QualType& ConvertedType,
2214                                bool &IncompatibleObjC) {
2215   IncompatibleObjC = false;
2216   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2217                               IncompatibleObjC))
2218     return true;
2219 
2220   // Conversion from a null pointer constant to any Objective-C pointer type.
2221   if (ToType->isObjCObjectPointerType() &&
2222       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2223     ConvertedType = ToType;
2224     return true;
2225   }
2226 
2227   // Blocks: Block pointers can be converted to void*.
2228   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2229       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2230     ConvertedType = ToType;
2231     return true;
2232   }
2233   // Blocks: A null pointer constant can be converted to a block
2234   // pointer type.
2235   if (ToType->isBlockPointerType() &&
2236       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2237     ConvertedType = ToType;
2238     return true;
2239   }
2240 
2241   // If the left-hand-side is nullptr_t, the right side can be a null
2242   // pointer constant.
2243   if (ToType->isNullPtrType() &&
2244       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2245     ConvertedType = ToType;
2246     return true;
2247   }
2248 
2249   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2250   if (!ToTypePtr)
2251     return false;
2252 
2253   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2254   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258 
2259   // Beyond this point, both types need to be pointers
2260   // , including objective-c pointers.
2261   QualType ToPointeeType = ToTypePtr->getPointeeType();
2262   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2263       !getLangOpts().ObjCAutoRefCount) {
2264     ConvertedType = BuildSimilarlyQualifiedPointerType(
2265                                       FromType->getAs<ObjCObjectPointerType>(),
2266                                                        ToPointeeType,
2267                                                        ToType, Context);
2268     return true;
2269   }
2270   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2271   if (!FromTypePtr)
2272     return false;
2273 
2274   QualType FromPointeeType = FromTypePtr->getPointeeType();
2275 
2276   // If the unqualified pointee types are the same, this can't be a
2277   // pointer conversion, so don't do all of the work below.
2278   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2279     return false;
2280 
2281   // An rvalue of type "pointer to cv T," where T is an object type,
2282   // can be converted to an rvalue of type "pointer to cv void" (C++
2283   // 4.10p2).
2284   if (FromPointeeType->isIncompleteOrObjectType() &&
2285       ToPointeeType->isVoidType()) {
2286     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2287                                                        ToPointeeType,
2288                                                        ToType, Context,
2289                                                    /*StripObjCLifetime=*/true);
2290     return true;
2291   }
2292 
2293   // MSVC allows implicit function to void* type conversion.
2294   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2295       ToPointeeType->isVoidType()) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297                                                        ToPointeeType,
2298                                                        ToType, Context);
2299     return true;
2300   }
2301 
2302   // When we're overloading in C, we allow a special kind of pointer
2303   // conversion for compatible-but-not-identical pointee types.
2304   if (!getLangOpts().CPlusPlus &&
2305       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2306     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2307                                                        ToPointeeType,
2308                                                        ToType, Context);
2309     return true;
2310   }
2311 
2312   // C++ [conv.ptr]p3:
2313   //
2314   //   An rvalue of type "pointer to cv D," where D is a class type,
2315   //   can be converted to an rvalue of type "pointer to cv B," where
2316   //   B is a base class (clause 10) of D. If B is an inaccessible
2317   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2318   //   necessitates this conversion is ill-formed. The result of the
2319   //   conversion is a pointer to the base class sub-object of the
2320   //   derived class object. The null pointer value is converted to
2321   //   the null pointer value of the destination type.
2322   //
2323   // Note that we do not check for ambiguity or inaccessibility
2324   // here. That is handled by CheckPointerConversion.
2325   if (getLangOpts().CPlusPlus &&
2326       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2327       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2328       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2329     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2330                                                        ToPointeeType,
2331                                                        ToType, Context);
2332     return true;
2333   }
2334 
2335   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2336       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2337     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338                                                        ToPointeeType,
2339                                                        ToType, Context);
2340     return true;
2341   }
2342 
2343   return false;
2344 }
2345 
2346 /// \brief Adopt the given qualifiers for the given type.
2347 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2348   Qualifiers TQs = T.getQualifiers();
2349 
2350   // Check whether qualifiers already match.
2351   if (TQs == Qs)
2352     return T;
2353 
2354   if (Qs.compatiblyIncludes(TQs))
2355     return Context.getQualifiedType(T, Qs);
2356 
2357   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2358 }
2359 
2360 /// isObjCPointerConversion - Determines whether this is an
2361 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2362 /// with the same arguments and return values.
2363 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2364                                    QualType& ConvertedType,
2365                                    bool &IncompatibleObjC) {
2366   if (!getLangOpts().ObjC1)
2367     return false;
2368 
2369   // The set of qualifiers on the type we're converting from.
2370   Qualifiers FromQualifiers = FromType.getQualifiers();
2371 
2372   // First, we handle all conversions on ObjC object pointer types.
2373   const ObjCObjectPointerType* ToObjCPtr =
2374     ToType->getAs<ObjCObjectPointerType>();
2375   const ObjCObjectPointerType *FromObjCPtr =
2376     FromType->getAs<ObjCObjectPointerType>();
2377 
2378   if (ToObjCPtr && FromObjCPtr) {
2379     // If the pointee types are the same (ignoring qualifications),
2380     // then this is not a pointer conversion.
2381     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2382                                        FromObjCPtr->getPointeeType()))
2383       return false;
2384 
2385     // Conversion between Objective-C pointers.
2386     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2387       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2388       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2389       if (getLangOpts().CPlusPlus && LHS && RHS &&
2390           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2391                                                 FromObjCPtr->getPointeeType()))
2392         return false;
2393       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2394                                                    ToObjCPtr->getPointeeType(),
2395                                                          ToType, Context);
2396       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2397       return true;
2398     }
2399 
2400     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2401       // Okay: this is some kind of implicit downcast of Objective-C
2402       // interfaces, which is permitted. However, we're going to
2403       // complain about it.
2404       IncompatibleObjC = true;
2405       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2406                                                    ToObjCPtr->getPointeeType(),
2407                                                          ToType, Context);
2408       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2409       return true;
2410     }
2411   }
2412   // Beyond this point, both types need to be C pointers or block pointers.
2413   QualType ToPointeeType;
2414   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2415     ToPointeeType = ToCPtr->getPointeeType();
2416   else if (const BlockPointerType *ToBlockPtr =
2417             ToType->getAs<BlockPointerType>()) {
2418     // Objective C++: We're able to convert from a pointer to any object
2419     // to a block pointer type.
2420     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2421       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2422       return true;
2423     }
2424     ToPointeeType = ToBlockPtr->getPointeeType();
2425   }
2426   else if (FromType->getAs<BlockPointerType>() &&
2427            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2428     // Objective C++: We're able to convert from a block pointer type to a
2429     // pointer to any object.
2430     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2431     return true;
2432   }
2433   else
2434     return false;
2435 
2436   QualType FromPointeeType;
2437   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2438     FromPointeeType = FromCPtr->getPointeeType();
2439   else if (const BlockPointerType *FromBlockPtr =
2440            FromType->getAs<BlockPointerType>())
2441     FromPointeeType = FromBlockPtr->getPointeeType();
2442   else
2443     return false;
2444 
2445   // If we have pointers to pointers, recursively check whether this
2446   // is an Objective-C conversion.
2447   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2448       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2449                               IncompatibleObjC)) {
2450     // We always complain about this conversion.
2451     IncompatibleObjC = true;
2452     ConvertedType = Context.getPointerType(ConvertedType);
2453     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2454     return true;
2455   }
2456   // Allow conversion of pointee being objective-c pointer to another one;
2457   // as in I* to id.
2458   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2459       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2460       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2461                               IncompatibleObjC)) {
2462 
2463     ConvertedType = Context.getPointerType(ConvertedType);
2464     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2465     return true;
2466   }
2467 
2468   // If we have pointers to functions or blocks, check whether the only
2469   // differences in the argument and result types are in Objective-C
2470   // pointer conversions. If so, we permit the conversion (but
2471   // complain about it).
2472   const FunctionProtoType *FromFunctionType
2473     = FromPointeeType->getAs<FunctionProtoType>();
2474   const FunctionProtoType *ToFunctionType
2475     = ToPointeeType->getAs<FunctionProtoType>();
2476   if (FromFunctionType && ToFunctionType) {
2477     // If the function types are exactly the same, this isn't an
2478     // Objective-C pointer conversion.
2479     if (Context.getCanonicalType(FromPointeeType)
2480           == Context.getCanonicalType(ToPointeeType))
2481       return false;
2482 
2483     // Perform the quick checks that will tell us whether these
2484     // function types are obviously different.
2485     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2486         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2487         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2488       return false;
2489 
2490     bool HasObjCConversion = false;
2491     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2492         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2493       // Okay, the types match exactly. Nothing to do.
2494     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2495                                        ToFunctionType->getReturnType(),
2496                                        ConvertedType, IncompatibleObjC)) {
2497       // Okay, we have an Objective-C pointer conversion.
2498       HasObjCConversion = true;
2499     } else {
2500       // Function types are too different. Abort.
2501       return false;
2502     }
2503 
2504     // Check argument types.
2505     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2506          ArgIdx != NumArgs; ++ArgIdx) {
2507       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2508       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2509       if (Context.getCanonicalType(FromArgType)
2510             == Context.getCanonicalType(ToArgType)) {
2511         // Okay, the types match exactly. Nothing to do.
2512       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2513                                          ConvertedType, IncompatibleObjC)) {
2514         // Okay, we have an Objective-C pointer conversion.
2515         HasObjCConversion = true;
2516       } else {
2517         // Argument types are too different. Abort.
2518         return false;
2519       }
2520     }
2521 
2522     if (HasObjCConversion) {
2523       // We had an Objective-C conversion. Allow this pointer
2524       // conversion, but complain about it.
2525       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2526       IncompatibleObjC = true;
2527       return true;
2528     }
2529   }
2530 
2531   return false;
2532 }
2533 
2534 /// \brief Determine whether this is an Objective-C writeback conversion,
2535 /// used for parameter passing when performing automatic reference counting.
2536 ///
2537 /// \param FromType The type we're converting form.
2538 ///
2539 /// \param ToType The type we're converting to.
2540 ///
2541 /// \param ConvertedType The type that will be produced after applying
2542 /// this conversion.
2543 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2544                                      QualType &ConvertedType) {
2545   if (!getLangOpts().ObjCAutoRefCount ||
2546       Context.hasSameUnqualifiedType(FromType, ToType))
2547     return false;
2548 
2549   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2550   QualType ToPointee;
2551   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2552     ToPointee = ToPointer->getPointeeType();
2553   else
2554     return false;
2555 
2556   Qualifiers ToQuals = ToPointee.getQualifiers();
2557   if (!ToPointee->isObjCLifetimeType() ||
2558       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2559       !ToQuals.withoutObjCLifetime().empty())
2560     return false;
2561 
2562   // Argument must be a pointer to __strong to __weak.
2563   QualType FromPointee;
2564   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2565     FromPointee = FromPointer->getPointeeType();
2566   else
2567     return false;
2568 
2569   Qualifiers FromQuals = FromPointee.getQualifiers();
2570   if (!FromPointee->isObjCLifetimeType() ||
2571       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2572        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2573     return false;
2574 
2575   // Make sure that we have compatible qualifiers.
2576   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2577   if (!ToQuals.compatiblyIncludes(FromQuals))
2578     return false;
2579 
2580   // Remove qualifiers from the pointee type we're converting from; they
2581   // aren't used in the compatibility check belong, and we'll be adding back
2582   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2583   FromPointee = FromPointee.getUnqualifiedType();
2584 
2585   // The unqualified form of the pointee types must be compatible.
2586   ToPointee = ToPointee.getUnqualifiedType();
2587   bool IncompatibleObjC;
2588   if (Context.typesAreCompatible(FromPointee, ToPointee))
2589     FromPointee = ToPointee;
2590   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2591                                     IncompatibleObjC))
2592     return false;
2593 
2594   /// \brief Construct the type we're converting to, which is a pointer to
2595   /// __autoreleasing pointee.
2596   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2597   ConvertedType = Context.getPointerType(FromPointee);
2598   return true;
2599 }
2600 
2601 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2602                                     QualType& ConvertedType) {
2603   QualType ToPointeeType;
2604   if (const BlockPointerType *ToBlockPtr =
2605         ToType->getAs<BlockPointerType>())
2606     ToPointeeType = ToBlockPtr->getPointeeType();
2607   else
2608     return false;
2609 
2610   QualType FromPointeeType;
2611   if (const BlockPointerType *FromBlockPtr =
2612       FromType->getAs<BlockPointerType>())
2613     FromPointeeType = FromBlockPtr->getPointeeType();
2614   else
2615     return false;
2616   // We have pointer to blocks, check whether the only
2617   // differences in the argument and result types are in Objective-C
2618   // pointer conversions. If so, we permit the conversion.
2619 
2620   const FunctionProtoType *FromFunctionType
2621     = FromPointeeType->getAs<FunctionProtoType>();
2622   const FunctionProtoType *ToFunctionType
2623     = ToPointeeType->getAs<FunctionProtoType>();
2624 
2625   if (!FromFunctionType || !ToFunctionType)
2626     return false;
2627 
2628   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2629     return true;
2630 
2631   // Perform the quick checks that will tell us whether these
2632   // function types are obviously different.
2633   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2634       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2635     return false;
2636 
2637   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2638   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2639   if (FromEInfo != ToEInfo)
2640     return false;
2641 
2642   bool IncompatibleObjC = false;
2643   if (Context.hasSameType(FromFunctionType->getReturnType(),
2644                           ToFunctionType->getReturnType())) {
2645     // Okay, the types match exactly. Nothing to do.
2646   } else {
2647     QualType RHS = FromFunctionType->getReturnType();
2648     QualType LHS = ToFunctionType->getReturnType();
2649     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2650         !RHS.hasQualifiers() && LHS.hasQualifiers())
2651        LHS = LHS.getUnqualifiedType();
2652 
2653      if (Context.hasSameType(RHS,LHS)) {
2654        // OK exact match.
2655      } else if (isObjCPointerConversion(RHS, LHS,
2656                                         ConvertedType, IncompatibleObjC)) {
2657      if (IncompatibleObjC)
2658        return false;
2659      // Okay, we have an Objective-C pointer conversion.
2660      }
2661      else
2662        return false;
2663    }
2664 
2665    // Check argument types.
2666    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2667         ArgIdx != NumArgs; ++ArgIdx) {
2668      IncompatibleObjC = false;
2669      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2670      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2671      if (Context.hasSameType(FromArgType, ToArgType)) {
2672        // Okay, the types match exactly. Nothing to do.
2673      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2674                                         ConvertedType, IncompatibleObjC)) {
2675        if (IncompatibleObjC)
2676          return false;
2677        // Okay, we have an Objective-C pointer conversion.
2678      } else
2679        // Argument types are too different. Abort.
2680        return false;
2681    }
2682 
2683    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2684    bool CanUseToFPT, CanUseFromFPT;
2685    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2686                                       CanUseToFPT, CanUseFromFPT,
2687                                       NewParamInfos))
2688      return false;
2689 
2690    ConvertedType = ToType;
2691    return true;
2692 }
2693 
2694 enum {
2695   ft_default,
2696   ft_different_class,
2697   ft_parameter_arity,
2698   ft_parameter_mismatch,
2699   ft_return_type,
2700   ft_qualifer_mismatch,
2701   ft_noexcept
2702 };
2703 
2704 /// Attempts to get the FunctionProtoType from a Type. Handles
2705 /// MemberFunctionPointers properly.
2706 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2707   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2708     return FPT;
2709 
2710   if (auto *MPT = FromType->getAs<MemberPointerType>())
2711     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2712 
2713   return nullptr;
2714 }
2715 
2716 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2717 /// function types.  Catches different number of parameter, mismatch in
2718 /// parameter types, and different return types.
2719 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2720                                       QualType FromType, QualType ToType) {
2721   // If either type is not valid, include no extra info.
2722   if (FromType.isNull() || ToType.isNull()) {
2723     PDiag << ft_default;
2724     return;
2725   }
2726 
2727   // Get the function type from the pointers.
2728   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2729     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2730                             *ToMember = ToType->getAs<MemberPointerType>();
2731     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2732       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2733             << QualType(FromMember->getClass(), 0);
2734       return;
2735     }
2736     FromType = FromMember->getPointeeType();
2737     ToType = ToMember->getPointeeType();
2738   }
2739 
2740   if (FromType->isPointerType())
2741     FromType = FromType->getPointeeType();
2742   if (ToType->isPointerType())
2743     ToType = ToType->getPointeeType();
2744 
2745   // Remove references.
2746   FromType = FromType.getNonReferenceType();
2747   ToType = ToType.getNonReferenceType();
2748 
2749   // Don't print extra info for non-specialized template functions.
2750   if (FromType->isInstantiationDependentType() &&
2751       !FromType->getAs<TemplateSpecializationType>()) {
2752     PDiag << ft_default;
2753     return;
2754   }
2755 
2756   // No extra info for same types.
2757   if (Context.hasSameType(FromType, ToType)) {
2758     PDiag << ft_default;
2759     return;
2760   }
2761 
2762   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2763                           *ToFunction = tryGetFunctionProtoType(ToType);
2764 
2765   // Both types need to be function types.
2766   if (!FromFunction || !ToFunction) {
2767     PDiag << ft_default;
2768     return;
2769   }
2770 
2771   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2772     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2773           << FromFunction->getNumParams();
2774     return;
2775   }
2776 
2777   // Handle different parameter types.
2778   unsigned ArgPos;
2779   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2780     PDiag << ft_parameter_mismatch << ArgPos + 1
2781           << ToFunction->getParamType(ArgPos)
2782           << FromFunction->getParamType(ArgPos);
2783     return;
2784   }
2785 
2786   // Handle different return type.
2787   if (!Context.hasSameType(FromFunction->getReturnType(),
2788                            ToFunction->getReturnType())) {
2789     PDiag << ft_return_type << ToFunction->getReturnType()
2790           << FromFunction->getReturnType();
2791     return;
2792   }
2793 
2794   unsigned FromQuals = FromFunction->getTypeQuals(),
2795            ToQuals = ToFunction->getTypeQuals();
2796   if (FromQuals != ToQuals) {
2797     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2798     return;
2799   }
2800 
2801   // Handle exception specification differences on canonical type (in C++17
2802   // onwards).
2803   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2804           ->isNothrow(Context) !=
2805       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2806           ->isNothrow(Context)) {
2807     PDiag << ft_noexcept;
2808     return;
2809   }
2810 
2811   // Unable to find a difference, so add no extra info.
2812   PDiag << ft_default;
2813 }
2814 
2815 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2816 /// for equality of their argument types. Caller has already checked that
2817 /// they have same number of arguments.  If the parameters are different,
2818 /// ArgPos will have the parameter index of the first different parameter.
2819 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2820                                       const FunctionProtoType *NewType,
2821                                       unsigned *ArgPos) {
2822   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2823                                               N = NewType->param_type_begin(),
2824                                               E = OldType->param_type_end();
2825        O && (O != E); ++O, ++N) {
2826     if (!Context.hasSameType(O->getUnqualifiedType(),
2827                              N->getUnqualifiedType())) {
2828       if (ArgPos)
2829         *ArgPos = O - OldType->param_type_begin();
2830       return false;
2831     }
2832   }
2833   return true;
2834 }
2835 
2836 /// CheckPointerConversion - Check the pointer conversion from the
2837 /// expression From to the type ToType. This routine checks for
2838 /// ambiguous or inaccessible derived-to-base pointer
2839 /// conversions for which IsPointerConversion has already returned
2840 /// true. It returns true and produces a diagnostic if there was an
2841 /// error, or returns false otherwise.
2842 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2843                                   CastKind &Kind,
2844                                   CXXCastPath& BasePath,
2845                                   bool IgnoreBaseAccess,
2846                                   bool Diagnose) {
2847   QualType FromType = From->getType();
2848   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2849 
2850   Kind = CK_BitCast;
2851 
2852   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2853       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2854           Expr::NPCK_ZeroExpression) {
2855     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2856       DiagRuntimeBehavior(From->getExprLoc(), From,
2857                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2858                             << ToType << From->getSourceRange());
2859     else if (!isUnevaluatedContext())
2860       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2861         << ToType << From->getSourceRange();
2862   }
2863   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2864     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2865       QualType FromPointeeType = FromPtrType->getPointeeType(),
2866                ToPointeeType   = ToPtrType->getPointeeType();
2867 
2868       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2869           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2870         // We must have a derived-to-base conversion. Check an
2871         // ambiguous or inaccessible conversion.
2872         unsigned InaccessibleID = 0;
2873         unsigned AmbigiousID = 0;
2874         if (Diagnose) {
2875           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2876           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2877         }
2878         if (CheckDerivedToBaseConversion(
2879                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2880                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2881                 &BasePath, IgnoreBaseAccess))
2882           return true;
2883 
2884         // The conversion was successful.
2885         Kind = CK_DerivedToBase;
2886       }
2887 
2888       if (Diagnose && !IsCStyleOrFunctionalCast &&
2889           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2890         assert(getLangOpts().MSVCCompat &&
2891                "this should only be possible with MSVCCompat!");
2892         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2893             << From->getSourceRange();
2894       }
2895     }
2896   } else if (const ObjCObjectPointerType *ToPtrType =
2897                ToType->getAs<ObjCObjectPointerType>()) {
2898     if (const ObjCObjectPointerType *FromPtrType =
2899           FromType->getAs<ObjCObjectPointerType>()) {
2900       // Objective-C++ conversions are always okay.
2901       // FIXME: We should have a different class of conversions for the
2902       // Objective-C++ implicit conversions.
2903       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2904         return false;
2905     } else if (FromType->isBlockPointerType()) {
2906       Kind = CK_BlockPointerToObjCPointerCast;
2907     } else {
2908       Kind = CK_CPointerToObjCPointerCast;
2909     }
2910   } else if (ToType->isBlockPointerType()) {
2911     if (!FromType->isBlockPointerType())
2912       Kind = CK_AnyPointerToBlockPointerCast;
2913   }
2914 
2915   // We shouldn't fall into this case unless it's valid for other
2916   // reasons.
2917   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2918     Kind = CK_NullToPointer;
2919 
2920   return false;
2921 }
2922 
2923 /// IsMemberPointerConversion - Determines whether the conversion of the
2924 /// expression From, which has the (possibly adjusted) type FromType, can be
2925 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2926 /// If so, returns true and places the converted type (that might differ from
2927 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2928 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2929                                      QualType ToType,
2930                                      bool InOverloadResolution,
2931                                      QualType &ConvertedType) {
2932   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2933   if (!ToTypePtr)
2934     return false;
2935 
2936   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2937   if (From->isNullPointerConstant(Context,
2938                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2939                                         : Expr::NPC_ValueDependentIsNull)) {
2940     ConvertedType = ToType;
2941     return true;
2942   }
2943 
2944   // Otherwise, both types have to be member pointers.
2945   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2946   if (!FromTypePtr)
2947     return false;
2948 
2949   // A pointer to member of B can be converted to a pointer to member of D,
2950   // where D is derived from B (C++ 4.11p2).
2951   QualType FromClass(FromTypePtr->getClass(), 0);
2952   QualType ToClass(ToTypePtr->getClass(), 0);
2953 
2954   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2955       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2956     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2957                                                  ToClass.getTypePtr());
2958     return true;
2959   }
2960 
2961   return false;
2962 }
2963 
2964 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2965 /// expression From to the type ToType. This routine checks for ambiguous or
2966 /// virtual or inaccessible base-to-derived member pointer conversions
2967 /// for which IsMemberPointerConversion has already returned true. It returns
2968 /// true and produces a diagnostic if there was an error, or returns false
2969 /// otherwise.
2970 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2971                                         CastKind &Kind,
2972                                         CXXCastPath &BasePath,
2973                                         bool IgnoreBaseAccess) {
2974   QualType FromType = From->getType();
2975   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2976   if (!FromPtrType) {
2977     // This must be a null pointer to member pointer conversion
2978     assert(From->isNullPointerConstant(Context,
2979                                        Expr::NPC_ValueDependentIsNull) &&
2980            "Expr must be null pointer constant!");
2981     Kind = CK_NullToMemberPointer;
2982     return false;
2983   }
2984 
2985   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2986   assert(ToPtrType && "No member pointer cast has a target type "
2987                       "that is not a member pointer.");
2988 
2989   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2990   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2991 
2992   // FIXME: What about dependent types?
2993   assert(FromClass->isRecordType() && "Pointer into non-class.");
2994   assert(ToClass->isRecordType() && "Pointer into non-class.");
2995 
2996   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2997                      /*DetectVirtual=*/true);
2998   bool DerivationOkay =
2999       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3000   assert(DerivationOkay &&
3001          "Should not have been called if derivation isn't OK.");
3002   (void)DerivationOkay;
3003 
3004   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3005                                   getUnqualifiedType())) {
3006     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3007     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3008       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3009     return true;
3010   }
3011 
3012   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3013     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3014       << FromClass << ToClass << QualType(VBase, 0)
3015       << From->getSourceRange();
3016     return true;
3017   }
3018 
3019   if (!IgnoreBaseAccess)
3020     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3021                          Paths.front(),
3022                          diag::err_downcast_from_inaccessible_base);
3023 
3024   // Must be a base to derived member conversion.
3025   BuildBasePathArray(Paths, BasePath);
3026   Kind = CK_BaseToDerivedMemberPointer;
3027   return false;
3028 }
3029 
3030 /// Determine whether the lifetime conversion between the two given
3031 /// qualifiers sets is nontrivial.
3032 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3033                                                Qualifiers ToQuals) {
3034   // Converting anything to const __unsafe_unretained is trivial.
3035   if (ToQuals.hasConst() &&
3036       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3037     return false;
3038 
3039   return true;
3040 }
3041 
3042 /// IsQualificationConversion - Determines whether the conversion from
3043 /// an rvalue of type FromType to ToType is a qualification conversion
3044 /// (C++ 4.4).
3045 ///
3046 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3047 /// when the qualification conversion involves a change in the Objective-C
3048 /// object lifetime.
3049 bool
3050 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3051                                 bool CStyle, bool &ObjCLifetimeConversion) {
3052   FromType = Context.getCanonicalType(FromType);
3053   ToType = Context.getCanonicalType(ToType);
3054   ObjCLifetimeConversion = false;
3055 
3056   // If FromType and ToType are the same type, this is not a
3057   // qualification conversion.
3058   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3059     return false;
3060 
3061   // (C++ 4.4p4):
3062   //   A conversion can add cv-qualifiers at levels other than the first
3063   //   in multi-level pointers, subject to the following rules: [...]
3064   bool PreviousToQualsIncludeConst = true;
3065   bool UnwrappedAnyPointer = false;
3066   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3067     // Within each iteration of the loop, we check the qualifiers to
3068     // determine if this still looks like a qualification
3069     // conversion. Then, if all is well, we unwrap one more level of
3070     // pointers or pointers-to-members and do it all again
3071     // until there are no more pointers or pointers-to-members left to
3072     // unwrap.
3073     UnwrappedAnyPointer = true;
3074 
3075     Qualifiers FromQuals = FromType.getQualifiers();
3076     Qualifiers ToQuals = ToType.getQualifiers();
3077 
3078     // Ignore __unaligned qualifier if this type is void.
3079     if (ToType.getUnqualifiedType()->isVoidType())
3080       FromQuals.removeUnaligned();
3081 
3082     // Objective-C ARC:
3083     //   Check Objective-C lifetime conversions.
3084     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3085         UnwrappedAnyPointer) {
3086       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3087         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3088           ObjCLifetimeConversion = true;
3089         FromQuals.removeObjCLifetime();
3090         ToQuals.removeObjCLifetime();
3091       } else {
3092         // Qualification conversions cannot cast between different
3093         // Objective-C lifetime qualifiers.
3094         return false;
3095       }
3096     }
3097 
3098     // Allow addition/removal of GC attributes but not changing GC attributes.
3099     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3100         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3101       FromQuals.removeObjCGCAttr();
3102       ToQuals.removeObjCGCAttr();
3103     }
3104 
3105     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3106     //      2,j, and similarly for volatile.
3107     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3108       return false;
3109 
3110     //   -- if the cv 1,j and cv 2,j are different, then const is in
3111     //      every cv for 0 < k < j.
3112     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3113         && !PreviousToQualsIncludeConst)
3114       return false;
3115 
3116     // Keep track of whether all prior cv-qualifiers in the "to" type
3117     // include const.
3118     PreviousToQualsIncludeConst
3119       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3120   }
3121 
3122   // We are left with FromType and ToType being the pointee types
3123   // after unwrapping the original FromType and ToType the same number
3124   // of types. If we unwrapped any pointers, and if FromType and
3125   // ToType have the same unqualified type (since we checked
3126   // qualifiers above), then this is a qualification conversion.
3127   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3128 }
3129 
3130 /// \brief - Determine whether this is a conversion from a scalar type to an
3131 /// atomic type.
3132 ///
3133 /// If successful, updates \c SCS's second and third steps in the conversion
3134 /// sequence to finish the conversion.
3135 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3136                                 bool InOverloadResolution,
3137                                 StandardConversionSequence &SCS,
3138                                 bool CStyle) {
3139   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3140   if (!ToAtomic)
3141     return false;
3142 
3143   StandardConversionSequence InnerSCS;
3144   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3145                             InOverloadResolution, InnerSCS,
3146                             CStyle, /*AllowObjCWritebackConversion=*/false))
3147     return false;
3148 
3149   SCS.Second = InnerSCS.Second;
3150   SCS.setToType(1, InnerSCS.getToType(1));
3151   SCS.Third = InnerSCS.Third;
3152   SCS.QualificationIncludesObjCLifetime
3153     = InnerSCS.QualificationIncludesObjCLifetime;
3154   SCS.setToType(2, InnerSCS.getToType(2));
3155   return true;
3156 }
3157 
3158 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3159                                               CXXConstructorDecl *Constructor,
3160                                               QualType Type) {
3161   const FunctionProtoType *CtorType =
3162       Constructor->getType()->getAs<FunctionProtoType>();
3163   if (CtorType->getNumParams() > 0) {
3164     QualType FirstArg = CtorType->getParamType(0);
3165     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3166       return true;
3167   }
3168   return false;
3169 }
3170 
3171 static OverloadingResult
3172 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3173                                        CXXRecordDecl *To,
3174                                        UserDefinedConversionSequence &User,
3175                                        OverloadCandidateSet &CandidateSet,
3176                                        bool AllowExplicit) {
3177   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3178   for (auto *D : S.LookupConstructors(To)) {
3179     auto Info = getConstructorInfo(D);
3180     if (!Info)
3181       continue;
3182 
3183     bool Usable = !Info.Constructor->isInvalidDecl() &&
3184                   S.isInitListConstructor(Info.Constructor) &&
3185                   (AllowExplicit || !Info.Constructor->isExplicit());
3186     if (Usable) {
3187       // If the first argument is (a reference to) the target type,
3188       // suppress conversions.
3189       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190           S.Context, Info.Constructor, ToType);
3191       if (Info.ConstructorTmpl)
3192         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3193                                        /*ExplicitArgs*/ nullptr, From,
3194                                        CandidateSet, SuppressUserConversions);
3195       else
3196         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3197                                CandidateSet, SuppressUserConversions);
3198     }
3199   }
3200 
3201   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3202 
3203   OverloadCandidateSet::iterator Best;
3204   switch (auto Result =
3205             CandidateSet.BestViableFunction(S, From->getLocStart(),
3206                                             Best)) {
3207   case OR_Deleted:
3208   case OR_Success: {
3209     // Record the standard conversion we used and the conversion function.
3210     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3211     QualType ThisType = Constructor->getThisType(S.Context);
3212     // Initializer lists don't have conversions as such.
3213     User.Before.setAsIdentityConversion();
3214     User.HadMultipleCandidates = HadMultipleCandidates;
3215     User.ConversionFunction = Constructor;
3216     User.FoundConversionFunction = Best->FoundDecl;
3217     User.After.setAsIdentityConversion();
3218     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3219     User.After.setAllToTypes(ToType);
3220     return Result;
3221   }
3222 
3223   case OR_No_Viable_Function:
3224     return OR_No_Viable_Function;
3225   case OR_Ambiguous:
3226     return OR_Ambiguous;
3227   }
3228 
3229   llvm_unreachable("Invalid OverloadResult!");
3230 }
3231 
3232 /// Determines whether there is a user-defined conversion sequence
3233 /// (C++ [over.ics.user]) that converts expression From to the type
3234 /// ToType. If such a conversion exists, User will contain the
3235 /// user-defined conversion sequence that performs such a conversion
3236 /// and this routine will return true. Otherwise, this routine returns
3237 /// false and User is unspecified.
3238 ///
3239 /// \param AllowExplicit  true if the conversion should consider C++0x
3240 /// "explicit" conversion functions as well as non-explicit conversion
3241 /// functions (C++0x [class.conv.fct]p2).
3242 ///
3243 /// \param AllowObjCConversionOnExplicit true if the conversion should
3244 /// allow an extra Objective-C pointer conversion on uses of explicit
3245 /// constructors. Requires \c AllowExplicit to also be set.
3246 static OverloadingResult
3247 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3248                         UserDefinedConversionSequence &User,
3249                         OverloadCandidateSet &CandidateSet,
3250                         bool AllowExplicit,
3251                         bool AllowObjCConversionOnExplicit) {
3252   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3253   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3254 
3255   // Whether we will only visit constructors.
3256   bool ConstructorsOnly = false;
3257 
3258   // If the type we are conversion to is a class type, enumerate its
3259   // constructors.
3260   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3261     // C++ [over.match.ctor]p1:
3262     //   When objects of class type are direct-initialized (8.5), or
3263     //   copy-initialized from an expression of the same or a
3264     //   derived class type (8.5), overload resolution selects the
3265     //   constructor. [...] For copy-initialization, the candidate
3266     //   functions are all the converting constructors (12.3.1) of
3267     //   that class. The argument list is the expression-list within
3268     //   the parentheses of the initializer.
3269     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3270         (From->getType()->getAs<RecordType>() &&
3271          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3272       ConstructorsOnly = true;
3273 
3274     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3275       // We're not going to find any constructors.
3276     } else if (CXXRecordDecl *ToRecordDecl
3277                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3278 
3279       Expr **Args = &From;
3280       unsigned NumArgs = 1;
3281       bool ListInitializing = false;
3282       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3283         // But first, see if there is an init-list-constructor that will work.
3284         OverloadingResult Result = IsInitializerListConstructorConversion(
3285             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3286         if (Result != OR_No_Viable_Function)
3287           return Result;
3288         // Never mind.
3289         CandidateSet.clear(
3290             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3291 
3292         // If we're list-initializing, we pass the individual elements as
3293         // arguments, not the entire list.
3294         Args = InitList->getInits();
3295         NumArgs = InitList->getNumInits();
3296         ListInitializing = true;
3297       }
3298 
3299       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3300         auto Info = getConstructorInfo(D);
3301         if (!Info)
3302           continue;
3303 
3304         bool Usable = !Info.Constructor->isInvalidDecl();
3305         if (ListInitializing)
3306           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3307         else
3308           Usable = Usable &&
3309                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3310         if (Usable) {
3311           bool SuppressUserConversions = !ConstructorsOnly;
3312           if (SuppressUserConversions && ListInitializing) {
3313             SuppressUserConversions = false;
3314             if (NumArgs == 1) {
3315               // If the first argument is (a reference to) the target type,
3316               // suppress conversions.
3317               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3318                   S.Context, Info.Constructor, ToType);
3319             }
3320           }
3321           if (Info.ConstructorTmpl)
3322             S.AddTemplateOverloadCandidate(
3323                 Info.ConstructorTmpl, Info.FoundDecl,
3324                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3325                 CandidateSet, SuppressUserConversions);
3326           else
3327             // Allow one user-defined conversion when user specifies a
3328             // From->ToType conversion via an static cast (c-style, etc).
3329             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3330                                    llvm::makeArrayRef(Args, NumArgs),
3331                                    CandidateSet, SuppressUserConversions);
3332         }
3333       }
3334     }
3335   }
3336 
3337   // Enumerate conversion functions, if we're allowed to.
3338   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3339   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3340     // No conversion functions from incomplete types.
3341   } else if (const RecordType *FromRecordType
3342                                    = From->getType()->getAs<RecordType>()) {
3343     if (CXXRecordDecl *FromRecordDecl
3344          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3345       // Add all of the conversion functions as candidates.
3346       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3347       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3348         DeclAccessPair FoundDecl = I.getPair();
3349         NamedDecl *D = FoundDecl.getDecl();
3350         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3351         if (isa<UsingShadowDecl>(D))
3352           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3353 
3354         CXXConversionDecl *Conv;
3355         FunctionTemplateDecl *ConvTemplate;
3356         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3357           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3358         else
3359           Conv = cast<CXXConversionDecl>(D);
3360 
3361         if (AllowExplicit || !Conv->isExplicit()) {
3362           if (ConvTemplate)
3363             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3364                                              ActingContext, From, ToType,
3365                                              CandidateSet,
3366                                              AllowObjCConversionOnExplicit);
3367           else
3368             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3369                                      From, ToType, CandidateSet,
3370                                      AllowObjCConversionOnExplicit);
3371         }
3372       }
3373     }
3374   }
3375 
3376   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3377 
3378   OverloadCandidateSet::iterator Best;
3379   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3380                                                         Best)) {
3381   case OR_Success:
3382   case OR_Deleted:
3383     // Record the standard conversion we used and the conversion function.
3384     if (CXXConstructorDecl *Constructor
3385           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3386       // C++ [over.ics.user]p1:
3387       //   If the user-defined conversion is specified by a
3388       //   constructor (12.3.1), the initial standard conversion
3389       //   sequence converts the source type to the type required by
3390       //   the argument of the constructor.
3391       //
3392       QualType ThisType = Constructor->getThisType(S.Context);
3393       if (isa<InitListExpr>(From)) {
3394         // Initializer lists don't have conversions as such.
3395         User.Before.setAsIdentityConversion();
3396       } else {
3397         if (Best->Conversions[0].isEllipsis())
3398           User.EllipsisConversion = true;
3399         else {
3400           User.Before = Best->Conversions[0].Standard;
3401           User.EllipsisConversion = false;
3402         }
3403       }
3404       User.HadMultipleCandidates = HadMultipleCandidates;
3405       User.ConversionFunction = Constructor;
3406       User.FoundConversionFunction = Best->FoundDecl;
3407       User.After.setAsIdentityConversion();
3408       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3409       User.After.setAllToTypes(ToType);
3410       return Result;
3411     }
3412     if (CXXConversionDecl *Conversion
3413                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3414       // C++ [over.ics.user]p1:
3415       //
3416       //   [...] If the user-defined conversion is specified by a
3417       //   conversion function (12.3.2), the initial standard
3418       //   conversion sequence converts the source type to the
3419       //   implicit object parameter of the conversion function.
3420       User.Before = Best->Conversions[0].Standard;
3421       User.HadMultipleCandidates = HadMultipleCandidates;
3422       User.ConversionFunction = Conversion;
3423       User.FoundConversionFunction = Best->FoundDecl;
3424       User.EllipsisConversion = false;
3425 
3426       // C++ [over.ics.user]p2:
3427       //   The second standard conversion sequence converts the
3428       //   result of the user-defined conversion to the target type
3429       //   for the sequence. Since an implicit conversion sequence
3430       //   is an initialization, the special rules for
3431       //   initialization by user-defined conversion apply when
3432       //   selecting the best user-defined conversion for a
3433       //   user-defined conversion sequence (see 13.3.3 and
3434       //   13.3.3.1).
3435       User.After = Best->FinalConversion;
3436       return Result;
3437     }
3438     llvm_unreachable("Not a constructor or conversion function?");
3439 
3440   case OR_No_Viable_Function:
3441     return OR_No_Viable_Function;
3442 
3443   case OR_Ambiguous:
3444     return OR_Ambiguous;
3445   }
3446 
3447   llvm_unreachable("Invalid OverloadResult!");
3448 }
3449 
3450 bool
3451 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3452   ImplicitConversionSequence ICS;
3453   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3454                                     OverloadCandidateSet::CSK_Normal);
3455   OverloadingResult OvResult =
3456     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3457                             CandidateSet, false, false);
3458   if (OvResult == OR_Ambiguous)
3459     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3460         << From->getType() << ToType << From->getSourceRange();
3461   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3462     if (!RequireCompleteType(From->getLocStart(), ToType,
3463                              diag::err_typecheck_nonviable_condition_incomplete,
3464                              From->getType(), From->getSourceRange()))
3465       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3466           << false << From->getType() << From->getSourceRange() << ToType;
3467   } else
3468     return false;
3469   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3470   return true;
3471 }
3472 
3473 /// \brief Compare the user-defined conversion functions or constructors
3474 /// of two user-defined conversion sequences to determine whether any ordering
3475 /// is possible.
3476 static ImplicitConversionSequence::CompareKind
3477 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3478                            FunctionDecl *Function2) {
3479   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3480     return ImplicitConversionSequence::Indistinguishable;
3481 
3482   // Objective-C++:
3483   //   If both conversion functions are implicitly-declared conversions from
3484   //   a lambda closure type to a function pointer and a block pointer,
3485   //   respectively, always prefer the conversion to a function pointer,
3486   //   because the function pointer is more lightweight and is more likely
3487   //   to keep code working.
3488   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3489   if (!Conv1)
3490     return ImplicitConversionSequence::Indistinguishable;
3491 
3492   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3493   if (!Conv2)
3494     return ImplicitConversionSequence::Indistinguishable;
3495 
3496   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3497     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3498     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3499     if (Block1 != Block2)
3500       return Block1 ? ImplicitConversionSequence::Worse
3501                     : ImplicitConversionSequence::Better;
3502   }
3503 
3504   return ImplicitConversionSequence::Indistinguishable;
3505 }
3506 
3507 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3508     const ImplicitConversionSequence &ICS) {
3509   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3510          (ICS.isUserDefined() &&
3511           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3512 }
3513 
3514 /// CompareImplicitConversionSequences - Compare two implicit
3515 /// conversion sequences to determine whether one is better than the
3516 /// other or if they are indistinguishable (C++ 13.3.3.2).
3517 static ImplicitConversionSequence::CompareKind
3518 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3519                                    const ImplicitConversionSequence& ICS1,
3520                                    const ImplicitConversionSequence& ICS2)
3521 {
3522   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3523   // conversion sequences (as defined in 13.3.3.1)
3524   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3525   //      conversion sequence than a user-defined conversion sequence or
3526   //      an ellipsis conversion sequence, and
3527   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3528   //      conversion sequence than an ellipsis conversion sequence
3529   //      (13.3.3.1.3).
3530   //
3531   // C++0x [over.best.ics]p10:
3532   //   For the purpose of ranking implicit conversion sequences as
3533   //   described in 13.3.3.2, the ambiguous conversion sequence is
3534   //   treated as a user-defined sequence that is indistinguishable
3535   //   from any other user-defined conversion sequence.
3536 
3537   // String literal to 'char *' conversion has been deprecated in C++03. It has
3538   // been removed from C++11. We still accept this conversion, if it happens at
3539   // the best viable function. Otherwise, this conversion is considered worse
3540   // than ellipsis conversion. Consider this as an extension; this is not in the
3541   // standard. For example:
3542   //
3543   // int &f(...);    // #1
3544   // void f(char*);  // #2
3545   // void g() { int &r = f("foo"); }
3546   //
3547   // In C++03, we pick #2 as the best viable function.
3548   // In C++11, we pick #1 as the best viable function, because ellipsis
3549   // conversion is better than string-literal to char* conversion (since there
3550   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3551   // convert arguments, #2 would be the best viable function in C++11.
3552   // If the best viable function has this conversion, a warning will be issued
3553   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3554 
3555   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3556       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3557       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3558     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3559                ? ImplicitConversionSequence::Worse
3560                : ImplicitConversionSequence::Better;
3561 
3562   if (ICS1.getKindRank() < ICS2.getKindRank())
3563     return ImplicitConversionSequence::Better;
3564   if (ICS2.getKindRank() < ICS1.getKindRank())
3565     return ImplicitConversionSequence::Worse;
3566 
3567   // The following checks require both conversion sequences to be of
3568   // the same kind.
3569   if (ICS1.getKind() != ICS2.getKind())
3570     return ImplicitConversionSequence::Indistinguishable;
3571 
3572   ImplicitConversionSequence::CompareKind Result =
3573       ImplicitConversionSequence::Indistinguishable;
3574 
3575   // Two implicit conversion sequences of the same form are
3576   // indistinguishable conversion sequences unless one of the
3577   // following rules apply: (C++ 13.3.3.2p3):
3578 
3579   // List-initialization sequence L1 is a better conversion sequence than
3580   // list-initialization sequence L2 if:
3581   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3582   //   if not that,
3583   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3584   //   and N1 is smaller than N2.,
3585   // even if one of the other rules in this paragraph would otherwise apply.
3586   if (!ICS1.isBad()) {
3587     if (ICS1.isStdInitializerListElement() &&
3588         !ICS2.isStdInitializerListElement())
3589       return ImplicitConversionSequence::Better;
3590     if (!ICS1.isStdInitializerListElement() &&
3591         ICS2.isStdInitializerListElement())
3592       return ImplicitConversionSequence::Worse;
3593   }
3594 
3595   if (ICS1.isStandard())
3596     // Standard conversion sequence S1 is a better conversion sequence than
3597     // standard conversion sequence S2 if [...]
3598     Result = CompareStandardConversionSequences(S, Loc,
3599                                                 ICS1.Standard, ICS2.Standard);
3600   else if (ICS1.isUserDefined()) {
3601     // User-defined conversion sequence U1 is a better conversion
3602     // sequence than another user-defined conversion sequence U2 if
3603     // they contain the same user-defined conversion function or
3604     // constructor and if the second standard conversion sequence of
3605     // U1 is better than the second standard conversion sequence of
3606     // U2 (C++ 13.3.3.2p3).
3607     if (ICS1.UserDefined.ConversionFunction ==
3608           ICS2.UserDefined.ConversionFunction)
3609       Result = CompareStandardConversionSequences(S, Loc,
3610                                                   ICS1.UserDefined.After,
3611                                                   ICS2.UserDefined.After);
3612     else
3613       Result = compareConversionFunctions(S,
3614                                           ICS1.UserDefined.ConversionFunction,
3615                                           ICS2.UserDefined.ConversionFunction);
3616   }
3617 
3618   return Result;
3619 }
3620 
3621 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3622   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3623     Qualifiers Quals;
3624     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3625     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3626   }
3627 
3628   return Context.hasSameUnqualifiedType(T1, T2);
3629 }
3630 
3631 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3632 // determine if one is a proper subset of the other.
3633 static ImplicitConversionSequence::CompareKind
3634 compareStandardConversionSubsets(ASTContext &Context,
3635                                  const StandardConversionSequence& SCS1,
3636                                  const StandardConversionSequence& SCS2) {
3637   ImplicitConversionSequence::CompareKind Result
3638     = ImplicitConversionSequence::Indistinguishable;
3639 
3640   // the identity conversion sequence is considered to be a subsequence of
3641   // any non-identity conversion sequence
3642   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3643     return ImplicitConversionSequence::Better;
3644   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3645     return ImplicitConversionSequence::Worse;
3646 
3647   if (SCS1.Second != SCS2.Second) {
3648     if (SCS1.Second == ICK_Identity)
3649       Result = ImplicitConversionSequence::Better;
3650     else if (SCS2.Second == ICK_Identity)
3651       Result = ImplicitConversionSequence::Worse;
3652     else
3653       return ImplicitConversionSequence::Indistinguishable;
3654   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   if (SCS1.Third == SCS2.Third) {
3658     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3659                              : ImplicitConversionSequence::Indistinguishable;
3660   }
3661 
3662   if (SCS1.Third == ICK_Identity)
3663     return Result == ImplicitConversionSequence::Worse
3664              ? ImplicitConversionSequence::Indistinguishable
3665              : ImplicitConversionSequence::Better;
3666 
3667   if (SCS2.Third == ICK_Identity)
3668     return Result == ImplicitConversionSequence::Better
3669              ? ImplicitConversionSequence::Indistinguishable
3670              : ImplicitConversionSequence::Worse;
3671 
3672   return ImplicitConversionSequence::Indistinguishable;
3673 }
3674 
3675 /// \brief Determine whether one of the given reference bindings is better
3676 /// than the other based on what kind of bindings they are.
3677 static bool
3678 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3679                              const StandardConversionSequence &SCS2) {
3680   // C++0x [over.ics.rank]p3b4:
3681   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3682   //      implicit object parameter of a non-static member function declared
3683   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3684   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3685   //      lvalue reference to a function lvalue and S2 binds an rvalue
3686   //      reference*.
3687   //
3688   // FIXME: Rvalue references. We're going rogue with the above edits,
3689   // because the semantics in the current C++0x working paper (N3225 at the
3690   // time of this writing) break the standard definition of std::forward
3691   // and std::reference_wrapper when dealing with references to functions.
3692   // Proposed wording changes submitted to CWG for consideration.
3693   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3694       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3695     return false;
3696 
3697   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3698           SCS2.IsLvalueReference) ||
3699          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3700           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3701 }
3702 
3703 /// CompareStandardConversionSequences - Compare two standard
3704 /// conversion sequences to determine whether one is better than the
3705 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3706 static ImplicitConversionSequence::CompareKind
3707 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3708                                    const StandardConversionSequence& SCS1,
3709                                    const StandardConversionSequence& SCS2)
3710 {
3711   // Standard conversion sequence S1 is a better conversion sequence
3712   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3713 
3714   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3715   //     sequences in the canonical form defined by 13.3.3.1.1,
3716   //     excluding any Lvalue Transformation; the identity conversion
3717   //     sequence is considered to be a subsequence of any
3718   //     non-identity conversion sequence) or, if not that,
3719   if (ImplicitConversionSequence::CompareKind CK
3720         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3721     return CK;
3722 
3723   //  -- the rank of S1 is better than the rank of S2 (by the rules
3724   //     defined below), or, if not that,
3725   ImplicitConversionRank Rank1 = SCS1.getRank();
3726   ImplicitConversionRank Rank2 = SCS2.getRank();
3727   if (Rank1 < Rank2)
3728     return ImplicitConversionSequence::Better;
3729   else if (Rank2 < Rank1)
3730     return ImplicitConversionSequence::Worse;
3731 
3732   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3733   // are indistinguishable unless one of the following rules
3734   // applies:
3735 
3736   //   A conversion that is not a conversion of a pointer, or
3737   //   pointer to member, to bool is better than another conversion
3738   //   that is such a conversion.
3739   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3740     return SCS2.isPointerConversionToBool()
3741              ? ImplicitConversionSequence::Better
3742              : ImplicitConversionSequence::Worse;
3743 
3744   // C++ [over.ics.rank]p4b2:
3745   //
3746   //   If class B is derived directly or indirectly from class A,
3747   //   conversion of B* to A* is better than conversion of B* to
3748   //   void*, and conversion of A* to void* is better than conversion
3749   //   of B* to void*.
3750   bool SCS1ConvertsToVoid
3751     = SCS1.isPointerConversionToVoidPointer(S.Context);
3752   bool SCS2ConvertsToVoid
3753     = SCS2.isPointerConversionToVoidPointer(S.Context);
3754   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3755     // Exactly one of the conversion sequences is a conversion to
3756     // a void pointer; it's the worse conversion.
3757     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3758                               : ImplicitConversionSequence::Worse;
3759   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3760     // Neither conversion sequence converts to a void pointer; compare
3761     // their derived-to-base conversions.
3762     if (ImplicitConversionSequence::CompareKind DerivedCK
3763           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3764       return DerivedCK;
3765   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3766              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3767     // Both conversion sequences are conversions to void
3768     // pointers. Compare the source types to determine if there's an
3769     // inheritance relationship in their sources.
3770     QualType FromType1 = SCS1.getFromType();
3771     QualType FromType2 = SCS2.getFromType();
3772 
3773     // Adjust the types we're converting from via the array-to-pointer
3774     // conversion, if we need to.
3775     if (SCS1.First == ICK_Array_To_Pointer)
3776       FromType1 = S.Context.getArrayDecayedType(FromType1);
3777     if (SCS2.First == ICK_Array_To_Pointer)
3778       FromType2 = S.Context.getArrayDecayedType(FromType2);
3779 
3780     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3781     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3782 
3783     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3784       return ImplicitConversionSequence::Better;
3785     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3786       return ImplicitConversionSequence::Worse;
3787 
3788     // Objective-C++: If one interface is more specific than the
3789     // other, it is the better one.
3790     const ObjCObjectPointerType* FromObjCPtr1
3791       = FromType1->getAs<ObjCObjectPointerType>();
3792     const ObjCObjectPointerType* FromObjCPtr2
3793       = FromType2->getAs<ObjCObjectPointerType>();
3794     if (FromObjCPtr1 && FromObjCPtr2) {
3795       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3796                                                           FromObjCPtr2);
3797       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3798                                                            FromObjCPtr1);
3799       if (AssignLeft != AssignRight) {
3800         return AssignLeft? ImplicitConversionSequence::Better
3801                          : ImplicitConversionSequence::Worse;
3802       }
3803     }
3804   }
3805 
3806   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3807   // bullet 3).
3808   if (ImplicitConversionSequence::CompareKind QualCK
3809         = CompareQualificationConversions(S, SCS1, SCS2))
3810     return QualCK;
3811 
3812   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3813     // Check for a better reference binding based on the kind of bindings.
3814     if (isBetterReferenceBindingKind(SCS1, SCS2))
3815       return ImplicitConversionSequence::Better;
3816     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3817       return ImplicitConversionSequence::Worse;
3818 
3819     // C++ [over.ics.rank]p3b4:
3820     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3821     //      which the references refer are the same type except for
3822     //      top-level cv-qualifiers, and the type to which the reference
3823     //      initialized by S2 refers is more cv-qualified than the type
3824     //      to which the reference initialized by S1 refers.
3825     QualType T1 = SCS1.getToType(2);
3826     QualType T2 = SCS2.getToType(2);
3827     T1 = S.Context.getCanonicalType(T1);
3828     T2 = S.Context.getCanonicalType(T2);
3829     Qualifiers T1Quals, T2Quals;
3830     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3831     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3832     if (UnqualT1 == UnqualT2) {
3833       // Objective-C++ ARC: If the references refer to objects with different
3834       // lifetimes, prefer bindings that don't change lifetime.
3835       if (SCS1.ObjCLifetimeConversionBinding !=
3836                                           SCS2.ObjCLifetimeConversionBinding) {
3837         return SCS1.ObjCLifetimeConversionBinding
3838                                            ? ImplicitConversionSequence::Worse
3839                                            : ImplicitConversionSequence::Better;
3840       }
3841 
3842       // If the type is an array type, promote the element qualifiers to the
3843       // type for comparison.
3844       if (isa<ArrayType>(T1) && T1Quals)
3845         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3846       if (isa<ArrayType>(T2) && T2Quals)
3847         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3848       if (T2.isMoreQualifiedThan(T1))
3849         return ImplicitConversionSequence::Better;
3850       else if (T1.isMoreQualifiedThan(T2))
3851         return ImplicitConversionSequence::Worse;
3852     }
3853   }
3854 
3855   // In Microsoft mode, prefer an integral conversion to a
3856   // floating-to-integral conversion if the integral conversion
3857   // is between types of the same size.
3858   // For example:
3859   // void f(float);
3860   // void f(int);
3861   // int main {
3862   //    long a;
3863   //    f(a);
3864   // }
3865   // Here, MSVC will call f(int) instead of generating a compile error
3866   // as clang will do in standard mode.
3867   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3868       SCS2.Second == ICK_Floating_Integral &&
3869       S.Context.getTypeSize(SCS1.getFromType()) ==
3870           S.Context.getTypeSize(SCS1.getToType(2)))
3871     return ImplicitConversionSequence::Better;
3872 
3873   return ImplicitConversionSequence::Indistinguishable;
3874 }
3875 
3876 /// CompareQualificationConversions - Compares two standard conversion
3877 /// sequences to determine whether they can be ranked based on their
3878 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3879 static ImplicitConversionSequence::CompareKind
3880 CompareQualificationConversions(Sema &S,
3881                                 const StandardConversionSequence& SCS1,
3882                                 const StandardConversionSequence& SCS2) {
3883   // C++ 13.3.3.2p3:
3884   //  -- S1 and S2 differ only in their qualification conversion and
3885   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3886   //     cv-qualification signature of type T1 is a proper subset of
3887   //     the cv-qualification signature of type T2, and S1 is not the
3888   //     deprecated string literal array-to-pointer conversion (4.2).
3889   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3890       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3891     return ImplicitConversionSequence::Indistinguishable;
3892 
3893   // FIXME: the example in the standard doesn't use a qualification
3894   // conversion (!)
3895   QualType T1 = SCS1.getToType(2);
3896   QualType T2 = SCS2.getToType(2);
3897   T1 = S.Context.getCanonicalType(T1);
3898   T2 = S.Context.getCanonicalType(T2);
3899   Qualifiers T1Quals, T2Quals;
3900   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3901   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3902 
3903   // If the types are the same, we won't learn anything by unwrapped
3904   // them.
3905   if (UnqualT1 == UnqualT2)
3906     return ImplicitConversionSequence::Indistinguishable;
3907 
3908   // If the type is an array type, promote the element qualifiers to the type
3909   // for comparison.
3910   if (isa<ArrayType>(T1) && T1Quals)
3911     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3912   if (isa<ArrayType>(T2) && T2Quals)
3913     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3914 
3915   ImplicitConversionSequence::CompareKind Result
3916     = ImplicitConversionSequence::Indistinguishable;
3917 
3918   // Objective-C++ ARC:
3919   //   Prefer qualification conversions not involving a change in lifetime
3920   //   to qualification conversions that do not change lifetime.
3921   if (SCS1.QualificationIncludesObjCLifetime !=
3922                                       SCS2.QualificationIncludesObjCLifetime) {
3923     Result = SCS1.QualificationIncludesObjCLifetime
3924                ? ImplicitConversionSequence::Worse
3925                : ImplicitConversionSequence::Better;
3926   }
3927 
3928   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3929     // Within each iteration of the loop, we check the qualifiers to
3930     // determine if this still looks like a qualification
3931     // conversion. Then, if all is well, we unwrap one more level of
3932     // pointers or pointers-to-members and do it all again
3933     // until there are no more pointers or pointers-to-members left
3934     // to unwrap. This essentially mimics what
3935     // IsQualificationConversion does, but here we're checking for a
3936     // strict subset of qualifiers.
3937     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3938       // The qualifiers are the same, so this doesn't tell us anything
3939       // about how the sequences rank.
3940       ;
3941     else if (T2.isMoreQualifiedThan(T1)) {
3942       // T1 has fewer qualifiers, so it could be the better sequence.
3943       if (Result == ImplicitConversionSequence::Worse)
3944         // Neither has qualifiers that are a subset of the other's
3945         // qualifiers.
3946         return ImplicitConversionSequence::Indistinguishable;
3947 
3948       Result = ImplicitConversionSequence::Better;
3949     } else if (T1.isMoreQualifiedThan(T2)) {
3950       // T2 has fewer qualifiers, so it could be the better sequence.
3951       if (Result == ImplicitConversionSequence::Better)
3952         // Neither has qualifiers that are a subset of the other's
3953         // qualifiers.
3954         return ImplicitConversionSequence::Indistinguishable;
3955 
3956       Result = ImplicitConversionSequence::Worse;
3957     } else {
3958       // Qualifiers are disjoint.
3959       return ImplicitConversionSequence::Indistinguishable;
3960     }
3961 
3962     // If the types after this point are equivalent, we're done.
3963     if (S.Context.hasSameUnqualifiedType(T1, T2))
3964       break;
3965   }
3966 
3967   // Check that the winning standard conversion sequence isn't using
3968   // the deprecated string literal array to pointer conversion.
3969   switch (Result) {
3970   case ImplicitConversionSequence::Better:
3971     if (SCS1.DeprecatedStringLiteralToCharPtr)
3972       Result = ImplicitConversionSequence::Indistinguishable;
3973     break;
3974 
3975   case ImplicitConversionSequence::Indistinguishable:
3976     break;
3977 
3978   case ImplicitConversionSequence::Worse:
3979     if (SCS2.DeprecatedStringLiteralToCharPtr)
3980       Result = ImplicitConversionSequence::Indistinguishable;
3981     break;
3982   }
3983 
3984   return Result;
3985 }
3986 
3987 /// CompareDerivedToBaseConversions - Compares two standard conversion
3988 /// sequences to determine whether they can be ranked based on their
3989 /// various kinds of derived-to-base conversions (C++
3990 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3991 /// conversions between Objective-C interface types.
3992 static ImplicitConversionSequence::CompareKind
3993 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3994                                 const StandardConversionSequence& SCS1,
3995                                 const StandardConversionSequence& SCS2) {
3996   QualType FromType1 = SCS1.getFromType();
3997   QualType ToType1 = SCS1.getToType(1);
3998   QualType FromType2 = SCS2.getFromType();
3999   QualType ToType2 = SCS2.getToType(1);
4000 
4001   // Adjust the types we're converting from via the array-to-pointer
4002   // conversion, if we need to.
4003   if (SCS1.First == ICK_Array_To_Pointer)
4004     FromType1 = S.Context.getArrayDecayedType(FromType1);
4005   if (SCS2.First == ICK_Array_To_Pointer)
4006     FromType2 = S.Context.getArrayDecayedType(FromType2);
4007 
4008   // Canonicalize all of the types.
4009   FromType1 = S.Context.getCanonicalType(FromType1);
4010   ToType1 = S.Context.getCanonicalType(ToType1);
4011   FromType2 = S.Context.getCanonicalType(FromType2);
4012   ToType2 = S.Context.getCanonicalType(ToType2);
4013 
4014   // C++ [over.ics.rank]p4b3:
4015   //
4016   //   If class B is derived directly or indirectly from class A and
4017   //   class C is derived directly or indirectly from B,
4018   //
4019   // Compare based on pointer conversions.
4020   if (SCS1.Second == ICK_Pointer_Conversion &&
4021       SCS2.Second == ICK_Pointer_Conversion &&
4022       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4023       FromType1->isPointerType() && FromType2->isPointerType() &&
4024       ToType1->isPointerType() && ToType2->isPointerType()) {
4025     QualType FromPointee1
4026       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4027     QualType ToPointee1
4028       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4029     QualType FromPointee2
4030       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031     QualType ToPointee2
4032       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4033 
4034     //   -- conversion of C* to B* is better than conversion of C* to A*,
4035     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4036       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4037         return ImplicitConversionSequence::Better;
4038       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4039         return ImplicitConversionSequence::Worse;
4040     }
4041 
4042     //   -- conversion of B* to A* is better than conversion of C* to A*,
4043     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4044       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4045         return ImplicitConversionSequence::Better;
4046       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4047         return ImplicitConversionSequence::Worse;
4048     }
4049   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4050              SCS2.Second == ICK_Pointer_Conversion) {
4051     const ObjCObjectPointerType *FromPtr1
4052       = FromType1->getAs<ObjCObjectPointerType>();
4053     const ObjCObjectPointerType *FromPtr2
4054       = FromType2->getAs<ObjCObjectPointerType>();
4055     const ObjCObjectPointerType *ToPtr1
4056       = ToType1->getAs<ObjCObjectPointerType>();
4057     const ObjCObjectPointerType *ToPtr2
4058       = ToType2->getAs<ObjCObjectPointerType>();
4059 
4060     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4061       // Apply the same conversion ranking rules for Objective-C pointer types
4062       // that we do for C++ pointers to class types. However, we employ the
4063       // Objective-C pseudo-subtyping relationship used for assignment of
4064       // Objective-C pointer types.
4065       bool FromAssignLeft
4066         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4067       bool FromAssignRight
4068         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4069       bool ToAssignLeft
4070         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4071       bool ToAssignRight
4072         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4073 
4074       // A conversion to an a non-id object pointer type or qualified 'id'
4075       // type is better than a conversion to 'id'.
4076       if (ToPtr1->isObjCIdType() &&
4077           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4078         return ImplicitConversionSequence::Worse;
4079       if (ToPtr2->isObjCIdType() &&
4080           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4081         return ImplicitConversionSequence::Better;
4082 
4083       // A conversion to a non-id object pointer type is better than a
4084       // conversion to a qualified 'id' type
4085       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4086         return ImplicitConversionSequence::Worse;
4087       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4088         return ImplicitConversionSequence::Better;
4089 
4090       // A conversion to an a non-Class object pointer type or qualified 'Class'
4091       // type is better than a conversion to 'Class'.
4092       if (ToPtr1->isObjCClassType() &&
4093           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4094         return ImplicitConversionSequence::Worse;
4095       if (ToPtr2->isObjCClassType() &&
4096           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4097         return ImplicitConversionSequence::Better;
4098 
4099       // A conversion to a non-Class object pointer type is better than a
4100       // conversion to a qualified 'Class' type.
4101       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4102         return ImplicitConversionSequence::Worse;
4103       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4104         return ImplicitConversionSequence::Better;
4105 
4106       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4107       if (S.Context.hasSameType(FromType1, FromType2) &&
4108           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4109           (ToAssignLeft != ToAssignRight)) {
4110         if (FromPtr1->isSpecialized()) {
4111           // "conversion of B<A> * to B * is better than conversion of B * to
4112           // C *.
4113           bool IsFirstSame =
4114               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4115           bool IsSecondSame =
4116               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4117           if (IsFirstSame) {
4118             if (!IsSecondSame)
4119               return ImplicitConversionSequence::Better;
4120           } else if (IsSecondSame)
4121             return ImplicitConversionSequence::Worse;
4122         }
4123         return ToAssignLeft? ImplicitConversionSequence::Worse
4124                            : ImplicitConversionSequence::Better;
4125       }
4126 
4127       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4128       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4129           (FromAssignLeft != FromAssignRight))
4130         return FromAssignLeft? ImplicitConversionSequence::Better
4131         : ImplicitConversionSequence::Worse;
4132     }
4133   }
4134 
4135   // Ranking of member-pointer types.
4136   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4137       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4138       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4139     const MemberPointerType * FromMemPointer1 =
4140                                         FromType1->getAs<MemberPointerType>();
4141     const MemberPointerType * ToMemPointer1 =
4142                                           ToType1->getAs<MemberPointerType>();
4143     const MemberPointerType * FromMemPointer2 =
4144                                           FromType2->getAs<MemberPointerType>();
4145     const MemberPointerType * ToMemPointer2 =
4146                                           ToType2->getAs<MemberPointerType>();
4147     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4148     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4149     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4150     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4151     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4152     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4153     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4154     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4155     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4156     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4157       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4158         return ImplicitConversionSequence::Worse;
4159       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4160         return ImplicitConversionSequence::Better;
4161     }
4162     // conversion of B::* to C::* is better than conversion of A::* to C::*
4163     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4164       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4165         return ImplicitConversionSequence::Better;
4166       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4167         return ImplicitConversionSequence::Worse;
4168     }
4169   }
4170 
4171   if (SCS1.Second == ICK_Derived_To_Base) {
4172     //   -- conversion of C to B is better than conversion of C to A,
4173     //   -- binding of an expression of type C to a reference of type
4174     //      B& is better than binding an expression of type C to a
4175     //      reference of type A&,
4176     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4177         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4178       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4179         return ImplicitConversionSequence::Better;
4180       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4181         return ImplicitConversionSequence::Worse;
4182     }
4183 
4184     //   -- conversion of B to A is better than conversion of C to A.
4185     //   -- binding of an expression of type B to a reference of type
4186     //      A& is better than binding an expression of type C to a
4187     //      reference of type A&,
4188     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4189         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4190       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4191         return ImplicitConversionSequence::Better;
4192       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4193         return ImplicitConversionSequence::Worse;
4194     }
4195   }
4196 
4197   return ImplicitConversionSequence::Indistinguishable;
4198 }
4199 
4200 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4201 /// C++ class.
4202 static bool isTypeValid(QualType T) {
4203   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4204     return !Record->isInvalidDecl();
4205 
4206   return true;
4207 }
4208 
4209 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4210 /// determine whether they are reference-related,
4211 /// reference-compatible, reference-compatible with added
4212 /// qualification, or incompatible, for use in C++ initialization by
4213 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4214 /// type, and the first type (T1) is the pointee type of the reference
4215 /// type being initialized.
4216 Sema::ReferenceCompareResult
4217 Sema::CompareReferenceRelationship(SourceLocation Loc,
4218                                    QualType OrigT1, QualType OrigT2,
4219                                    bool &DerivedToBase,
4220                                    bool &ObjCConversion,
4221                                    bool &ObjCLifetimeConversion) {
4222   assert(!OrigT1->isReferenceType() &&
4223     "T1 must be the pointee type of the reference type");
4224   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4225 
4226   QualType T1 = Context.getCanonicalType(OrigT1);
4227   QualType T2 = Context.getCanonicalType(OrigT2);
4228   Qualifiers T1Quals, T2Quals;
4229   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4230   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4231 
4232   // C++ [dcl.init.ref]p4:
4233   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4234   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4235   //   T1 is a base class of T2.
4236   DerivedToBase = false;
4237   ObjCConversion = false;
4238   ObjCLifetimeConversion = false;
4239   QualType ConvertedT2;
4240   if (UnqualT1 == UnqualT2) {
4241     // Nothing to do.
4242   } else if (isCompleteType(Loc, OrigT2) &&
4243              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4244              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4245     DerivedToBase = true;
4246   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4247            UnqualT2->isObjCObjectOrInterfaceType() &&
4248            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4249     ObjCConversion = true;
4250   else if (UnqualT2->isFunctionType() &&
4251            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4252     // C++1z [dcl.init.ref]p4:
4253     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4254     //   function" and T1 is "function"
4255     //
4256     // We extend this to also apply to 'noreturn', so allow any function
4257     // conversion between function types.
4258     return Ref_Compatible;
4259   else
4260     return Ref_Incompatible;
4261 
4262   // At this point, we know that T1 and T2 are reference-related (at
4263   // least).
4264 
4265   // If the type is an array type, promote the element qualifiers to the type
4266   // for comparison.
4267   if (isa<ArrayType>(T1) && T1Quals)
4268     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4269   if (isa<ArrayType>(T2) && T2Quals)
4270     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4271 
4272   // C++ [dcl.init.ref]p4:
4273   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4274   //   reference-related to T2 and cv1 is the same cv-qualification
4275   //   as, or greater cv-qualification than, cv2. For purposes of
4276   //   overload resolution, cases for which cv1 is greater
4277   //   cv-qualification than cv2 are identified as
4278   //   reference-compatible with added qualification (see 13.3.3.2).
4279   //
4280   // Note that we also require equivalence of Objective-C GC and address-space
4281   // qualifiers when performing these computations, so that e.g., an int in
4282   // address space 1 is not reference-compatible with an int in address
4283   // space 2.
4284   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4285       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4286     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4287       ObjCLifetimeConversion = true;
4288 
4289     T1Quals.removeObjCLifetime();
4290     T2Quals.removeObjCLifetime();
4291   }
4292 
4293   // MS compiler ignores __unaligned qualifier for references; do the same.
4294   T1Quals.removeUnaligned();
4295   T2Quals.removeUnaligned();
4296 
4297   if (T1Quals.compatiblyIncludes(T2Quals))
4298     return Ref_Compatible;
4299   else
4300     return Ref_Related;
4301 }
4302 
4303 /// \brief Look for a user-defined conversion to a value reference-compatible
4304 ///        with DeclType. Return true if something definite is found.
4305 static bool
4306 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4307                          QualType DeclType, SourceLocation DeclLoc,
4308                          Expr *Init, QualType T2, bool AllowRvalues,
4309                          bool AllowExplicit) {
4310   assert(T2->isRecordType() && "Can only find conversions of record types.");
4311   CXXRecordDecl *T2RecordDecl
4312     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4313 
4314   OverloadCandidateSet CandidateSet(
4315       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4316   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4317   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4318     NamedDecl *D = *I;
4319     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4320     if (isa<UsingShadowDecl>(D))
4321       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4322 
4323     FunctionTemplateDecl *ConvTemplate
4324       = dyn_cast<FunctionTemplateDecl>(D);
4325     CXXConversionDecl *Conv;
4326     if (ConvTemplate)
4327       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4328     else
4329       Conv = cast<CXXConversionDecl>(D);
4330 
4331     // If this is an explicit conversion, and we're not allowed to consider
4332     // explicit conversions, skip it.
4333     if (!AllowExplicit && Conv->isExplicit())
4334       continue;
4335 
4336     if (AllowRvalues) {
4337       bool DerivedToBase = false;
4338       bool ObjCConversion = false;
4339       bool ObjCLifetimeConversion = false;
4340 
4341       // If we are initializing an rvalue reference, don't permit conversion
4342       // functions that return lvalues.
4343       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4344         const ReferenceType *RefType
4345           = Conv->getConversionType()->getAs<LValueReferenceType>();
4346         if (RefType && !RefType->getPointeeType()->isFunctionType())
4347           continue;
4348       }
4349 
4350       if (!ConvTemplate &&
4351           S.CompareReferenceRelationship(
4352             DeclLoc,
4353             Conv->getConversionType().getNonReferenceType()
4354               .getUnqualifiedType(),
4355             DeclType.getNonReferenceType().getUnqualifiedType(),
4356             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4357           Sema::Ref_Incompatible)
4358         continue;
4359     } else {
4360       // If the conversion function doesn't return a reference type,
4361       // it can't be considered for this conversion. An rvalue reference
4362       // is only acceptable if its referencee is a function type.
4363 
4364       const ReferenceType *RefType =
4365         Conv->getConversionType()->getAs<ReferenceType>();
4366       if (!RefType ||
4367           (!RefType->isLValueReferenceType() &&
4368            !RefType->getPointeeType()->isFunctionType()))
4369         continue;
4370     }
4371 
4372     if (ConvTemplate)
4373       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4374                                        Init, DeclType, CandidateSet,
4375                                        /*AllowObjCConversionOnExplicit=*/false);
4376     else
4377       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4378                                DeclType, CandidateSet,
4379                                /*AllowObjCConversionOnExplicit=*/false);
4380   }
4381 
4382   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4383 
4384   OverloadCandidateSet::iterator Best;
4385   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4386   case OR_Success:
4387     // C++ [over.ics.ref]p1:
4388     //
4389     //   [...] If the parameter binds directly to the result of
4390     //   applying a conversion function to the argument
4391     //   expression, the implicit conversion sequence is a
4392     //   user-defined conversion sequence (13.3.3.1.2), with the
4393     //   second standard conversion sequence either an identity
4394     //   conversion or, if the conversion function returns an
4395     //   entity of a type that is a derived class of the parameter
4396     //   type, a derived-to-base Conversion.
4397     if (!Best->FinalConversion.DirectBinding)
4398       return false;
4399 
4400     ICS.setUserDefined();
4401     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4402     ICS.UserDefined.After = Best->FinalConversion;
4403     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4404     ICS.UserDefined.ConversionFunction = Best->Function;
4405     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4406     ICS.UserDefined.EllipsisConversion = false;
4407     assert(ICS.UserDefined.After.ReferenceBinding &&
4408            ICS.UserDefined.After.DirectBinding &&
4409            "Expected a direct reference binding!");
4410     return true;
4411 
4412   case OR_Ambiguous:
4413     ICS.setAmbiguous();
4414     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4415          Cand != CandidateSet.end(); ++Cand)
4416       if (Cand->Viable)
4417         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4418     return true;
4419 
4420   case OR_No_Viable_Function:
4421   case OR_Deleted:
4422     // There was no suitable conversion, or we found a deleted
4423     // conversion; continue with other checks.
4424     return false;
4425   }
4426 
4427   llvm_unreachable("Invalid OverloadResult!");
4428 }
4429 
4430 /// \brief Compute an implicit conversion sequence for reference
4431 /// initialization.
4432 static ImplicitConversionSequence
4433 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4434                  SourceLocation DeclLoc,
4435                  bool SuppressUserConversions,
4436                  bool AllowExplicit) {
4437   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4438 
4439   // Most paths end in a failed conversion.
4440   ImplicitConversionSequence ICS;
4441   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4442 
4443   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4444   QualType T2 = Init->getType();
4445 
4446   // If the initializer is the address of an overloaded function, try
4447   // to resolve the overloaded function. If all goes well, T2 is the
4448   // type of the resulting function.
4449   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4450     DeclAccessPair Found;
4451     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4452                                                                 false, Found))
4453       T2 = Fn->getType();
4454   }
4455 
4456   // Compute some basic properties of the types and the initializer.
4457   bool isRValRef = DeclType->isRValueReferenceType();
4458   bool DerivedToBase = false;
4459   bool ObjCConversion = false;
4460   bool ObjCLifetimeConversion = false;
4461   Expr::Classification InitCategory = Init->Classify(S.Context);
4462   Sema::ReferenceCompareResult RefRelationship
4463     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4464                                      ObjCConversion, ObjCLifetimeConversion);
4465 
4466 
4467   // C++0x [dcl.init.ref]p5:
4468   //   A reference to type "cv1 T1" is initialized by an expression
4469   //   of type "cv2 T2" as follows:
4470 
4471   //     -- If reference is an lvalue reference and the initializer expression
4472   if (!isRValRef) {
4473     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4474     //        reference-compatible with "cv2 T2," or
4475     //
4476     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4477     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4478       // C++ [over.ics.ref]p1:
4479       //   When a parameter of reference type binds directly (8.5.3)
4480       //   to an argument expression, the implicit conversion sequence
4481       //   is the identity conversion, unless the argument expression
4482       //   has a type that is a derived class of the parameter type,
4483       //   in which case the implicit conversion sequence is a
4484       //   derived-to-base Conversion (13.3.3.1).
4485       ICS.setStandard();
4486       ICS.Standard.First = ICK_Identity;
4487       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4488                          : ObjCConversion? ICK_Compatible_Conversion
4489                          : ICK_Identity;
4490       ICS.Standard.Third = ICK_Identity;
4491       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4492       ICS.Standard.setToType(0, T2);
4493       ICS.Standard.setToType(1, T1);
4494       ICS.Standard.setToType(2, T1);
4495       ICS.Standard.ReferenceBinding = true;
4496       ICS.Standard.DirectBinding = true;
4497       ICS.Standard.IsLvalueReference = !isRValRef;
4498       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4499       ICS.Standard.BindsToRvalue = false;
4500       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4501       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4502       ICS.Standard.CopyConstructor = nullptr;
4503       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4504 
4505       // Nothing more to do: the inaccessibility/ambiguity check for
4506       // derived-to-base conversions is suppressed when we're
4507       // computing the implicit conversion sequence (C++
4508       // [over.best.ics]p2).
4509       return ICS;
4510     }
4511 
4512     //       -- has a class type (i.e., T2 is a class type), where T1 is
4513     //          not reference-related to T2, and can be implicitly
4514     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4515     //          is reference-compatible with "cv3 T3" 92) (this
4516     //          conversion is selected by enumerating the applicable
4517     //          conversion functions (13.3.1.6) and choosing the best
4518     //          one through overload resolution (13.3)),
4519     if (!SuppressUserConversions && T2->isRecordType() &&
4520         S.isCompleteType(DeclLoc, T2) &&
4521         RefRelationship == Sema::Ref_Incompatible) {
4522       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4523                                    Init, T2, /*AllowRvalues=*/false,
4524                                    AllowExplicit))
4525         return ICS;
4526     }
4527   }
4528 
4529   //     -- Otherwise, the reference shall be an lvalue reference to a
4530   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4531   //        shall be an rvalue reference.
4532   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4533     return ICS;
4534 
4535   //       -- If the initializer expression
4536   //
4537   //            -- is an xvalue, class prvalue, array prvalue or function
4538   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4539   if (RefRelationship == Sema::Ref_Compatible &&
4540       (InitCategory.isXValue() ||
4541        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4542        (InitCategory.isLValue() && T2->isFunctionType()))) {
4543     ICS.setStandard();
4544     ICS.Standard.First = ICK_Identity;
4545     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4546                       : ObjCConversion? ICK_Compatible_Conversion
4547                       : ICK_Identity;
4548     ICS.Standard.Third = ICK_Identity;
4549     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4550     ICS.Standard.setToType(0, T2);
4551     ICS.Standard.setToType(1, T1);
4552     ICS.Standard.setToType(2, T1);
4553     ICS.Standard.ReferenceBinding = true;
4554     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4555     // binding unless we're binding to a class prvalue.
4556     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4557     // allow the use of rvalue references in C++98/03 for the benefit of
4558     // standard library implementors; therefore, we need the xvalue check here.
4559     ICS.Standard.DirectBinding =
4560       S.getLangOpts().CPlusPlus11 ||
4561       !(InitCategory.isPRValue() || T2->isRecordType());
4562     ICS.Standard.IsLvalueReference = !isRValRef;
4563     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4564     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4565     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4566     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4567     ICS.Standard.CopyConstructor = nullptr;
4568     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4569     return ICS;
4570   }
4571 
4572   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4573   //               reference-related to T2, and can be implicitly converted to
4574   //               an xvalue, class prvalue, or function lvalue of type
4575   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4576   //               "cv3 T3",
4577   //
4578   //          then the reference is bound to the value of the initializer
4579   //          expression in the first case and to the result of the conversion
4580   //          in the second case (or, in either case, to an appropriate base
4581   //          class subobject).
4582   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4583       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4584       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4585                                Init, T2, /*AllowRvalues=*/true,
4586                                AllowExplicit)) {
4587     // In the second case, if the reference is an rvalue reference
4588     // and the second standard conversion sequence of the
4589     // user-defined conversion sequence includes an lvalue-to-rvalue
4590     // conversion, the program is ill-formed.
4591     if (ICS.isUserDefined() && isRValRef &&
4592         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4593       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4594 
4595     return ICS;
4596   }
4597 
4598   // A temporary of function type cannot be created; don't even try.
4599   if (T1->isFunctionType())
4600     return ICS;
4601 
4602   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4603   //          initialized from the initializer expression using the
4604   //          rules for a non-reference copy initialization (8.5). The
4605   //          reference is then bound to the temporary. If T1 is
4606   //          reference-related to T2, cv1 must be the same
4607   //          cv-qualification as, or greater cv-qualification than,
4608   //          cv2; otherwise, the program is ill-formed.
4609   if (RefRelationship == Sema::Ref_Related) {
4610     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4611     // we would be reference-compatible or reference-compatible with
4612     // added qualification. But that wasn't the case, so the reference
4613     // initialization fails.
4614     //
4615     // Note that we only want to check address spaces and cvr-qualifiers here.
4616     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4617     Qualifiers T1Quals = T1.getQualifiers();
4618     Qualifiers T2Quals = T2.getQualifiers();
4619     T1Quals.removeObjCGCAttr();
4620     T1Quals.removeObjCLifetime();
4621     T2Quals.removeObjCGCAttr();
4622     T2Quals.removeObjCLifetime();
4623     // MS compiler ignores __unaligned qualifier for references; do the same.
4624     T1Quals.removeUnaligned();
4625     T2Quals.removeUnaligned();
4626     if (!T1Quals.compatiblyIncludes(T2Quals))
4627       return ICS;
4628   }
4629 
4630   // If at least one of the types is a class type, the types are not
4631   // related, and we aren't allowed any user conversions, the
4632   // reference binding fails. This case is important for breaking
4633   // recursion, since TryImplicitConversion below will attempt to
4634   // create a temporary through the use of a copy constructor.
4635   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4636       (T1->isRecordType() || T2->isRecordType()))
4637     return ICS;
4638 
4639   // If T1 is reference-related to T2 and the reference is an rvalue
4640   // reference, the initializer expression shall not be an lvalue.
4641   if (RefRelationship >= Sema::Ref_Related &&
4642       isRValRef && Init->Classify(S.Context).isLValue())
4643     return ICS;
4644 
4645   // C++ [over.ics.ref]p2:
4646   //   When a parameter of reference type is not bound directly to
4647   //   an argument expression, the conversion sequence is the one
4648   //   required to convert the argument expression to the
4649   //   underlying type of the reference according to
4650   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4651   //   to copy-initializing a temporary of the underlying type with
4652   //   the argument expression. Any difference in top-level
4653   //   cv-qualification is subsumed by the initialization itself
4654   //   and does not constitute a conversion.
4655   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4656                               /*AllowExplicit=*/false,
4657                               /*InOverloadResolution=*/false,
4658                               /*CStyle=*/false,
4659                               /*AllowObjCWritebackConversion=*/false,
4660                               /*AllowObjCConversionOnExplicit=*/false);
4661 
4662   // Of course, that's still a reference binding.
4663   if (ICS.isStandard()) {
4664     ICS.Standard.ReferenceBinding = true;
4665     ICS.Standard.IsLvalueReference = !isRValRef;
4666     ICS.Standard.BindsToFunctionLvalue = false;
4667     ICS.Standard.BindsToRvalue = true;
4668     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4669     ICS.Standard.ObjCLifetimeConversionBinding = false;
4670   } else if (ICS.isUserDefined()) {
4671     const ReferenceType *LValRefType =
4672         ICS.UserDefined.ConversionFunction->getReturnType()
4673             ->getAs<LValueReferenceType>();
4674 
4675     // C++ [over.ics.ref]p3:
4676     //   Except for an implicit object parameter, for which see 13.3.1, a
4677     //   standard conversion sequence cannot be formed if it requires [...]
4678     //   binding an rvalue reference to an lvalue other than a function
4679     //   lvalue.
4680     // Note that the function case is not possible here.
4681     if (DeclType->isRValueReferenceType() && LValRefType) {
4682       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4683       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4684       // reference to an rvalue!
4685       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4686       return ICS;
4687     }
4688 
4689     ICS.UserDefined.After.ReferenceBinding = true;
4690     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4691     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4692     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4693     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4694     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4695   }
4696 
4697   return ICS;
4698 }
4699 
4700 static ImplicitConversionSequence
4701 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4702                       bool SuppressUserConversions,
4703                       bool InOverloadResolution,
4704                       bool AllowObjCWritebackConversion,
4705                       bool AllowExplicit = false);
4706 
4707 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4708 /// initializer list From.
4709 static ImplicitConversionSequence
4710 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4711                   bool SuppressUserConversions,
4712                   bool InOverloadResolution,
4713                   bool AllowObjCWritebackConversion) {
4714   // C++11 [over.ics.list]p1:
4715   //   When an argument is an initializer list, it is not an expression and
4716   //   special rules apply for converting it to a parameter type.
4717 
4718   ImplicitConversionSequence Result;
4719   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4720 
4721   // We need a complete type for what follows. Incomplete types can never be
4722   // initialized from init lists.
4723   if (!S.isCompleteType(From->getLocStart(), ToType))
4724     return Result;
4725 
4726   // Per DR1467:
4727   //   If the parameter type is a class X and the initializer list has a single
4728   //   element of type cv U, where U is X or a class derived from X, the
4729   //   implicit conversion sequence is the one required to convert the element
4730   //   to the parameter type.
4731   //
4732   //   Otherwise, if the parameter type is a character array [... ]
4733   //   and the initializer list has a single element that is an
4734   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4735   //   implicit conversion sequence is the identity conversion.
4736   if (From->getNumInits() == 1) {
4737     if (ToType->isRecordType()) {
4738       QualType InitType = From->getInit(0)->getType();
4739       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4740           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4741         return TryCopyInitialization(S, From->getInit(0), ToType,
4742                                      SuppressUserConversions,
4743                                      InOverloadResolution,
4744                                      AllowObjCWritebackConversion);
4745     }
4746     // FIXME: Check the other conditions here: array of character type,
4747     // initializer is a string literal.
4748     if (ToType->isArrayType()) {
4749       InitializedEntity Entity =
4750         InitializedEntity::InitializeParameter(S.Context, ToType,
4751                                                /*Consumed=*/false);
4752       if (S.CanPerformCopyInitialization(Entity, From)) {
4753         Result.setStandard();
4754         Result.Standard.setAsIdentityConversion();
4755         Result.Standard.setFromType(ToType);
4756         Result.Standard.setAllToTypes(ToType);
4757         return Result;
4758       }
4759     }
4760   }
4761 
4762   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4763   // C++11 [over.ics.list]p2:
4764   //   If the parameter type is std::initializer_list<X> or "array of X" and
4765   //   all the elements can be implicitly converted to X, the implicit
4766   //   conversion sequence is the worst conversion necessary to convert an
4767   //   element of the list to X.
4768   //
4769   // C++14 [over.ics.list]p3:
4770   //   Otherwise, if the parameter type is "array of N X", if the initializer
4771   //   list has exactly N elements or if it has fewer than N elements and X is
4772   //   default-constructible, and if all the elements of the initializer list
4773   //   can be implicitly converted to X, the implicit conversion sequence is
4774   //   the worst conversion necessary to convert an element of the list to X.
4775   //
4776   // FIXME: We're missing a lot of these checks.
4777   bool toStdInitializerList = false;
4778   QualType X;
4779   if (ToType->isArrayType())
4780     X = S.Context.getAsArrayType(ToType)->getElementType();
4781   else
4782     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4783   if (!X.isNull()) {
4784     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4785       Expr *Init = From->getInit(i);
4786       ImplicitConversionSequence ICS =
4787           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4788                                 InOverloadResolution,
4789                                 AllowObjCWritebackConversion);
4790       // If a single element isn't convertible, fail.
4791       if (ICS.isBad()) {
4792         Result = ICS;
4793         break;
4794       }
4795       // Otherwise, look for the worst conversion.
4796       if (Result.isBad() ||
4797           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4798                                              Result) ==
4799               ImplicitConversionSequence::Worse)
4800         Result = ICS;
4801     }
4802 
4803     // For an empty list, we won't have computed any conversion sequence.
4804     // Introduce the identity conversion sequence.
4805     if (From->getNumInits() == 0) {
4806       Result.setStandard();
4807       Result.Standard.setAsIdentityConversion();
4808       Result.Standard.setFromType(ToType);
4809       Result.Standard.setAllToTypes(ToType);
4810     }
4811 
4812     Result.setStdInitializerListElement(toStdInitializerList);
4813     return Result;
4814   }
4815 
4816   // C++14 [over.ics.list]p4:
4817   // C++11 [over.ics.list]p3:
4818   //   Otherwise, if the parameter is a non-aggregate class X and overload
4819   //   resolution chooses a single best constructor [...] the implicit
4820   //   conversion sequence is a user-defined conversion sequence. If multiple
4821   //   constructors are viable but none is better than the others, the
4822   //   implicit conversion sequence is a user-defined conversion sequence.
4823   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4824     // This function can deal with initializer lists.
4825     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4826                                     /*AllowExplicit=*/false,
4827                                     InOverloadResolution, /*CStyle=*/false,
4828                                     AllowObjCWritebackConversion,
4829                                     /*AllowObjCConversionOnExplicit=*/false);
4830   }
4831 
4832   // C++14 [over.ics.list]p5:
4833   // C++11 [over.ics.list]p4:
4834   //   Otherwise, if the parameter has an aggregate type which can be
4835   //   initialized from the initializer list [...] the implicit conversion
4836   //   sequence is a user-defined conversion sequence.
4837   if (ToType->isAggregateType()) {
4838     // Type is an aggregate, argument is an init list. At this point it comes
4839     // down to checking whether the initialization works.
4840     // FIXME: Find out whether this parameter is consumed or not.
4841     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4842     // need to call into the initialization code here; overload resolution
4843     // should not be doing that.
4844     InitializedEntity Entity =
4845         InitializedEntity::InitializeParameter(S.Context, ToType,
4846                                                /*Consumed=*/false);
4847     if (S.CanPerformCopyInitialization(Entity, From)) {
4848       Result.setUserDefined();
4849       Result.UserDefined.Before.setAsIdentityConversion();
4850       // Initializer lists don't have a type.
4851       Result.UserDefined.Before.setFromType(QualType());
4852       Result.UserDefined.Before.setAllToTypes(QualType());
4853 
4854       Result.UserDefined.After.setAsIdentityConversion();
4855       Result.UserDefined.After.setFromType(ToType);
4856       Result.UserDefined.After.setAllToTypes(ToType);
4857       Result.UserDefined.ConversionFunction = nullptr;
4858     }
4859     return Result;
4860   }
4861 
4862   // C++14 [over.ics.list]p6:
4863   // C++11 [over.ics.list]p5:
4864   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4865   if (ToType->isReferenceType()) {
4866     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4867     // mention initializer lists in any way. So we go by what list-
4868     // initialization would do and try to extrapolate from that.
4869 
4870     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4871 
4872     // If the initializer list has a single element that is reference-related
4873     // to the parameter type, we initialize the reference from that.
4874     if (From->getNumInits() == 1) {
4875       Expr *Init = From->getInit(0);
4876 
4877       QualType T2 = Init->getType();
4878 
4879       // If the initializer is the address of an overloaded function, try
4880       // to resolve the overloaded function. If all goes well, T2 is the
4881       // type of the resulting function.
4882       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4883         DeclAccessPair Found;
4884         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4885                                    Init, ToType, false, Found))
4886           T2 = Fn->getType();
4887       }
4888 
4889       // Compute some basic properties of the types and the initializer.
4890       bool dummy1 = false;
4891       bool dummy2 = false;
4892       bool dummy3 = false;
4893       Sema::ReferenceCompareResult RefRelationship
4894         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4895                                          dummy2, dummy3);
4896 
4897       if (RefRelationship >= Sema::Ref_Related) {
4898         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4899                                 SuppressUserConversions,
4900                                 /*AllowExplicit=*/false);
4901       }
4902     }
4903 
4904     // Otherwise, we bind the reference to a temporary created from the
4905     // initializer list.
4906     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4907                                InOverloadResolution,
4908                                AllowObjCWritebackConversion);
4909     if (Result.isFailure())
4910       return Result;
4911     assert(!Result.isEllipsis() &&
4912            "Sub-initialization cannot result in ellipsis conversion.");
4913 
4914     // Can we even bind to a temporary?
4915     if (ToType->isRValueReferenceType() ||
4916         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4917       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4918                                             Result.UserDefined.After;
4919       SCS.ReferenceBinding = true;
4920       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4921       SCS.BindsToRvalue = true;
4922       SCS.BindsToFunctionLvalue = false;
4923       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4924       SCS.ObjCLifetimeConversionBinding = false;
4925     } else
4926       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4927                     From, ToType);
4928     return Result;
4929   }
4930 
4931   // C++14 [over.ics.list]p7:
4932   // C++11 [over.ics.list]p6:
4933   //   Otherwise, if the parameter type is not a class:
4934   if (!ToType->isRecordType()) {
4935     //    - if the initializer list has one element that is not itself an
4936     //      initializer list, the implicit conversion sequence is the one
4937     //      required to convert the element to the parameter type.
4938     unsigned NumInits = From->getNumInits();
4939     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4940       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4941                                      SuppressUserConversions,
4942                                      InOverloadResolution,
4943                                      AllowObjCWritebackConversion);
4944     //    - if the initializer list has no elements, the implicit conversion
4945     //      sequence is the identity conversion.
4946     else if (NumInits == 0) {
4947       Result.setStandard();
4948       Result.Standard.setAsIdentityConversion();
4949       Result.Standard.setFromType(ToType);
4950       Result.Standard.setAllToTypes(ToType);
4951     }
4952     return Result;
4953   }
4954 
4955   // C++14 [over.ics.list]p8:
4956   // C++11 [over.ics.list]p7:
4957   //   In all cases other than those enumerated above, no conversion is possible
4958   return Result;
4959 }
4960 
4961 /// TryCopyInitialization - Try to copy-initialize a value of type
4962 /// ToType from the expression From. Return the implicit conversion
4963 /// sequence required to pass this argument, which may be a bad
4964 /// conversion sequence (meaning that the argument cannot be passed to
4965 /// a parameter of this type). If @p SuppressUserConversions, then we
4966 /// do not permit any user-defined conversion sequences.
4967 static ImplicitConversionSequence
4968 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4969                       bool SuppressUserConversions,
4970                       bool InOverloadResolution,
4971                       bool AllowObjCWritebackConversion,
4972                       bool AllowExplicit) {
4973   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4974     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4975                              InOverloadResolution,AllowObjCWritebackConversion);
4976 
4977   if (ToType->isReferenceType())
4978     return TryReferenceInit(S, From, ToType,
4979                             /*FIXME:*/From->getLocStart(),
4980                             SuppressUserConversions,
4981                             AllowExplicit);
4982 
4983   return TryImplicitConversion(S, From, ToType,
4984                                SuppressUserConversions,
4985                                /*AllowExplicit=*/false,
4986                                InOverloadResolution,
4987                                /*CStyle=*/false,
4988                                AllowObjCWritebackConversion,
4989                                /*AllowObjCConversionOnExplicit=*/false);
4990 }
4991 
4992 static bool TryCopyInitialization(const CanQualType FromQTy,
4993                                   const CanQualType ToQTy,
4994                                   Sema &S,
4995                                   SourceLocation Loc,
4996                                   ExprValueKind FromVK) {
4997   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4998   ImplicitConversionSequence ICS =
4999     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5000 
5001   return !ICS.isBad();
5002 }
5003 
5004 /// TryObjectArgumentInitialization - Try to initialize the object
5005 /// parameter of the given member function (@c Method) from the
5006 /// expression @p From.
5007 static ImplicitConversionSequence
5008 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5009                                 Expr::Classification FromClassification,
5010                                 CXXMethodDecl *Method,
5011                                 CXXRecordDecl *ActingContext) {
5012   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5013   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5014   //                 const volatile object.
5015   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5016     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5017   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5018 
5019   // Set up the conversion sequence as a "bad" conversion, to allow us
5020   // to exit early.
5021   ImplicitConversionSequence ICS;
5022 
5023   // We need to have an object of class type.
5024   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5025     FromType = PT->getPointeeType();
5026 
5027     // When we had a pointer, it's implicitly dereferenced, so we
5028     // better have an lvalue.
5029     assert(FromClassification.isLValue());
5030   }
5031 
5032   assert(FromType->isRecordType());
5033 
5034   // C++0x [over.match.funcs]p4:
5035   //   For non-static member functions, the type of the implicit object
5036   //   parameter is
5037   //
5038   //     - "lvalue reference to cv X" for functions declared without a
5039   //        ref-qualifier or with the & ref-qualifier
5040   //     - "rvalue reference to cv X" for functions declared with the &&
5041   //        ref-qualifier
5042   //
5043   // where X is the class of which the function is a member and cv is the
5044   // cv-qualification on the member function declaration.
5045   //
5046   // However, when finding an implicit conversion sequence for the argument, we
5047   // are not allowed to perform user-defined conversions
5048   // (C++ [over.match.funcs]p5). We perform a simplified version of
5049   // reference binding here, that allows class rvalues to bind to
5050   // non-constant references.
5051 
5052   // First check the qualifiers.
5053   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5054   if (ImplicitParamType.getCVRQualifiers()
5055                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5056       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5057     ICS.setBad(BadConversionSequence::bad_qualifiers,
5058                FromType, ImplicitParamType);
5059     return ICS;
5060   }
5061 
5062   // Check that we have either the same type or a derived type. It
5063   // affects the conversion rank.
5064   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5065   ImplicitConversionKind SecondKind;
5066   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5067     SecondKind = ICK_Identity;
5068   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5069     SecondKind = ICK_Derived_To_Base;
5070   else {
5071     ICS.setBad(BadConversionSequence::unrelated_class,
5072                FromType, ImplicitParamType);
5073     return ICS;
5074   }
5075 
5076   // Check the ref-qualifier.
5077   switch (Method->getRefQualifier()) {
5078   case RQ_None:
5079     // Do nothing; we don't care about lvalueness or rvalueness.
5080     break;
5081 
5082   case RQ_LValue:
5083     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5084       // non-const lvalue reference cannot bind to an rvalue
5085       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5086                  ImplicitParamType);
5087       return ICS;
5088     }
5089     break;
5090 
5091   case RQ_RValue:
5092     if (!FromClassification.isRValue()) {
5093       // rvalue reference cannot bind to an lvalue
5094       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5095                  ImplicitParamType);
5096       return ICS;
5097     }
5098     break;
5099   }
5100 
5101   // Success. Mark this as a reference binding.
5102   ICS.setStandard();
5103   ICS.Standard.setAsIdentityConversion();
5104   ICS.Standard.Second = SecondKind;
5105   ICS.Standard.setFromType(FromType);
5106   ICS.Standard.setAllToTypes(ImplicitParamType);
5107   ICS.Standard.ReferenceBinding = true;
5108   ICS.Standard.DirectBinding = true;
5109   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5110   ICS.Standard.BindsToFunctionLvalue = false;
5111   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5112   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5113     = (Method->getRefQualifier() == RQ_None);
5114   return ICS;
5115 }
5116 
5117 /// PerformObjectArgumentInitialization - Perform initialization of
5118 /// the implicit object parameter for the given Method with the given
5119 /// expression.
5120 ExprResult
5121 Sema::PerformObjectArgumentInitialization(Expr *From,
5122                                           NestedNameSpecifier *Qualifier,
5123                                           NamedDecl *FoundDecl,
5124                                           CXXMethodDecl *Method) {
5125   QualType FromRecordType, DestType;
5126   QualType ImplicitParamRecordType  =
5127     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5128 
5129   Expr::Classification FromClassification;
5130   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5131     FromRecordType = PT->getPointeeType();
5132     DestType = Method->getThisType(Context);
5133     FromClassification = Expr::Classification::makeSimpleLValue();
5134   } else {
5135     FromRecordType = From->getType();
5136     DestType = ImplicitParamRecordType;
5137     FromClassification = From->Classify(Context);
5138   }
5139 
5140   // Note that we always use the true parent context when performing
5141   // the actual argument initialization.
5142   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5143       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5144       Method->getParent());
5145   if (ICS.isBad()) {
5146     switch (ICS.Bad.Kind) {
5147     case BadConversionSequence::bad_qualifiers: {
5148       Qualifiers FromQs = FromRecordType.getQualifiers();
5149       Qualifiers ToQs = DestType.getQualifiers();
5150       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5151       if (CVR) {
5152         Diag(From->getLocStart(),
5153              diag::err_member_function_call_bad_cvr)
5154           << Method->getDeclName() << FromRecordType << (CVR - 1)
5155           << From->getSourceRange();
5156         Diag(Method->getLocation(), diag::note_previous_decl)
5157           << Method->getDeclName();
5158         return ExprError();
5159       }
5160       break;
5161     }
5162 
5163     case BadConversionSequence::lvalue_ref_to_rvalue:
5164     case BadConversionSequence::rvalue_ref_to_lvalue: {
5165       bool IsRValueQualified =
5166         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5167       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5168         << Method->getDeclName() << FromClassification.isRValue()
5169         << IsRValueQualified;
5170       Diag(Method->getLocation(), diag::note_previous_decl)
5171         << Method->getDeclName();
5172       return ExprError();
5173     }
5174 
5175     case BadConversionSequence::no_conversion:
5176     case BadConversionSequence::unrelated_class:
5177       break;
5178     }
5179 
5180     return Diag(From->getLocStart(),
5181                 diag::err_member_function_call_bad_type)
5182        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5183   }
5184 
5185   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5186     ExprResult FromRes =
5187       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5188     if (FromRes.isInvalid())
5189       return ExprError();
5190     From = FromRes.get();
5191   }
5192 
5193   if (!Context.hasSameType(From->getType(), DestType))
5194     From = ImpCastExprToType(From, DestType, CK_NoOp,
5195                              From->getValueKind()).get();
5196   return From;
5197 }
5198 
5199 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5200 /// expression From to bool (C++0x [conv]p3).
5201 static ImplicitConversionSequence
5202 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5203   return TryImplicitConversion(S, From, S.Context.BoolTy,
5204                                /*SuppressUserConversions=*/false,
5205                                /*AllowExplicit=*/true,
5206                                /*InOverloadResolution=*/false,
5207                                /*CStyle=*/false,
5208                                /*AllowObjCWritebackConversion=*/false,
5209                                /*AllowObjCConversionOnExplicit=*/false);
5210 }
5211 
5212 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5213 /// of the expression From to bool (C++0x [conv]p3).
5214 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5215   if (checkPlaceholderForOverload(*this, From))
5216     return ExprError();
5217 
5218   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5219   if (!ICS.isBad())
5220     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5221 
5222   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5223     return Diag(From->getLocStart(),
5224                 diag::err_typecheck_bool_condition)
5225                   << From->getType() << From->getSourceRange();
5226   return ExprError();
5227 }
5228 
5229 /// Check that the specified conversion is permitted in a converted constant
5230 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5231 /// is acceptable.
5232 static bool CheckConvertedConstantConversions(Sema &S,
5233                                               StandardConversionSequence &SCS) {
5234   // Since we know that the target type is an integral or unscoped enumeration
5235   // type, most conversion kinds are impossible. All possible First and Third
5236   // conversions are fine.
5237   switch (SCS.Second) {
5238   case ICK_Identity:
5239   case ICK_Function_Conversion:
5240   case ICK_Integral_Promotion:
5241   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5242   case ICK_Zero_Queue_Conversion:
5243     return true;
5244 
5245   case ICK_Boolean_Conversion:
5246     // Conversion from an integral or unscoped enumeration type to bool is
5247     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5248     // conversion, so we allow it in a converted constant expression.
5249     //
5250     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5251     // a lot of popular code. We should at least add a warning for this
5252     // (non-conforming) extension.
5253     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5254            SCS.getToType(2)->isBooleanType();
5255 
5256   case ICK_Pointer_Conversion:
5257   case ICK_Pointer_Member:
5258     // C++1z: null pointer conversions and null member pointer conversions are
5259     // only permitted if the source type is std::nullptr_t.
5260     return SCS.getFromType()->isNullPtrType();
5261 
5262   case ICK_Floating_Promotion:
5263   case ICK_Complex_Promotion:
5264   case ICK_Floating_Conversion:
5265   case ICK_Complex_Conversion:
5266   case ICK_Floating_Integral:
5267   case ICK_Compatible_Conversion:
5268   case ICK_Derived_To_Base:
5269   case ICK_Vector_Conversion:
5270   case ICK_Vector_Splat:
5271   case ICK_Complex_Real:
5272   case ICK_Block_Pointer_Conversion:
5273   case ICK_TransparentUnionConversion:
5274   case ICK_Writeback_Conversion:
5275   case ICK_Zero_Event_Conversion:
5276   case ICK_C_Only_Conversion:
5277   case ICK_Incompatible_Pointer_Conversion:
5278     return false;
5279 
5280   case ICK_Lvalue_To_Rvalue:
5281   case ICK_Array_To_Pointer:
5282   case ICK_Function_To_Pointer:
5283     llvm_unreachable("found a first conversion kind in Second");
5284 
5285   case ICK_Qualification:
5286     llvm_unreachable("found a third conversion kind in Second");
5287 
5288   case ICK_Num_Conversion_Kinds:
5289     break;
5290   }
5291 
5292   llvm_unreachable("unknown conversion kind");
5293 }
5294 
5295 /// CheckConvertedConstantExpression - Check that the expression From is a
5296 /// converted constant expression of type T, perform the conversion and produce
5297 /// the converted expression, per C++11 [expr.const]p3.
5298 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5299                                                    QualType T, APValue &Value,
5300                                                    Sema::CCEKind CCE,
5301                                                    bool RequireInt) {
5302   assert(S.getLangOpts().CPlusPlus11 &&
5303          "converted constant expression outside C++11");
5304 
5305   if (checkPlaceholderForOverload(S, From))
5306     return ExprError();
5307 
5308   // C++1z [expr.const]p3:
5309   //  A converted constant expression of type T is an expression,
5310   //  implicitly converted to type T, where the converted
5311   //  expression is a constant expression and the implicit conversion
5312   //  sequence contains only [... list of conversions ...].
5313   // C++1z [stmt.if]p2:
5314   //  If the if statement is of the form if constexpr, the value of the
5315   //  condition shall be a contextually converted constant expression of type
5316   //  bool.
5317   ImplicitConversionSequence ICS =
5318       CCE == Sema::CCEK_ConstexprIf
5319           ? TryContextuallyConvertToBool(S, From)
5320           : TryCopyInitialization(S, From, T,
5321                                   /*SuppressUserConversions=*/false,
5322                                   /*InOverloadResolution=*/false,
5323                                   /*AllowObjcWritebackConversion=*/false,
5324                                   /*AllowExplicit=*/false);
5325   StandardConversionSequence *SCS = nullptr;
5326   switch (ICS.getKind()) {
5327   case ImplicitConversionSequence::StandardConversion:
5328     SCS = &ICS.Standard;
5329     break;
5330   case ImplicitConversionSequence::UserDefinedConversion:
5331     // We are converting to a non-class type, so the Before sequence
5332     // must be trivial.
5333     SCS = &ICS.UserDefined.After;
5334     break;
5335   case ImplicitConversionSequence::AmbiguousConversion:
5336   case ImplicitConversionSequence::BadConversion:
5337     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5338       return S.Diag(From->getLocStart(),
5339                     diag::err_typecheck_converted_constant_expression)
5340                 << From->getType() << From->getSourceRange() << T;
5341     return ExprError();
5342 
5343   case ImplicitConversionSequence::EllipsisConversion:
5344     llvm_unreachable("ellipsis conversion in converted constant expression");
5345   }
5346 
5347   // Check that we would only use permitted conversions.
5348   if (!CheckConvertedConstantConversions(S, *SCS)) {
5349     return S.Diag(From->getLocStart(),
5350                   diag::err_typecheck_converted_constant_expression_disallowed)
5351              << From->getType() << From->getSourceRange() << T;
5352   }
5353   // [...] and where the reference binding (if any) binds directly.
5354   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5355     return S.Diag(From->getLocStart(),
5356                   diag::err_typecheck_converted_constant_expression_indirect)
5357              << From->getType() << From->getSourceRange() << T;
5358   }
5359 
5360   ExprResult Result =
5361       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5362   if (Result.isInvalid())
5363     return Result;
5364 
5365   // Check for a narrowing implicit conversion.
5366   APValue PreNarrowingValue;
5367   QualType PreNarrowingType;
5368   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5369                                 PreNarrowingType)) {
5370   case NK_Dependent_Narrowing:
5371     // Implicit conversion to a narrower type, but the expression is
5372     // value-dependent so we can't tell whether it's actually narrowing.
5373   case NK_Variable_Narrowing:
5374     // Implicit conversion to a narrower type, and the value is not a constant
5375     // expression. We'll diagnose this in a moment.
5376   case NK_Not_Narrowing:
5377     break;
5378 
5379   case NK_Constant_Narrowing:
5380     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5381       << CCE << /*Constant*/1
5382       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5383     break;
5384 
5385   case NK_Type_Narrowing:
5386     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5387       << CCE << /*Constant*/0 << From->getType() << T;
5388     break;
5389   }
5390 
5391   if (Result.get()->isValueDependent()) {
5392     Value = APValue();
5393     return Result;
5394   }
5395 
5396   // Check the expression is a constant expression.
5397   SmallVector<PartialDiagnosticAt, 8> Notes;
5398   Expr::EvalResult Eval;
5399   Eval.Diag = &Notes;
5400 
5401   if ((T->isReferenceType()
5402            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5403            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5404       (RequireInt && !Eval.Val.isInt())) {
5405     // The expression can't be folded, so we can't keep it at this position in
5406     // the AST.
5407     Result = ExprError();
5408   } else {
5409     Value = Eval.Val;
5410 
5411     if (Notes.empty()) {
5412       // It's a constant expression.
5413       return Result;
5414     }
5415   }
5416 
5417   // It's not a constant expression. Produce an appropriate diagnostic.
5418   if (Notes.size() == 1 &&
5419       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5420     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5421   else {
5422     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5423       << CCE << From->getSourceRange();
5424     for (unsigned I = 0; I < Notes.size(); ++I)
5425       S.Diag(Notes[I].first, Notes[I].second);
5426   }
5427   return ExprError();
5428 }
5429 
5430 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5431                                                   APValue &Value, CCEKind CCE) {
5432   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5433 }
5434 
5435 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5436                                                   llvm::APSInt &Value,
5437                                                   CCEKind CCE) {
5438   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5439 
5440   APValue V;
5441   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5442   if (!R.isInvalid() && !R.get()->isValueDependent())
5443     Value = V.getInt();
5444   return R;
5445 }
5446 
5447 
5448 /// dropPointerConversions - If the given standard conversion sequence
5449 /// involves any pointer conversions, remove them.  This may change
5450 /// the result type of the conversion sequence.
5451 static void dropPointerConversion(StandardConversionSequence &SCS) {
5452   if (SCS.Second == ICK_Pointer_Conversion) {
5453     SCS.Second = ICK_Identity;
5454     SCS.Third = ICK_Identity;
5455     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5456   }
5457 }
5458 
5459 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5460 /// convert the expression From to an Objective-C pointer type.
5461 static ImplicitConversionSequence
5462 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5463   // Do an implicit conversion to 'id'.
5464   QualType Ty = S.Context.getObjCIdType();
5465   ImplicitConversionSequence ICS
5466     = TryImplicitConversion(S, From, Ty,
5467                             // FIXME: Are these flags correct?
5468                             /*SuppressUserConversions=*/false,
5469                             /*AllowExplicit=*/true,
5470                             /*InOverloadResolution=*/false,
5471                             /*CStyle=*/false,
5472                             /*AllowObjCWritebackConversion=*/false,
5473                             /*AllowObjCConversionOnExplicit=*/true);
5474 
5475   // Strip off any final conversions to 'id'.
5476   switch (ICS.getKind()) {
5477   case ImplicitConversionSequence::BadConversion:
5478   case ImplicitConversionSequence::AmbiguousConversion:
5479   case ImplicitConversionSequence::EllipsisConversion:
5480     break;
5481 
5482   case ImplicitConversionSequence::UserDefinedConversion:
5483     dropPointerConversion(ICS.UserDefined.After);
5484     break;
5485 
5486   case ImplicitConversionSequence::StandardConversion:
5487     dropPointerConversion(ICS.Standard);
5488     break;
5489   }
5490 
5491   return ICS;
5492 }
5493 
5494 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5495 /// conversion of the expression From to an Objective-C pointer type.
5496 /// Returns a valid but null ExprResult if no conversion sequence exists.
5497 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5498   if (checkPlaceholderForOverload(*this, From))
5499     return ExprError();
5500 
5501   QualType Ty = Context.getObjCIdType();
5502   ImplicitConversionSequence ICS =
5503     TryContextuallyConvertToObjCPointer(*this, From);
5504   if (!ICS.isBad())
5505     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5506   return ExprResult();
5507 }
5508 
5509 /// Determine whether the provided type is an integral type, or an enumeration
5510 /// type of a permitted flavor.
5511 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5512   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5513                                  : T->isIntegralOrUnscopedEnumerationType();
5514 }
5515 
5516 static ExprResult
5517 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5518                             Sema::ContextualImplicitConverter &Converter,
5519                             QualType T, UnresolvedSetImpl &ViableConversions) {
5520 
5521   if (Converter.Suppress)
5522     return ExprError();
5523 
5524   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5525   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5526     CXXConversionDecl *Conv =
5527         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5528     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5529     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5530   }
5531   return From;
5532 }
5533 
5534 static bool
5535 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5536                            Sema::ContextualImplicitConverter &Converter,
5537                            QualType T, bool HadMultipleCandidates,
5538                            UnresolvedSetImpl &ExplicitConversions) {
5539   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5540     DeclAccessPair Found = ExplicitConversions[0];
5541     CXXConversionDecl *Conversion =
5542         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5543 
5544     // The user probably meant to invoke the given explicit
5545     // conversion; use it.
5546     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5547     std::string TypeStr;
5548     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5549 
5550     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5551         << FixItHint::CreateInsertion(From->getLocStart(),
5552                                       "static_cast<" + TypeStr + ">(")
5553         << FixItHint::CreateInsertion(
5554                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5555     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5556 
5557     // If we aren't in a SFINAE context, build a call to the
5558     // explicit conversion function.
5559     if (SemaRef.isSFINAEContext())
5560       return true;
5561 
5562     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5563     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5564                                                        HadMultipleCandidates);
5565     if (Result.isInvalid())
5566       return true;
5567     // Record usage of conversion in an implicit cast.
5568     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5569                                     CK_UserDefinedConversion, Result.get(),
5570                                     nullptr, Result.get()->getValueKind());
5571   }
5572   return false;
5573 }
5574 
5575 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5576                              Sema::ContextualImplicitConverter &Converter,
5577                              QualType T, bool HadMultipleCandidates,
5578                              DeclAccessPair &Found) {
5579   CXXConversionDecl *Conversion =
5580       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5581   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5582 
5583   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5584   if (!Converter.SuppressConversion) {
5585     if (SemaRef.isSFINAEContext())
5586       return true;
5587 
5588     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5589         << From->getSourceRange();
5590   }
5591 
5592   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5593                                                      HadMultipleCandidates);
5594   if (Result.isInvalid())
5595     return true;
5596   // Record usage of conversion in an implicit cast.
5597   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5598                                   CK_UserDefinedConversion, Result.get(),
5599                                   nullptr, Result.get()->getValueKind());
5600   return false;
5601 }
5602 
5603 static ExprResult finishContextualImplicitConversion(
5604     Sema &SemaRef, SourceLocation Loc, Expr *From,
5605     Sema::ContextualImplicitConverter &Converter) {
5606   if (!Converter.match(From->getType()) && !Converter.Suppress)
5607     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5608         << From->getSourceRange();
5609 
5610   return SemaRef.DefaultLvalueConversion(From);
5611 }
5612 
5613 static void
5614 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5615                                   UnresolvedSetImpl &ViableConversions,
5616                                   OverloadCandidateSet &CandidateSet) {
5617   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5618     DeclAccessPair FoundDecl = ViableConversions[I];
5619     NamedDecl *D = FoundDecl.getDecl();
5620     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5621     if (isa<UsingShadowDecl>(D))
5622       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5623 
5624     CXXConversionDecl *Conv;
5625     FunctionTemplateDecl *ConvTemplate;
5626     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5627       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5628     else
5629       Conv = cast<CXXConversionDecl>(D);
5630 
5631     if (ConvTemplate)
5632       SemaRef.AddTemplateConversionCandidate(
5633         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5634         /*AllowObjCConversionOnExplicit=*/false);
5635     else
5636       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5637                                      ToType, CandidateSet,
5638                                      /*AllowObjCConversionOnExplicit=*/false);
5639   }
5640 }
5641 
5642 /// \brief Attempt to convert the given expression to a type which is accepted
5643 /// by the given converter.
5644 ///
5645 /// This routine will attempt to convert an expression of class type to a
5646 /// type accepted by the specified converter. In C++11 and before, the class
5647 /// must have a single non-explicit conversion function converting to a matching
5648 /// type. In C++1y, there can be multiple such conversion functions, but only
5649 /// one target type.
5650 ///
5651 /// \param Loc The source location of the construct that requires the
5652 /// conversion.
5653 ///
5654 /// \param From The expression we're converting from.
5655 ///
5656 /// \param Converter Used to control and diagnose the conversion process.
5657 ///
5658 /// \returns The expression, converted to an integral or enumeration type if
5659 /// successful.
5660 ExprResult Sema::PerformContextualImplicitConversion(
5661     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5662   // We can't perform any more checking for type-dependent expressions.
5663   if (From->isTypeDependent())
5664     return From;
5665 
5666   // Process placeholders immediately.
5667   if (From->hasPlaceholderType()) {
5668     ExprResult result = CheckPlaceholderExpr(From);
5669     if (result.isInvalid())
5670       return result;
5671     From = result.get();
5672   }
5673 
5674   // If the expression already has a matching type, we're golden.
5675   QualType T = From->getType();
5676   if (Converter.match(T))
5677     return DefaultLvalueConversion(From);
5678 
5679   // FIXME: Check for missing '()' if T is a function type?
5680 
5681   // We can only perform contextual implicit conversions on objects of class
5682   // type.
5683   const RecordType *RecordTy = T->getAs<RecordType>();
5684   if (!RecordTy || !getLangOpts().CPlusPlus) {
5685     if (!Converter.Suppress)
5686       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5687     return From;
5688   }
5689 
5690   // We must have a complete class type.
5691   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5692     ContextualImplicitConverter &Converter;
5693     Expr *From;
5694 
5695     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5696         : Converter(Converter), From(From) {}
5697 
5698     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5699       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5700     }
5701   } IncompleteDiagnoser(Converter, From);
5702 
5703   if (Converter.Suppress ? !isCompleteType(Loc, T)
5704                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5705     return From;
5706 
5707   // Look for a conversion to an integral or enumeration type.
5708   UnresolvedSet<4>
5709       ViableConversions; // These are *potentially* viable in C++1y.
5710   UnresolvedSet<4> ExplicitConversions;
5711   const auto &Conversions =
5712       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5713 
5714   bool HadMultipleCandidates =
5715       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5716 
5717   // To check that there is only one target type, in C++1y:
5718   QualType ToType;
5719   bool HasUniqueTargetType = true;
5720 
5721   // Collect explicit or viable (potentially in C++1y) conversions.
5722   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5723     NamedDecl *D = (*I)->getUnderlyingDecl();
5724     CXXConversionDecl *Conversion;
5725     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5726     if (ConvTemplate) {
5727       if (getLangOpts().CPlusPlus14)
5728         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5729       else
5730         continue; // C++11 does not consider conversion operator templates(?).
5731     } else
5732       Conversion = cast<CXXConversionDecl>(D);
5733 
5734     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5735            "Conversion operator templates are considered potentially "
5736            "viable in C++1y");
5737 
5738     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5739     if (Converter.match(CurToType) || ConvTemplate) {
5740 
5741       if (Conversion->isExplicit()) {
5742         // FIXME: For C++1y, do we need this restriction?
5743         // cf. diagnoseNoViableConversion()
5744         if (!ConvTemplate)
5745           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5746       } else {
5747         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5748           if (ToType.isNull())
5749             ToType = CurToType.getUnqualifiedType();
5750           else if (HasUniqueTargetType &&
5751                    (CurToType.getUnqualifiedType() != ToType))
5752             HasUniqueTargetType = false;
5753         }
5754         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5755       }
5756     }
5757   }
5758 
5759   if (getLangOpts().CPlusPlus14) {
5760     // C++1y [conv]p6:
5761     // ... An expression e of class type E appearing in such a context
5762     // is said to be contextually implicitly converted to a specified
5763     // type T and is well-formed if and only if e can be implicitly
5764     // converted to a type T that is determined as follows: E is searched
5765     // for conversion functions whose return type is cv T or reference to
5766     // cv T such that T is allowed by the context. There shall be
5767     // exactly one such T.
5768 
5769     // If no unique T is found:
5770     if (ToType.isNull()) {
5771       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5772                                      HadMultipleCandidates,
5773                                      ExplicitConversions))
5774         return ExprError();
5775       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5776     }
5777 
5778     // If more than one unique Ts are found:
5779     if (!HasUniqueTargetType)
5780       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5781                                          ViableConversions);
5782 
5783     // If one unique T is found:
5784     // First, build a candidate set from the previously recorded
5785     // potentially viable conversions.
5786     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5787     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5788                                       CandidateSet);
5789 
5790     // Then, perform overload resolution over the candidate set.
5791     OverloadCandidateSet::iterator Best;
5792     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5793     case OR_Success: {
5794       // Apply this conversion.
5795       DeclAccessPair Found =
5796           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5797       if (recordConversion(*this, Loc, From, Converter, T,
5798                            HadMultipleCandidates, Found))
5799         return ExprError();
5800       break;
5801     }
5802     case OR_Ambiguous:
5803       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5804                                          ViableConversions);
5805     case OR_No_Viable_Function:
5806       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5807                                      HadMultipleCandidates,
5808                                      ExplicitConversions))
5809         return ExprError();
5810       LLVM_FALLTHROUGH;
5811     case OR_Deleted:
5812       // We'll complain below about a non-integral condition type.
5813       break;
5814     }
5815   } else {
5816     switch (ViableConversions.size()) {
5817     case 0: {
5818       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5819                                      HadMultipleCandidates,
5820                                      ExplicitConversions))
5821         return ExprError();
5822 
5823       // We'll complain below about a non-integral condition type.
5824       break;
5825     }
5826     case 1: {
5827       // Apply this conversion.
5828       DeclAccessPair Found = ViableConversions[0];
5829       if (recordConversion(*this, Loc, From, Converter, T,
5830                            HadMultipleCandidates, Found))
5831         return ExprError();
5832       break;
5833     }
5834     default:
5835       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5836                                          ViableConversions);
5837     }
5838   }
5839 
5840   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5841 }
5842 
5843 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5844 /// an acceptable non-member overloaded operator for a call whose
5845 /// arguments have types T1 (and, if non-empty, T2). This routine
5846 /// implements the check in C++ [over.match.oper]p3b2 concerning
5847 /// enumeration types.
5848 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5849                                                    FunctionDecl *Fn,
5850                                                    ArrayRef<Expr *> Args) {
5851   QualType T1 = Args[0]->getType();
5852   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5853 
5854   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5855     return true;
5856 
5857   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5858     return true;
5859 
5860   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5861   if (Proto->getNumParams() < 1)
5862     return false;
5863 
5864   if (T1->isEnumeralType()) {
5865     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5866     if (Context.hasSameUnqualifiedType(T1, ArgType))
5867       return true;
5868   }
5869 
5870   if (Proto->getNumParams() < 2)
5871     return false;
5872 
5873   if (!T2.isNull() && T2->isEnumeralType()) {
5874     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5875     if (Context.hasSameUnqualifiedType(T2, ArgType))
5876       return true;
5877   }
5878 
5879   return false;
5880 }
5881 
5882 /// AddOverloadCandidate - Adds the given function to the set of
5883 /// candidate functions, using the given function call arguments.  If
5884 /// @p SuppressUserConversions, then don't allow user-defined
5885 /// conversions via constructors or conversion operators.
5886 ///
5887 /// \param PartialOverloading true if we are performing "partial" overloading
5888 /// based on an incomplete set of function arguments. This feature is used by
5889 /// code completion.
5890 void
5891 Sema::AddOverloadCandidate(FunctionDecl *Function,
5892                            DeclAccessPair FoundDecl,
5893                            ArrayRef<Expr *> Args,
5894                            OverloadCandidateSet &CandidateSet,
5895                            bool SuppressUserConversions,
5896                            bool PartialOverloading,
5897                            bool AllowExplicit,
5898                            ConversionSequenceList EarlyConversions) {
5899   const FunctionProtoType *Proto
5900     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5901   assert(Proto && "Functions without a prototype cannot be overloaded");
5902   assert(!Function->getDescribedFunctionTemplate() &&
5903          "Use AddTemplateOverloadCandidate for function templates");
5904 
5905   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5906     if (!isa<CXXConstructorDecl>(Method)) {
5907       // If we get here, it's because we're calling a member function
5908       // that is named without a member access expression (e.g.,
5909       // "this->f") that was either written explicitly or created
5910       // implicitly. This can happen with a qualified call to a member
5911       // function, e.g., X::f(). We use an empty type for the implied
5912       // object argument (C++ [over.call.func]p3), and the acting context
5913       // is irrelevant.
5914       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5915                          Expr::Classification::makeSimpleLValue(), Args,
5916                          CandidateSet, SuppressUserConversions,
5917                          PartialOverloading, EarlyConversions);
5918       return;
5919     }
5920     // We treat a constructor like a non-member function, since its object
5921     // argument doesn't participate in overload resolution.
5922   }
5923 
5924   if (!CandidateSet.isNewCandidate(Function))
5925     return;
5926 
5927   // C++ [over.match.oper]p3:
5928   //   if no operand has a class type, only those non-member functions in the
5929   //   lookup set that have a first parameter of type T1 or "reference to
5930   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5931   //   is a right operand) a second parameter of type T2 or "reference to
5932   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5933   //   candidate functions.
5934   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5935       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5936     return;
5937 
5938   // C++11 [class.copy]p11: [DR1402]
5939   //   A defaulted move constructor that is defined as deleted is ignored by
5940   //   overload resolution.
5941   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5942   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5943       Constructor->isMoveConstructor())
5944     return;
5945 
5946   // Overload resolution is always an unevaluated context.
5947   EnterExpressionEvaluationContext Unevaluated(
5948       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5949 
5950   // Add this candidate
5951   OverloadCandidate &Candidate =
5952       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5953   Candidate.FoundDecl = FoundDecl;
5954   Candidate.Function = Function;
5955   Candidate.Viable = true;
5956   Candidate.IsSurrogate = false;
5957   Candidate.IgnoreObjectArgument = false;
5958   Candidate.ExplicitCallArguments = Args.size();
5959 
5960   if (Function->isMultiVersion() &&
5961       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5962     Candidate.Viable = false;
5963     Candidate.FailureKind = ovl_non_default_multiversion_function;
5964     return;
5965   }
5966 
5967   if (Constructor) {
5968     // C++ [class.copy]p3:
5969     //   A member function template is never instantiated to perform the copy
5970     //   of a class object to an object of its class type.
5971     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5972     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5973         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5974          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5975                        ClassType))) {
5976       Candidate.Viable = false;
5977       Candidate.FailureKind = ovl_fail_illegal_constructor;
5978       return;
5979     }
5980 
5981     // C++ [over.match.funcs]p8: (proposed DR resolution)
5982     //   A constructor inherited from class type C that has a first parameter
5983     //   of type "reference to P" (including such a constructor instantiated
5984     //   from a template) is excluded from the set of candidate functions when
5985     //   constructing an object of type cv D if the argument list has exactly
5986     //   one argument and D is reference-related to P and P is reference-related
5987     //   to C.
5988     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5989     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5990         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5991       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5992       QualType C = Context.getRecordType(Constructor->getParent());
5993       QualType D = Context.getRecordType(Shadow->getParent());
5994       SourceLocation Loc = Args.front()->getExprLoc();
5995       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5996           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5997         Candidate.Viable = false;
5998         Candidate.FailureKind = ovl_fail_inhctor_slice;
5999         return;
6000       }
6001     }
6002   }
6003 
6004   unsigned NumParams = Proto->getNumParams();
6005 
6006   // (C++ 13.3.2p2): A candidate function having fewer than m
6007   // parameters is viable only if it has an ellipsis in its parameter
6008   // list (8.3.5).
6009   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6010       !Proto->isVariadic()) {
6011     Candidate.Viable = false;
6012     Candidate.FailureKind = ovl_fail_too_many_arguments;
6013     return;
6014   }
6015 
6016   // (C++ 13.3.2p2): A candidate function having more than m parameters
6017   // is viable only if the (m+1)st parameter has a default argument
6018   // (8.3.6). For the purposes of overload resolution, the
6019   // parameter list is truncated on the right, so that there are
6020   // exactly m parameters.
6021   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6022   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6023     // Not enough arguments.
6024     Candidate.Viable = false;
6025     Candidate.FailureKind = ovl_fail_too_few_arguments;
6026     return;
6027   }
6028 
6029   // (CUDA B.1): Check for invalid calls between targets.
6030   if (getLangOpts().CUDA)
6031     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6032       // Skip the check for callers that are implicit members, because in this
6033       // case we may not yet know what the member's target is; the target is
6034       // inferred for the member automatically, based on the bases and fields of
6035       // the class.
6036       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6037         Candidate.Viable = false;
6038         Candidate.FailureKind = ovl_fail_bad_target;
6039         return;
6040       }
6041 
6042   // Determine the implicit conversion sequences for each of the
6043   // arguments.
6044   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6045     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6046       // We already formed a conversion sequence for this parameter during
6047       // template argument deduction.
6048     } else if (ArgIdx < NumParams) {
6049       // (C++ 13.3.2p3): for F to be a viable function, there shall
6050       // exist for each argument an implicit conversion sequence
6051       // (13.3.3.1) that converts that argument to the corresponding
6052       // parameter of F.
6053       QualType ParamType = Proto->getParamType(ArgIdx);
6054       Candidate.Conversions[ArgIdx]
6055         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6056                                 SuppressUserConversions,
6057                                 /*InOverloadResolution=*/true,
6058                                 /*AllowObjCWritebackConversion=*/
6059                                   getLangOpts().ObjCAutoRefCount,
6060                                 AllowExplicit);
6061       if (Candidate.Conversions[ArgIdx].isBad()) {
6062         Candidate.Viable = false;
6063         Candidate.FailureKind = ovl_fail_bad_conversion;
6064         return;
6065       }
6066     } else {
6067       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6068       // argument for which there is no corresponding parameter is
6069       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6070       Candidate.Conversions[ArgIdx].setEllipsis();
6071     }
6072   }
6073 
6074   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6075     Candidate.Viable = false;
6076     Candidate.FailureKind = ovl_fail_enable_if;
6077     Candidate.DeductionFailure.Data = FailedAttr;
6078     return;
6079   }
6080 
6081   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6082     Candidate.Viable = false;
6083     Candidate.FailureKind = ovl_fail_ext_disabled;
6084     return;
6085   }
6086 }
6087 
6088 ObjCMethodDecl *
6089 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6090                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6091   if (Methods.size() <= 1)
6092     return nullptr;
6093 
6094   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6095     bool Match = true;
6096     ObjCMethodDecl *Method = Methods[b];
6097     unsigned NumNamedArgs = Sel.getNumArgs();
6098     // Method might have more arguments than selector indicates. This is due
6099     // to addition of c-style arguments in method.
6100     if (Method->param_size() > NumNamedArgs)
6101       NumNamedArgs = Method->param_size();
6102     if (Args.size() < NumNamedArgs)
6103       continue;
6104 
6105     for (unsigned i = 0; i < NumNamedArgs; i++) {
6106       // We can't do any type-checking on a type-dependent argument.
6107       if (Args[i]->isTypeDependent()) {
6108         Match = false;
6109         break;
6110       }
6111 
6112       ParmVarDecl *param = Method->parameters()[i];
6113       Expr *argExpr = Args[i];
6114       assert(argExpr && "SelectBestMethod(): missing expression");
6115 
6116       // Strip the unbridged-cast placeholder expression off unless it's
6117       // a consumed argument.
6118       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6119           !param->hasAttr<CFConsumedAttr>())
6120         argExpr = stripARCUnbridgedCast(argExpr);
6121 
6122       // If the parameter is __unknown_anytype, move on to the next method.
6123       if (param->getType() == Context.UnknownAnyTy) {
6124         Match = false;
6125         break;
6126       }
6127 
6128       ImplicitConversionSequence ConversionState
6129         = TryCopyInitialization(*this, argExpr, param->getType(),
6130                                 /*SuppressUserConversions*/false,
6131                                 /*InOverloadResolution=*/true,
6132                                 /*AllowObjCWritebackConversion=*/
6133                                 getLangOpts().ObjCAutoRefCount,
6134                                 /*AllowExplicit*/false);
6135       // This function looks for a reasonably-exact match, so we consider
6136       // incompatible pointer conversions to be a failure here.
6137       if (ConversionState.isBad() ||
6138           (ConversionState.isStandard() &&
6139            ConversionState.Standard.Second ==
6140                ICK_Incompatible_Pointer_Conversion)) {
6141         Match = false;
6142         break;
6143       }
6144     }
6145     // Promote additional arguments to variadic methods.
6146     if (Match && Method->isVariadic()) {
6147       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6148         if (Args[i]->isTypeDependent()) {
6149           Match = false;
6150           break;
6151         }
6152         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6153                                                           nullptr);
6154         if (Arg.isInvalid()) {
6155           Match = false;
6156           break;
6157         }
6158       }
6159     } else {
6160       // Check for extra arguments to non-variadic methods.
6161       if (Args.size() != NumNamedArgs)
6162         Match = false;
6163       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6164         // Special case when selectors have no argument. In this case, select
6165         // one with the most general result type of 'id'.
6166         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6167           QualType ReturnT = Methods[b]->getReturnType();
6168           if (ReturnT->isObjCIdType())
6169             return Methods[b];
6170         }
6171       }
6172     }
6173 
6174     if (Match)
6175       return Method;
6176   }
6177   return nullptr;
6178 }
6179 
6180 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6181 // enable_if is order-sensitive. As a result, we need to reverse things
6182 // sometimes. Size of 4 elements is arbitrary.
6183 static SmallVector<EnableIfAttr *, 4>
6184 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6185   SmallVector<EnableIfAttr *, 4> Result;
6186   if (!Function->hasAttrs())
6187     return Result;
6188 
6189   const auto &FuncAttrs = Function->getAttrs();
6190   for (Attr *Attr : FuncAttrs)
6191     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6192       Result.push_back(EnableIf);
6193 
6194   std::reverse(Result.begin(), Result.end());
6195   return Result;
6196 }
6197 
6198 static bool
6199 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6200                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6201                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6202                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6203   if (ThisArg) {
6204     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6205     assert(!isa<CXXConstructorDecl>(Method) &&
6206            "Shouldn't have `this` for ctors!");
6207     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6208     ExprResult R = S.PerformObjectArgumentInitialization(
6209         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6210     if (R.isInvalid())
6211       return false;
6212     ConvertedThis = R.get();
6213   } else {
6214     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6215       (void)MD;
6216       assert((MissingImplicitThis || MD->isStatic() ||
6217               isa<CXXConstructorDecl>(MD)) &&
6218              "Expected `this` for non-ctor instance methods");
6219     }
6220     ConvertedThis = nullptr;
6221   }
6222 
6223   // Ignore any variadic arguments. Converting them is pointless, since the
6224   // user can't refer to them in the function condition.
6225   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6226 
6227   // Convert the arguments.
6228   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6229     ExprResult R;
6230     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6231                                         S.Context, Function->getParamDecl(I)),
6232                                     SourceLocation(), Args[I]);
6233 
6234     if (R.isInvalid())
6235       return false;
6236 
6237     ConvertedArgs.push_back(R.get());
6238   }
6239 
6240   if (Trap.hasErrorOccurred())
6241     return false;
6242 
6243   // Push default arguments if needed.
6244   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6245     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6246       ParmVarDecl *P = Function->getParamDecl(i);
6247       ExprResult R = S.PerformCopyInitialization(
6248           InitializedEntity::InitializeParameter(S.Context,
6249                                                  Function->getParamDecl(i)),
6250           SourceLocation(),
6251           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6252                                            : P->getDefaultArg());
6253       if (R.isInvalid())
6254         return false;
6255       ConvertedArgs.push_back(R.get());
6256     }
6257 
6258     if (Trap.hasErrorOccurred())
6259       return false;
6260   }
6261   return true;
6262 }
6263 
6264 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6265                                   bool MissingImplicitThis) {
6266   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6267       getOrderedEnableIfAttrs(Function);
6268   if (EnableIfAttrs.empty())
6269     return nullptr;
6270 
6271   SFINAETrap Trap(*this);
6272   SmallVector<Expr *, 16> ConvertedArgs;
6273   // FIXME: We should look into making enable_if late-parsed.
6274   Expr *DiscardedThis;
6275   if (!convertArgsForAvailabilityChecks(
6276           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6277           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6278     return EnableIfAttrs[0];
6279 
6280   for (auto *EIA : EnableIfAttrs) {
6281     APValue Result;
6282     // FIXME: This doesn't consider value-dependent cases, because doing so is
6283     // very difficult. Ideally, we should handle them more gracefully.
6284     if (!EIA->getCond()->EvaluateWithSubstitution(
6285             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6286       return EIA;
6287 
6288     if (!Result.isInt() || !Result.getInt().getBoolValue())
6289       return EIA;
6290   }
6291   return nullptr;
6292 }
6293 
6294 template <typename CheckFn>
6295 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6296                                         bool ArgDependent, SourceLocation Loc,
6297                                         CheckFn &&IsSuccessful) {
6298   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6299   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6300     if (ArgDependent == DIA->getArgDependent())
6301       Attrs.push_back(DIA);
6302   }
6303 
6304   // Common case: No diagnose_if attributes, so we can quit early.
6305   if (Attrs.empty())
6306     return false;
6307 
6308   auto WarningBegin = std::stable_partition(
6309       Attrs.begin(), Attrs.end(),
6310       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6311 
6312   // Note that diagnose_if attributes are late-parsed, so they appear in the
6313   // correct order (unlike enable_if attributes).
6314   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6315                                IsSuccessful);
6316   if (ErrAttr != WarningBegin) {
6317     const DiagnoseIfAttr *DIA = *ErrAttr;
6318     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6319     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6320         << DIA->getParent() << DIA->getCond()->getSourceRange();
6321     return true;
6322   }
6323 
6324   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6325     if (IsSuccessful(DIA)) {
6326       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6327       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6328           << DIA->getParent() << DIA->getCond()->getSourceRange();
6329     }
6330 
6331   return false;
6332 }
6333 
6334 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6335                                                const Expr *ThisArg,
6336                                                ArrayRef<const Expr *> Args,
6337                                                SourceLocation Loc) {
6338   return diagnoseDiagnoseIfAttrsWith(
6339       *this, Function, /*ArgDependent=*/true, Loc,
6340       [&](const DiagnoseIfAttr *DIA) {
6341         APValue Result;
6342         // It's sane to use the same Args for any redecl of this function, since
6343         // EvaluateWithSubstitution only cares about the position of each
6344         // argument in the arg list, not the ParmVarDecl* it maps to.
6345         if (!DIA->getCond()->EvaluateWithSubstitution(
6346                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6347           return false;
6348         return Result.isInt() && Result.getInt().getBoolValue();
6349       });
6350 }
6351 
6352 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6353                                                  SourceLocation Loc) {
6354   return diagnoseDiagnoseIfAttrsWith(
6355       *this, ND, /*ArgDependent=*/false, Loc,
6356       [&](const DiagnoseIfAttr *DIA) {
6357         bool Result;
6358         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6359                Result;
6360       });
6361 }
6362 
6363 /// \brief Add all of the function declarations in the given function set to
6364 /// the overload candidate set.
6365 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6366                                  ArrayRef<Expr *> Args,
6367                                  OverloadCandidateSet& CandidateSet,
6368                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6369                                  bool SuppressUserConversions,
6370                                  bool PartialOverloading,
6371                                  bool FirstArgumentIsBase) {
6372   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6373     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6374     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6375       ArrayRef<Expr *> FunctionArgs = Args;
6376       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6377         QualType ObjectType;
6378         Expr::Classification ObjectClassification;
6379         if (Args.size() > 0) {
6380           if (Expr *E = Args[0]) {
6381             // Use the explit base to restrict the lookup:
6382             ObjectType = E->getType();
6383             ObjectClassification = E->Classify(Context);
6384           } // .. else there is an implit base.
6385           FunctionArgs = Args.slice(1);
6386         }
6387         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6388                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6389                            ObjectClassification, FunctionArgs, CandidateSet,
6390                            SuppressUserConversions, PartialOverloading);
6391       } else {
6392         // Slice the first argument (which is the base) when we access
6393         // static method as non-static
6394         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6395                                              !isa<CXXConstructorDecl>(FD)))) {
6396           assert(cast<CXXMethodDecl>(FD)->isStatic());
6397           FunctionArgs = Args.slice(1);
6398         }
6399         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6400                              SuppressUserConversions, PartialOverloading);
6401       }
6402     } else {
6403       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6404       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6405           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6406         QualType ObjectType;
6407         Expr::Classification ObjectClassification;
6408         if (Expr *E = Args[0]) {
6409           // Use the explit base to restrict the lookup:
6410           ObjectType = E->getType();
6411           ObjectClassification = E->Classify(Context);
6412         } // .. else there is an implit base.
6413         AddMethodTemplateCandidate(
6414             FunTmpl, F.getPair(),
6415             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6416             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6417             Args.slice(1), CandidateSet, SuppressUserConversions,
6418             PartialOverloading);
6419       } else {
6420         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6421                                      ExplicitTemplateArgs, Args,
6422                                      CandidateSet, SuppressUserConversions,
6423                                      PartialOverloading);
6424       }
6425     }
6426   }
6427 }
6428 
6429 /// AddMethodCandidate - Adds a named decl (which is some kind of
6430 /// method) as a method candidate to the given overload set.
6431 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6432                               QualType ObjectType,
6433                               Expr::Classification ObjectClassification,
6434                               ArrayRef<Expr *> Args,
6435                               OverloadCandidateSet& CandidateSet,
6436                               bool SuppressUserConversions) {
6437   NamedDecl *Decl = FoundDecl.getDecl();
6438   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6439 
6440   if (isa<UsingShadowDecl>(Decl))
6441     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6442 
6443   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6444     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6445            "Expected a member function template");
6446     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6447                                /*ExplicitArgs*/ nullptr, ObjectType,
6448                                ObjectClassification, Args, CandidateSet,
6449                                SuppressUserConversions);
6450   } else {
6451     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6452                        ObjectType, ObjectClassification, Args, CandidateSet,
6453                        SuppressUserConversions);
6454   }
6455 }
6456 
6457 /// AddMethodCandidate - Adds the given C++ member function to the set
6458 /// of candidate functions, using the given function call arguments
6459 /// and the object argument (@c Object). For example, in a call
6460 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6461 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6462 /// allow user-defined conversions via constructors or conversion
6463 /// operators.
6464 void
6465 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6466                          CXXRecordDecl *ActingContext, QualType ObjectType,
6467                          Expr::Classification ObjectClassification,
6468                          ArrayRef<Expr *> Args,
6469                          OverloadCandidateSet &CandidateSet,
6470                          bool SuppressUserConversions,
6471                          bool PartialOverloading,
6472                          ConversionSequenceList EarlyConversions) {
6473   const FunctionProtoType *Proto
6474     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6475   assert(Proto && "Methods without a prototype cannot be overloaded");
6476   assert(!isa<CXXConstructorDecl>(Method) &&
6477          "Use AddOverloadCandidate for constructors");
6478 
6479   if (!CandidateSet.isNewCandidate(Method))
6480     return;
6481 
6482   // C++11 [class.copy]p23: [DR1402]
6483   //   A defaulted move assignment operator that is defined as deleted is
6484   //   ignored by overload resolution.
6485   if (Method->isDefaulted() && Method->isDeleted() &&
6486       Method->isMoveAssignmentOperator())
6487     return;
6488 
6489   // Overload resolution is always an unevaluated context.
6490   EnterExpressionEvaluationContext Unevaluated(
6491       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6492 
6493   // Add this candidate
6494   OverloadCandidate &Candidate =
6495       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6496   Candidate.FoundDecl = FoundDecl;
6497   Candidate.Function = Method;
6498   Candidate.IsSurrogate = false;
6499   Candidate.IgnoreObjectArgument = false;
6500   Candidate.ExplicitCallArguments = Args.size();
6501 
6502   unsigned NumParams = Proto->getNumParams();
6503 
6504   // (C++ 13.3.2p2): A candidate function having fewer than m
6505   // parameters is viable only if it has an ellipsis in its parameter
6506   // list (8.3.5).
6507   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6508       !Proto->isVariadic()) {
6509     Candidate.Viable = false;
6510     Candidate.FailureKind = ovl_fail_too_many_arguments;
6511     return;
6512   }
6513 
6514   // (C++ 13.3.2p2): A candidate function having more than m parameters
6515   // is viable only if the (m+1)st parameter has a default argument
6516   // (8.3.6). For the purposes of overload resolution, the
6517   // parameter list is truncated on the right, so that there are
6518   // exactly m parameters.
6519   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6520   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6521     // Not enough arguments.
6522     Candidate.Viable = false;
6523     Candidate.FailureKind = ovl_fail_too_few_arguments;
6524     return;
6525   }
6526 
6527   Candidate.Viable = true;
6528 
6529   if (Method->isStatic() || ObjectType.isNull())
6530     // The implicit object argument is ignored.
6531     Candidate.IgnoreObjectArgument = true;
6532   else {
6533     // Determine the implicit conversion sequence for the object
6534     // parameter.
6535     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6536         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6537         Method, ActingContext);
6538     if (Candidate.Conversions[0].isBad()) {
6539       Candidate.Viable = false;
6540       Candidate.FailureKind = ovl_fail_bad_conversion;
6541       return;
6542     }
6543   }
6544 
6545   // (CUDA B.1): Check for invalid calls between targets.
6546   if (getLangOpts().CUDA)
6547     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6548       if (!IsAllowedCUDACall(Caller, Method)) {
6549         Candidate.Viable = false;
6550         Candidate.FailureKind = ovl_fail_bad_target;
6551         return;
6552       }
6553 
6554   // Determine the implicit conversion sequences for each of the
6555   // arguments.
6556   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6557     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6558       // We already formed a conversion sequence for this parameter during
6559       // template argument deduction.
6560     } else if (ArgIdx < NumParams) {
6561       // (C++ 13.3.2p3): for F to be a viable function, there shall
6562       // exist for each argument an implicit conversion sequence
6563       // (13.3.3.1) that converts that argument to the corresponding
6564       // parameter of F.
6565       QualType ParamType = Proto->getParamType(ArgIdx);
6566       Candidate.Conversions[ArgIdx + 1]
6567         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6568                                 SuppressUserConversions,
6569                                 /*InOverloadResolution=*/true,
6570                                 /*AllowObjCWritebackConversion=*/
6571                                   getLangOpts().ObjCAutoRefCount);
6572       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6573         Candidate.Viable = false;
6574         Candidate.FailureKind = ovl_fail_bad_conversion;
6575         return;
6576       }
6577     } else {
6578       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6579       // argument for which there is no corresponding parameter is
6580       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6581       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6582     }
6583   }
6584 
6585   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6586     Candidate.Viable = false;
6587     Candidate.FailureKind = ovl_fail_enable_if;
6588     Candidate.DeductionFailure.Data = FailedAttr;
6589     return;
6590   }
6591 
6592   if (Method->isMultiVersion() &&
6593       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6594     Candidate.Viable = false;
6595     Candidate.FailureKind = ovl_non_default_multiversion_function;
6596   }
6597 }
6598 
6599 /// \brief Add a C++ member function template as a candidate to the candidate
6600 /// set, using template argument deduction to produce an appropriate member
6601 /// function template specialization.
6602 void
6603 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6604                                  DeclAccessPair FoundDecl,
6605                                  CXXRecordDecl *ActingContext,
6606                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6607                                  QualType ObjectType,
6608                                  Expr::Classification ObjectClassification,
6609                                  ArrayRef<Expr *> Args,
6610                                  OverloadCandidateSet& CandidateSet,
6611                                  bool SuppressUserConversions,
6612                                  bool PartialOverloading) {
6613   if (!CandidateSet.isNewCandidate(MethodTmpl))
6614     return;
6615 
6616   // C++ [over.match.funcs]p7:
6617   //   In each case where a candidate is a function template, candidate
6618   //   function template specializations are generated using template argument
6619   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6620   //   candidate functions in the usual way.113) A given name can refer to one
6621   //   or more function templates and also to a set of overloaded non-template
6622   //   functions. In such a case, the candidate functions generated from each
6623   //   function template are combined with the set of non-template candidate
6624   //   functions.
6625   TemplateDeductionInfo Info(CandidateSet.getLocation());
6626   FunctionDecl *Specialization = nullptr;
6627   ConversionSequenceList Conversions;
6628   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6629           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6630           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6631             return CheckNonDependentConversions(
6632                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6633                 SuppressUserConversions, ActingContext, ObjectType,
6634                 ObjectClassification);
6635           })) {
6636     OverloadCandidate &Candidate =
6637         CandidateSet.addCandidate(Conversions.size(), Conversions);
6638     Candidate.FoundDecl = FoundDecl;
6639     Candidate.Function = MethodTmpl->getTemplatedDecl();
6640     Candidate.Viable = false;
6641     Candidate.IsSurrogate = false;
6642     Candidate.IgnoreObjectArgument =
6643         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6644         ObjectType.isNull();
6645     Candidate.ExplicitCallArguments = Args.size();
6646     if (Result == TDK_NonDependentConversionFailure)
6647       Candidate.FailureKind = ovl_fail_bad_conversion;
6648     else {
6649       Candidate.FailureKind = ovl_fail_bad_deduction;
6650       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6651                                                             Info);
6652     }
6653     return;
6654   }
6655 
6656   // Add the function template specialization produced by template argument
6657   // deduction as a candidate.
6658   assert(Specialization && "Missing member function template specialization?");
6659   assert(isa<CXXMethodDecl>(Specialization) &&
6660          "Specialization is not a member function?");
6661   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6662                      ActingContext, ObjectType, ObjectClassification, Args,
6663                      CandidateSet, SuppressUserConversions, PartialOverloading,
6664                      Conversions);
6665 }
6666 
6667 /// \brief Add a C++ function template specialization as a candidate
6668 /// in the candidate set, using template argument deduction to produce
6669 /// an appropriate function template specialization.
6670 void
6671 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6672                                    DeclAccessPair FoundDecl,
6673                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6674                                    ArrayRef<Expr *> Args,
6675                                    OverloadCandidateSet& CandidateSet,
6676                                    bool SuppressUserConversions,
6677                                    bool PartialOverloading) {
6678   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6679     return;
6680 
6681   // C++ [over.match.funcs]p7:
6682   //   In each case where a candidate is a function template, candidate
6683   //   function template specializations are generated using template argument
6684   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6685   //   candidate functions in the usual way.113) A given name can refer to one
6686   //   or more function templates and also to a set of overloaded non-template
6687   //   functions. In such a case, the candidate functions generated from each
6688   //   function template are combined with the set of non-template candidate
6689   //   functions.
6690   TemplateDeductionInfo Info(CandidateSet.getLocation());
6691   FunctionDecl *Specialization = nullptr;
6692   ConversionSequenceList Conversions;
6693   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6694           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6695           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6696             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6697                                                 Args, CandidateSet, Conversions,
6698                                                 SuppressUserConversions);
6699           })) {
6700     OverloadCandidate &Candidate =
6701         CandidateSet.addCandidate(Conversions.size(), Conversions);
6702     Candidate.FoundDecl = FoundDecl;
6703     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6704     Candidate.Viable = false;
6705     Candidate.IsSurrogate = false;
6706     // Ignore the object argument if there is one, since we don't have an object
6707     // type.
6708     Candidate.IgnoreObjectArgument =
6709         isa<CXXMethodDecl>(Candidate.Function) &&
6710         !isa<CXXConstructorDecl>(Candidate.Function);
6711     Candidate.ExplicitCallArguments = Args.size();
6712     if (Result == TDK_NonDependentConversionFailure)
6713       Candidate.FailureKind = ovl_fail_bad_conversion;
6714     else {
6715       Candidate.FailureKind = ovl_fail_bad_deduction;
6716       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6717                                                             Info);
6718     }
6719     return;
6720   }
6721 
6722   // Add the function template specialization produced by template argument
6723   // deduction as a candidate.
6724   assert(Specialization && "Missing function template specialization?");
6725   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6726                        SuppressUserConversions, PartialOverloading,
6727                        /*AllowExplicit*/false, Conversions);
6728 }
6729 
6730 /// Check that implicit conversion sequences can be formed for each argument
6731 /// whose corresponding parameter has a non-dependent type, per DR1391's
6732 /// [temp.deduct.call]p10.
6733 bool Sema::CheckNonDependentConversions(
6734     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6735     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6736     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6737     CXXRecordDecl *ActingContext, QualType ObjectType,
6738     Expr::Classification ObjectClassification) {
6739   // FIXME: The cases in which we allow explicit conversions for constructor
6740   // arguments never consider calling a constructor template. It's not clear
6741   // that is correct.
6742   const bool AllowExplicit = false;
6743 
6744   auto *FD = FunctionTemplate->getTemplatedDecl();
6745   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6746   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6747   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6748 
6749   Conversions =
6750       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6751 
6752   // Overload resolution is always an unevaluated context.
6753   EnterExpressionEvaluationContext Unevaluated(
6754       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6755 
6756   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6757   // require that, but this check should never result in a hard error, and
6758   // overload resolution is permitted to sidestep instantiations.
6759   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6760       !ObjectType.isNull()) {
6761     Conversions[0] = TryObjectArgumentInitialization(
6762         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6763         Method, ActingContext);
6764     if (Conversions[0].isBad())
6765       return true;
6766   }
6767 
6768   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6769        ++I) {
6770     QualType ParamType = ParamTypes[I];
6771     if (!ParamType->isDependentType()) {
6772       Conversions[ThisConversions + I]
6773         = TryCopyInitialization(*this, Args[I], ParamType,
6774                                 SuppressUserConversions,
6775                                 /*InOverloadResolution=*/true,
6776                                 /*AllowObjCWritebackConversion=*/
6777                                   getLangOpts().ObjCAutoRefCount,
6778                                 AllowExplicit);
6779       if (Conversions[ThisConversions + I].isBad())
6780         return true;
6781     }
6782   }
6783 
6784   return false;
6785 }
6786 
6787 /// Determine whether this is an allowable conversion from the result
6788 /// of an explicit conversion operator to the expected type, per C++
6789 /// [over.match.conv]p1 and [over.match.ref]p1.
6790 ///
6791 /// \param ConvType The return type of the conversion function.
6792 ///
6793 /// \param ToType The type we are converting to.
6794 ///
6795 /// \param AllowObjCPointerConversion Allow a conversion from one
6796 /// Objective-C pointer to another.
6797 ///
6798 /// \returns true if the conversion is allowable, false otherwise.
6799 static bool isAllowableExplicitConversion(Sema &S,
6800                                           QualType ConvType, QualType ToType,
6801                                           bool AllowObjCPointerConversion) {
6802   QualType ToNonRefType = ToType.getNonReferenceType();
6803 
6804   // Easy case: the types are the same.
6805   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6806     return true;
6807 
6808   // Allow qualification conversions.
6809   bool ObjCLifetimeConversion;
6810   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6811                                   ObjCLifetimeConversion))
6812     return true;
6813 
6814   // If we're not allowed to consider Objective-C pointer conversions,
6815   // we're done.
6816   if (!AllowObjCPointerConversion)
6817     return false;
6818 
6819   // Is this an Objective-C pointer conversion?
6820   bool IncompatibleObjC = false;
6821   QualType ConvertedType;
6822   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6823                                    IncompatibleObjC);
6824 }
6825 
6826 /// AddConversionCandidate - Add a C++ conversion function as a
6827 /// candidate in the candidate set (C++ [over.match.conv],
6828 /// C++ [over.match.copy]). From is the expression we're converting from,
6829 /// and ToType is the type that we're eventually trying to convert to
6830 /// (which may or may not be the same type as the type that the
6831 /// conversion function produces).
6832 void
6833 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6834                              DeclAccessPair FoundDecl,
6835                              CXXRecordDecl *ActingContext,
6836                              Expr *From, QualType ToType,
6837                              OverloadCandidateSet& CandidateSet,
6838                              bool AllowObjCConversionOnExplicit,
6839                              bool AllowResultConversion) {
6840   assert(!Conversion->getDescribedFunctionTemplate() &&
6841          "Conversion function templates use AddTemplateConversionCandidate");
6842   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6843   if (!CandidateSet.isNewCandidate(Conversion))
6844     return;
6845 
6846   // If the conversion function has an undeduced return type, trigger its
6847   // deduction now.
6848   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6849     if (DeduceReturnType(Conversion, From->getExprLoc()))
6850       return;
6851     ConvType = Conversion->getConversionType().getNonReferenceType();
6852   }
6853 
6854   // If we don't allow any conversion of the result type, ignore conversion
6855   // functions that don't convert to exactly (possibly cv-qualified) T.
6856   if (!AllowResultConversion &&
6857       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6858     return;
6859 
6860   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6861   // operator is only a candidate if its return type is the target type or
6862   // can be converted to the target type with a qualification conversion.
6863   if (Conversion->isExplicit() &&
6864       !isAllowableExplicitConversion(*this, ConvType, ToType,
6865                                      AllowObjCConversionOnExplicit))
6866     return;
6867 
6868   // Overload resolution is always an unevaluated context.
6869   EnterExpressionEvaluationContext Unevaluated(
6870       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6871 
6872   // Add this candidate
6873   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6874   Candidate.FoundDecl = FoundDecl;
6875   Candidate.Function = Conversion;
6876   Candidate.IsSurrogate = false;
6877   Candidate.IgnoreObjectArgument = false;
6878   Candidate.FinalConversion.setAsIdentityConversion();
6879   Candidate.FinalConversion.setFromType(ConvType);
6880   Candidate.FinalConversion.setAllToTypes(ToType);
6881   Candidate.Viable = true;
6882   Candidate.ExplicitCallArguments = 1;
6883 
6884   // C++ [over.match.funcs]p4:
6885   //   For conversion functions, the function is considered to be a member of
6886   //   the class of the implicit implied object argument for the purpose of
6887   //   defining the type of the implicit object parameter.
6888   //
6889   // Determine the implicit conversion sequence for the implicit
6890   // object parameter.
6891   QualType ImplicitParamType = From->getType();
6892   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6893     ImplicitParamType = FromPtrType->getPointeeType();
6894   CXXRecordDecl *ConversionContext
6895     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6896 
6897   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6898       *this, CandidateSet.getLocation(), From->getType(),
6899       From->Classify(Context), Conversion, ConversionContext);
6900 
6901   if (Candidate.Conversions[0].isBad()) {
6902     Candidate.Viable = false;
6903     Candidate.FailureKind = ovl_fail_bad_conversion;
6904     return;
6905   }
6906 
6907   // We won't go through a user-defined type conversion function to convert a
6908   // derived to base as such conversions are given Conversion Rank. They only
6909   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6910   QualType FromCanon
6911     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6912   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6913   if (FromCanon == ToCanon ||
6914       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6915     Candidate.Viable = false;
6916     Candidate.FailureKind = ovl_fail_trivial_conversion;
6917     return;
6918   }
6919 
6920   // To determine what the conversion from the result of calling the
6921   // conversion function to the type we're eventually trying to
6922   // convert to (ToType), we need to synthesize a call to the
6923   // conversion function and attempt copy initialization from it. This
6924   // makes sure that we get the right semantics with respect to
6925   // lvalues/rvalues and the type. Fortunately, we can allocate this
6926   // call on the stack and we don't need its arguments to be
6927   // well-formed.
6928   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6929                             VK_LValue, From->getLocStart());
6930   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6931                                 Context.getPointerType(Conversion->getType()),
6932                                 CK_FunctionToPointerDecay,
6933                                 &ConversionRef, VK_RValue);
6934 
6935   QualType ConversionType = Conversion->getConversionType();
6936   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6937     Candidate.Viable = false;
6938     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6939     return;
6940   }
6941 
6942   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6943 
6944   // Note that it is safe to allocate CallExpr on the stack here because
6945   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6946   // allocator).
6947   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6948   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6949                 From->getLocStart());
6950   ImplicitConversionSequence ICS =
6951     TryCopyInitialization(*this, &Call, ToType,
6952                           /*SuppressUserConversions=*/true,
6953                           /*InOverloadResolution=*/false,
6954                           /*AllowObjCWritebackConversion=*/false);
6955 
6956   switch (ICS.getKind()) {
6957   case ImplicitConversionSequence::StandardConversion:
6958     Candidate.FinalConversion = ICS.Standard;
6959 
6960     // C++ [over.ics.user]p3:
6961     //   If the user-defined conversion is specified by a specialization of a
6962     //   conversion function template, the second standard conversion sequence
6963     //   shall have exact match rank.
6964     if (Conversion->getPrimaryTemplate() &&
6965         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6966       Candidate.Viable = false;
6967       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6968       return;
6969     }
6970 
6971     // C++0x [dcl.init.ref]p5:
6972     //    In the second case, if the reference is an rvalue reference and
6973     //    the second standard conversion sequence of the user-defined
6974     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6975     //    program is ill-formed.
6976     if (ToType->isRValueReferenceType() &&
6977         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6978       Candidate.Viable = false;
6979       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6980       return;
6981     }
6982     break;
6983 
6984   case ImplicitConversionSequence::BadConversion:
6985     Candidate.Viable = false;
6986     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6987     return;
6988 
6989   default:
6990     llvm_unreachable(
6991            "Can only end up with a standard conversion sequence or failure");
6992   }
6993 
6994   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6995     Candidate.Viable = false;
6996     Candidate.FailureKind = ovl_fail_enable_if;
6997     Candidate.DeductionFailure.Data = FailedAttr;
6998     return;
6999   }
7000 
7001   if (Conversion->isMultiVersion() &&
7002       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7003     Candidate.Viable = false;
7004     Candidate.FailureKind = ovl_non_default_multiversion_function;
7005   }
7006 }
7007 
7008 /// \brief Adds a conversion function template specialization
7009 /// candidate to the overload set, using template argument deduction
7010 /// to deduce the template arguments of the conversion function
7011 /// template from the type that we are converting to (C++
7012 /// [temp.deduct.conv]).
7013 void
7014 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7015                                      DeclAccessPair FoundDecl,
7016                                      CXXRecordDecl *ActingDC,
7017                                      Expr *From, QualType ToType,
7018                                      OverloadCandidateSet &CandidateSet,
7019                                      bool AllowObjCConversionOnExplicit,
7020                                      bool AllowResultConversion) {
7021   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7022          "Only conversion function templates permitted here");
7023 
7024   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7025     return;
7026 
7027   TemplateDeductionInfo Info(CandidateSet.getLocation());
7028   CXXConversionDecl *Specialization = nullptr;
7029   if (TemplateDeductionResult Result
7030         = DeduceTemplateArguments(FunctionTemplate, ToType,
7031                                   Specialization, Info)) {
7032     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7033     Candidate.FoundDecl = FoundDecl;
7034     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7035     Candidate.Viable = false;
7036     Candidate.FailureKind = ovl_fail_bad_deduction;
7037     Candidate.IsSurrogate = false;
7038     Candidate.IgnoreObjectArgument = false;
7039     Candidate.ExplicitCallArguments = 1;
7040     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7041                                                           Info);
7042     return;
7043   }
7044 
7045   // Add the conversion function template specialization produced by
7046   // template argument deduction as a candidate.
7047   assert(Specialization && "Missing function template specialization?");
7048   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7049                          CandidateSet, AllowObjCConversionOnExplicit,
7050                          AllowResultConversion);
7051 }
7052 
7053 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7054 /// converts the given @c Object to a function pointer via the
7055 /// conversion function @c Conversion, and then attempts to call it
7056 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7057 /// the type of function that we'll eventually be calling.
7058 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7059                                  DeclAccessPair FoundDecl,
7060                                  CXXRecordDecl *ActingContext,
7061                                  const FunctionProtoType *Proto,
7062                                  Expr *Object,
7063                                  ArrayRef<Expr *> Args,
7064                                  OverloadCandidateSet& CandidateSet) {
7065   if (!CandidateSet.isNewCandidate(Conversion))
7066     return;
7067 
7068   // Overload resolution is always an unevaluated context.
7069   EnterExpressionEvaluationContext Unevaluated(
7070       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7071 
7072   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7073   Candidate.FoundDecl = FoundDecl;
7074   Candidate.Function = nullptr;
7075   Candidate.Surrogate = Conversion;
7076   Candidate.Viable = true;
7077   Candidate.IsSurrogate = true;
7078   Candidate.IgnoreObjectArgument = false;
7079   Candidate.ExplicitCallArguments = Args.size();
7080 
7081   // Determine the implicit conversion sequence for the implicit
7082   // object parameter.
7083   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7084       *this, CandidateSet.getLocation(), Object->getType(),
7085       Object->Classify(Context), Conversion, ActingContext);
7086   if (ObjectInit.isBad()) {
7087     Candidate.Viable = false;
7088     Candidate.FailureKind = ovl_fail_bad_conversion;
7089     Candidate.Conversions[0] = ObjectInit;
7090     return;
7091   }
7092 
7093   // The first conversion is actually a user-defined conversion whose
7094   // first conversion is ObjectInit's standard conversion (which is
7095   // effectively a reference binding). Record it as such.
7096   Candidate.Conversions[0].setUserDefined();
7097   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7098   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7099   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7100   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7101   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7102   Candidate.Conversions[0].UserDefined.After
7103     = Candidate.Conversions[0].UserDefined.Before;
7104   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7105 
7106   // Find the
7107   unsigned NumParams = Proto->getNumParams();
7108 
7109   // (C++ 13.3.2p2): A candidate function having fewer than m
7110   // parameters is viable only if it has an ellipsis in its parameter
7111   // list (8.3.5).
7112   if (Args.size() > NumParams && !Proto->isVariadic()) {
7113     Candidate.Viable = false;
7114     Candidate.FailureKind = ovl_fail_too_many_arguments;
7115     return;
7116   }
7117 
7118   // Function types don't have any default arguments, so just check if
7119   // we have enough arguments.
7120   if (Args.size() < NumParams) {
7121     // Not enough arguments.
7122     Candidate.Viable = false;
7123     Candidate.FailureKind = ovl_fail_too_few_arguments;
7124     return;
7125   }
7126 
7127   // Determine the implicit conversion sequences for each of the
7128   // arguments.
7129   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7130     if (ArgIdx < NumParams) {
7131       // (C++ 13.3.2p3): for F to be a viable function, there shall
7132       // exist for each argument an implicit conversion sequence
7133       // (13.3.3.1) that converts that argument to the corresponding
7134       // parameter of F.
7135       QualType ParamType = Proto->getParamType(ArgIdx);
7136       Candidate.Conversions[ArgIdx + 1]
7137         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7138                                 /*SuppressUserConversions=*/false,
7139                                 /*InOverloadResolution=*/false,
7140                                 /*AllowObjCWritebackConversion=*/
7141                                   getLangOpts().ObjCAutoRefCount);
7142       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7143         Candidate.Viable = false;
7144         Candidate.FailureKind = ovl_fail_bad_conversion;
7145         return;
7146       }
7147     } else {
7148       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7149       // argument for which there is no corresponding parameter is
7150       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7151       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7152     }
7153   }
7154 
7155   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7156     Candidate.Viable = false;
7157     Candidate.FailureKind = ovl_fail_enable_if;
7158     Candidate.DeductionFailure.Data = FailedAttr;
7159     return;
7160   }
7161 }
7162 
7163 /// \brief Add overload candidates for overloaded operators that are
7164 /// member functions.
7165 ///
7166 /// Add the overloaded operator candidates that are member functions
7167 /// for the operator Op that was used in an operator expression such
7168 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7169 /// CandidateSet will store the added overload candidates. (C++
7170 /// [over.match.oper]).
7171 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7172                                        SourceLocation OpLoc,
7173                                        ArrayRef<Expr *> Args,
7174                                        OverloadCandidateSet& CandidateSet,
7175                                        SourceRange OpRange) {
7176   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7177 
7178   // C++ [over.match.oper]p3:
7179   //   For a unary operator @ with an operand of a type whose
7180   //   cv-unqualified version is T1, and for a binary operator @ with
7181   //   a left operand of a type whose cv-unqualified version is T1 and
7182   //   a right operand of a type whose cv-unqualified version is T2,
7183   //   three sets of candidate functions, designated member
7184   //   candidates, non-member candidates and built-in candidates, are
7185   //   constructed as follows:
7186   QualType T1 = Args[0]->getType();
7187 
7188   //     -- If T1 is a complete class type or a class currently being
7189   //        defined, the set of member candidates is the result of the
7190   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7191   //        the set of member candidates is empty.
7192   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7193     // Complete the type if it can be completed.
7194     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7195       return;
7196     // If the type is neither complete nor being defined, bail out now.
7197     if (!T1Rec->getDecl()->getDefinition())
7198       return;
7199 
7200     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7201     LookupQualifiedName(Operators, T1Rec->getDecl());
7202     Operators.suppressDiagnostics();
7203 
7204     for (LookupResult::iterator Oper = Operators.begin(),
7205                              OperEnd = Operators.end();
7206          Oper != OperEnd;
7207          ++Oper)
7208       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7209                          Args[0]->Classify(Context), Args.slice(1),
7210                          CandidateSet, /*SuppressUserConversions=*/false);
7211   }
7212 }
7213 
7214 /// AddBuiltinCandidate - Add a candidate for a built-in
7215 /// operator. ResultTy and ParamTys are the result and parameter types
7216 /// of the built-in candidate, respectively. Args and NumArgs are the
7217 /// arguments being passed to the candidate. IsAssignmentOperator
7218 /// should be true when this built-in candidate is an assignment
7219 /// operator. NumContextualBoolArguments is the number of arguments
7220 /// (at the beginning of the argument list) that will be contextually
7221 /// converted to bool.
7222 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7223                                OverloadCandidateSet& CandidateSet,
7224                                bool IsAssignmentOperator,
7225                                unsigned NumContextualBoolArguments) {
7226   // Overload resolution is always an unevaluated context.
7227   EnterExpressionEvaluationContext Unevaluated(
7228       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7229 
7230   // Add this candidate
7231   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7232   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7233   Candidate.Function = nullptr;
7234   Candidate.IsSurrogate = false;
7235   Candidate.IgnoreObjectArgument = false;
7236   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7237 
7238   // Determine the implicit conversion sequences for each of the
7239   // arguments.
7240   Candidate.Viable = true;
7241   Candidate.ExplicitCallArguments = Args.size();
7242   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7243     // C++ [over.match.oper]p4:
7244     //   For the built-in assignment operators, conversions of the
7245     //   left operand are restricted as follows:
7246     //     -- no temporaries are introduced to hold the left operand, and
7247     //     -- no user-defined conversions are applied to the left
7248     //        operand to achieve a type match with the left-most
7249     //        parameter of a built-in candidate.
7250     //
7251     // We block these conversions by turning off user-defined
7252     // conversions, since that is the only way that initialization of
7253     // a reference to a non-class type can occur from something that
7254     // is not of the same type.
7255     if (ArgIdx < NumContextualBoolArguments) {
7256       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7257              "Contextual conversion to bool requires bool type");
7258       Candidate.Conversions[ArgIdx]
7259         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7260     } else {
7261       Candidate.Conversions[ArgIdx]
7262         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7263                                 ArgIdx == 0 && IsAssignmentOperator,
7264                                 /*InOverloadResolution=*/false,
7265                                 /*AllowObjCWritebackConversion=*/
7266                                   getLangOpts().ObjCAutoRefCount);
7267     }
7268     if (Candidate.Conversions[ArgIdx].isBad()) {
7269       Candidate.Viable = false;
7270       Candidate.FailureKind = ovl_fail_bad_conversion;
7271       break;
7272     }
7273   }
7274 }
7275 
7276 namespace {
7277 
7278 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7279 /// candidate operator functions for built-in operators (C++
7280 /// [over.built]). The types are separated into pointer types and
7281 /// enumeration types.
7282 class BuiltinCandidateTypeSet  {
7283   /// TypeSet - A set of types.
7284   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7285                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7286 
7287   /// PointerTypes - The set of pointer types that will be used in the
7288   /// built-in candidates.
7289   TypeSet PointerTypes;
7290 
7291   /// MemberPointerTypes - The set of member pointer types that will be
7292   /// used in the built-in candidates.
7293   TypeSet MemberPointerTypes;
7294 
7295   /// EnumerationTypes - The set of enumeration types that will be
7296   /// used in the built-in candidates.
7297   TypeSet EnumerationTypes;
7298 
7299   /// \brief The set of vector types that will be used in the built-in
7300   /// candidates.
7301   TypeSet VectorTypes;
7302 
7303   /// \brief A flag indicating non-record types are viable candidates
7304   bool HasNonRecordTypes;
7305 
7306   /// \brief A flag indicating whether either arithmetic or enumeration types
7307   /// were present in the candidate set.
7308   bool HasArithmeticOrEnumeralTypes;
7309 
7310   /// \brief A flag indicating whether the nullptr type was present in the
7311   /// candidate set.
7312   bool HasNullPtrType;
7313 
7314   /// Sema - The semantic analysis instance where we are building the
7315   /// candidate type set.
7316   Sema &SemaRef;
7317 
7318   /// Context - The AST context in which we will build the type sets.
7319   ASTContext &Context;
7320 
7321   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7322                                                const Qualifiers &VisibleQuals);
7323   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7324 
7325 public:
7326   /// iterator - Iterates through the types that are part of the set.
7327   typedef TypeSet::iterator iterator;
7328 
7329   BuiltinCandidateTypeSet(Sema &SemaRef)
7330     : HasNonRecordTypes(false),
7331       HasArithmeticOrEnumeralTypes(false),
7332       HasNullPtrType(false),
7333       SemaRef(SemaRef),
7334       Context(SemaRef.Context) { }
7335 
7336   void AddTypesConvertedFrom(QualType Ty,
7337                              SourceLocation Loc,
7338                              bool AllowUserConversions,
7339                              bool AllowExplicitConversions,
7340                              const Qualifiers &VisibleTypeConversionsQuals);
7341 
7342   /// pointer_begin - First pointer type found;
7343   iterator pointer_begin() { return PointerTypes.begin(); }
7344 
7345   /// pointer_end - Past the last pointer type found;
7346   iterator pointer_end() { return PointerTypes.end(); }
7347 
7348   /// member_pointer_begin - First member pointer type found;
7349   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7350 
7351   /// member_pointer_end - Past the last member pointer type found;
7352   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7353 
7354   /// enumeration_begin - First enumeration type found;
7355   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7356 
7357   /// enumeration_end - Past the last enumeration type found;
7358   iterator enumeration_end() { return EnumerationTypes.end(); }
7359 
7360   iterator vector_begin() { return VectorTypes.begin(); }
7361   iterator vector_end() { return VectorTypes.end(); }
7362 
7363   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7364   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7365   bool hasNullPtrType() const { return HasNullPtrType; }
7366 };
7367 
7368 } // end anonymous namespace
7369 
7370 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7371 /// the set of pointer types along with any more-qualified variants of
7372 /// that type. For example, if @p Ty is "int const *", this routine
7373 /// will add "int const *", "int const volatile *", "int const
7374 /// restrict *", and "int const volatile restrict *" to the set of
7375 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7376 /// false otherwise.
7377 ///
7378 /// FIXME: what to do about extended qualifiers?
7379 bool
7380 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7381                                              const Qualifiers &VisibleQuals) {
7382 
7383   // Insert this type.
7384   if (!PointerTypes.insert(Ty))
7385     return false;
7386 
7387   QualType PointeeTy;
7388   const PointerType *PointerTy = Ty->getAs<PointerType>();
7389   bool buildObjCPtr = false;
7390   if (!PointerTy) {
7391     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7392     PointeeTy = PTy->getPointeeType();
7393     buildObjCPtr = true;
7394   } else {
7395     PointeeTy = PointerTy->getPointeeType();
7396   }
7397 
7398   // Don't add qualified variants of arrays. For one, they're not allowed
7399   // (the qualifier would sink to the element type), and for another, the
7400   // only overload situation where it matters is subscript or pointer +- int,
7401   // and those shouldn't have qualifier variants anyway.
7402   if (PointeeTy->isArrayType())
7403     return true;
7404 
7405   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7406   bool hasVolatile = VisibleQuals.hasVolatile();
7407   bool hasRestrict = VisibleQuals.hasRestrict();
7408 
7409   // Iterate through all strict supersets of BaseCVR.
7410   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7411     if ((CVR | BaseCVR) != CVR) continue;
7412     // Skip over volatile if no volatile found anywhere in the types.
7413     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7414 
7415     // Skip over restrict if no restrict found anywhere in the types, or if
7416     // the type cannot be restrict-qualified.
7417     if ((CVR & Qualifiers::Restrict) &&
7418         (!hasRestrict ||
7419          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7420       continue;
7421 
7422     // Build qualified pointee type.
7423     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7424 
7425     // Build qualified pointer type.
7426     QualType QPointerTy;
7427     if (!buildObjCPtr)
7428       QPointerTy = Context.getPointerType(QPointeeTy);
7429     else
7430       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7431 
7432     // Insert qualified pointer type.
7433     PointerTypes.insert(QPointerTy);
7434   }
7435 
7436   return true;
7437 }
7438 
7439 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7440 /// to the set of pointer types along with any more-qualified variants of
7441 /// that type. For example, if @p Ty is "int const *", this routine
7442 /// will add "int const *", "int const volatile *", "int const
7443 /// restrict *", and "int const volatile restrict *" to the set of
7444 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7445 /// false otherwise.
7446 ///
7447 /// FIXME: what to do about extended qualifiers?
7448 bool
7449 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7450     QualType Ty) {
7451   // Insert this type.
7452   if (!MemberPointerTypes.insert(Ty))
7453     return false;
7454 
7455   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7456   assert(PointerTy && "type was not a member pointer type!");
7457 
7458   QualType PointeeTy = PointerTy->getPointeeType();
7459   // Don't add qualified variants of arrays. For one, they're not allowed
7460   // (the qualifier would sink to the element type), and for another, the
7461   // only overload situation where it matters is subscript or pointer +- int,
7462   // and those shouldn't have qualifier variants anyway.
7463   if (PointeeTy->isArrayType())
7464     return true;
7465   const Type *ClassTy = PointerTy->getClass();
7466 
7467   // Iterate through all strict supersets of the pointee type's CVR
7468   // qualifiers.
7469   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7470   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7471     if ((CVR | BaseCVR) != CVR) continue;
7472 
7473     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7474     MemberPointerTypes.insert(
7475       Context.getMemberPointerType(QPointeeTy, ClassTy));
7476   }
7477 
7478   return true;
7479 }
7480 
7481 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7482 /// Ty can be implicit converted to the given set of @p Types. We're
7483 /// primarily interested in pointer types and enumeration types. We also
7484 /// take member pointer types, for the conditional operator.
7485 /// AllowUserConversions is true if we should look at the conversion
7486 /// functions of a class type, and AllowExplicitConversions if we
7487 /// should also include the explicit conversion functions of a class
7488 /// type.
7489 void
7490 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7491                                                SourceLocation Loc,
7492                                                bool AllowUserConversions,
7493                                                bool AllowExplicitConversions,
7494                                                const Qualifiers &VisibleQuals) {
7495   // Only deal with canonical types.
7496   Ty = Context.getCanonicalType(Ty);
7497 
7498   // Look through reference types; they aren't part of the type of an
7499   // expression for the purposes of conversions.
7500   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7501     Ty = RefTy->getPointeeType();
7502 
7503   // If we're dealing with an array type, decay to the pointer.
7504   if (Ty->isArrayType())
7505     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7506 
7507   // Otherwise, we don't care about qualifiers on the type.
7508   Ty = Ty.getLocalUnqualifiedType();
7509 
7510   // Flag if we ever add a non-record type.
7511   const RecordType *TyRec = Ty->getAs<RecordType>();
7512   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7513 
7514   // Flag if we encounter an arithmetic type.
7515   HasArithmeticOrEnumeralTypes =
7516     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7517 
7518   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7519     PointerTypes.insert(Ty);
7520   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7521     // Insert our type, and its more-qualified variants, into the set
7522     // of types.
7523     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7524       return;
7525   } else if (Ty->isMemberPointerType()) {
7526     // Member pointers are far easier, since the pointee can't be converted.
7527     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7528       return;
7529   } else if (Ty->isEnumeralType()) {
7530     HasArithmeticOrEnumeralTypes = true;
7531     EnumerationTypes.insert(Ty);
7532   } else if (Ty->isVectorType()) {
7533     // We treat vector types as arithmetic types in many contexts as an
7534     // extension.
7535     HasArithmeticOrEnumeralTypes = true;
7536     VectorTypes.insert(Ty);
7537   } else if (Ty->isNullPtrType()) {
7538     HasNullPtrType = true;
7539   } else if (AllowUserConversions && TyRec) {
7540     // No conversion functions in incomplete types.
7541     if (!SemaRef.isCompleteType(Loc, Ty))
7542       return;
7543 
7544     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7545     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7546       if (isa<UsingShadowDecl>(D))
7547         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7548 
7549       // Skip conversion function templates; they don't tell us anything
7550       // about which builtin types we can convert to.
7551       if (isa<FunctionTemplateDecl>(D))
7552         continue;
7553 
7554       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7555       if (AllowExplicitConversions || !Conv->isExplicit()) {
7556         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7557                               VisibleQuals);
7558       }
7559     }
7560   }
7561 }
7562 
7563 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7564 /// the volatile- and non-volatile-qualified assignment operators for the
7565 /// given type to the candidate set.
7566 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7567                                                    QualType T,
7568                                                    ArrayRef<Expr *> Args,
7569                                     OverloadCandidateSet &CandidateSet) {
7570   QualType ParamTypes[2];
7571 
7572   // T& operator=(T&, T)
7573   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7574   ParamTypes[1] = T;
7575   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7576                         /*IsAssignmentOperator=*/true);
7577 
7578   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7579     // volatile T& operator=(volatile T&, T)
7580     ParamTypes[0]
7581       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7582     ParamTypes[1] = T;
7583     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7584                           /*IsAssignmentOperator=*/true);
7585   }
7586 }
7587 
7588 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7589 /// if any, found in visible type conversion functions found in ArgExpr's type.
7590 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7591     Qualifiers VRQuals;
7592     const RecordType *TyRec;
7593     if (const MemberPointerType *RHSMPType =
7594         ArgExpr->getType()->getAs<MemberPointerType>())
7595       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7596     else
7597       TyRec = ArgExpr->getType()->getAs<RecordType>();
7598     if (!TyRec) {
7599       // Just to be safe, assume the worst case.
7600       VRQuals.addVolatile();
7601       VRQuals.addRestrict();
7602       return VRQuals;
7603     }
7604 
7605     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7606     if (!ClassDecl->hasDefinition())
7607       return VRQuals;
7608 
7609     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7610       if (isa<UsingShadowDecl>(D))
7611         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7612       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7613         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7614         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7615           CanTy = ResTypeRef->getPointeeType();
7616         // Need to go down the pointer/mempointer chain and add qualifiers
7617         // as see them.
7618         bool done = false;
7619         while (!done) {
7620           if (CanTy.isRestrictQualified())
7621             VRQuals.addRestrict();
7622           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7623             CanTy = ResTypePtr->getPointeeType();
7624           else if (const MemberPointerType *ResTypeMPtr =
7625                 CanTy->getAs<MemberPointerType>())
7626             CanTy = ResTypeMPtr->getPointeeType();
7627           else
7628             done = true;
7629           if (CanTy.isVolatileQualified())
7630             VRQuals.addVolatile();
7631           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7632             return VRQuals;
7633         }
7634       }
7635     }
7636     return VRQuals;
7637 }
7638 
7639 namespace {
7640 
7641 /// \brief Helper class to manage the addition of builtin operator overload
7642 /// candidates. It provides shared state and utility methods used throughout
7643 /// the process, as well as a helper method to add each group of builtin
7644 /// operator overloads from the standard to a candidate set.
7645 class BuiltinOperatorOverloadBuilder {
7646   // Common instance state available to all overload candidate addition methods.
7647   Sema &S;
7648   ArrayRef<Expr *> Args;
7649   Qualifiers VisibleTypeConversionsQuals;
7650   bool HasArithmeticOrEnumeralCandidateType;
7651   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7652   OverloadCandidateSet &CandidateSet;
7653 
7654   static constexpr int ArithmeticTypesCap = 24;
7655   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7656 
7657   // Define some indices used to iterate over the arithemetic types in
7658   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7659   // types are that preserved by promotion (C++ [over.built]p2).
7660   unsigned FirstIntegralType,
7661            LastIntegralType;
7662   unsigned FirstPromotedIntegralType,
7663            LastPromotedIntegralType;
7664   unsigned FirstPromotedArithmeticType,
7665            LastPromotedArithmeticType;
7666   unsigned NumArithmeticTypes;
7667 
7668   void InitArithmeticTypes() {
7669     // Start of promoted types.
7670     FirstPromotedArithmeticType = 0;
7671     ArithmeticTypes.push_back(S.Context.FloatTy);
7672     ArithmeticTypes.push_back(S.Context.DoubleTy);
7673     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7674     if (S.Context.getTargetInfo().hasFloat128Type())
7675       ArithmeticTypes.push_back(S.Context.Float128Ty);
7676 
7677     // Start of integral types.
7678     FirstIntegralType = ArithmeticTypes.size();
7679     FirstPromotedIntegralType = ArithmeticTypes.size();
7680     ArithmeticTypes.push_back(S.Context.IntTy);
7681     ArithmeticTypes.push_back(S.Context.LongTy);
7682     ArithmeticTypes.push_back(S.Context.LongLongTy);
7683     if (S.Context.getTargetInfo().hasInt128Type())
7684       ArithmeticTypes.push_back(S.Context.Int128Ty);
7685     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7686     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7687     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7688     if (S.Context.getTargetInfo().hasInt128Type())
7689       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7690     LastPromotedIntegralType = ArithmeticTypes.size();
7691     LastPromotedArithmeticType = ArithmeticTypes.size();
7692     // End of promoted types.
7693 
7694     ArithmeticTypes.push_back(S.Context.BoolTy);
7695     ArithmeticTypes.push_back(S.Context.CharTy);
7696     ArithmeticTypes.push_back(S.Context.WCharTy);
7697     ArithmeticTypes.push_back(S.Context.Char16Ty);
7698     ArithmeticTypes.push_back(S.Context.Char32Ty);
7699     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7700     ArithmeticTypes.push_back(S.Context.ShortTy);
7701     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7702     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7703     LastIntegralType = ArithmeticTypes.size();
7704     NumArithmeticTypes = ArithmeticTypes.size();
7705     // End of integral types.
7706     // FIXME: What about complex? What about half?
7707 
7708     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7709            "Enough inline storage for all arithmetic types.");
7710   }
7711 
7712   /// \brief Helper method to factor out the common pattern of adding overloads
7713   /// for '++' and '--' builtin operators.
7714   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7715                                            bool HasVolatile,
7716                                            bool HasRestrict) {
7717     QualType ParamTypes[2] = {
7718       S.Context.getLValueReferenceType(CandidateTy),
7719       S.Context.IntTy
7720     };
7721 
7722     // Non-volatile version.
7723     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7724 
7725     // Use a heuristic to reduce number of builtin candidates in the set:
7726     // add volatile version only if there are conversions to a volatile type.
7727     if (HasVolatile) {
7728       ParamTypes[0] =
7729         S.Context.getLValueReferenceType(
7730           S.Context.getVolatileType(CandidateTy));
7731       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7732     }
7733 
7734     // Add restrict version only if there are conversions to a restrict type
7735     // and our candidate type is a non-restrict-qualified pointer.
7736     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7737         !CandidateTy.isRestrictQualified()) {
7738       ParamTypes[0]
7739         = S.Context.getLValueReferenceType(
7740             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7741       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7742 
7743       if (HasVolatile) {
7744         ParamTypes[0]
7745           = S.Context.getLValueReferenceType(
7746               S.Context.getCVRQualifiedType(CandidateTy,
7747                                             (Qualifiers::Volatile |
7748                                              Qualifiers::Restrict)));
7749         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7750       }
7751     }
7752 
7753   }
7754 
7755 public:
7756   BuiltinOperatorOverloadBuilder(
7757     Sema &S, ArrayRef<Expr *> Args,
7758     Qualifiers VisibleTypeConversionsQuals,
7759     bool HasArithmeticOrEnumeralCandidateType,
7760     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7761     OverloadCandidateSet &CandidateSet)
7762     : S(S), Args(Args),
7763       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7764       HasArithmeticOrEnumeralCandidateType(
7765         HasArithmeticOrEnumeralCandidateType),
7766       CandidateTypes(CandidateTypes),
7767       CandidateSet(CandidateSet) {
7768 
7769     InitArithmeticTypes();
7770   }
7771 
7772   // C++ [over.built]p3:
7773   //
7774   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7775   //   is either volatile or empty, there exist candidate operator
7776   //   functions of the form
7777   //
7778   //       VQ T&      operator++(VQ T&);
7779   //       T          operator++(VQ T&, int);
7780   //
7781   // C++ [over.built]p4:
7782   //
7783   //   For every pair (T, VQ), where T is an arithmetic type other
7784   //   than bool, and VQ is either volatile or empty, there exist
7785   //   candidate operator functions of the form
7786   //
7787   //       VQ T&      operator--(VQ T&);
7788   //       T          operator--(VQ T&, int);
7789   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7790     if (!HasArithmeticOrEnumeralCandidateType)
7791       return;
7792 
7793     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7794          Arith < NumArithmeticTypes; ++Arith) {
7795       addPlusPlusMinusMinusStyleOverloads(
7796         ArithmeticTypes[Arith],
7797         VisibleTypeConversionsQuals.hasVolatile(),
7798         VisibleTypeConversionsQuals.hasRestrict());
7799     }
7800   }
7801 
7802   // C++ [over.built]p5:
7803   //
7804   //   For every pair (T, VQ), where T is a cv-qualified or
7805   //   cv-unqualified object type, and VQ is either volatile or
7806   //   empty, there exist candidate operator functions of the form
7807   //
7808   //       T*VQ&      operator++(T*VQ&);
7809   //       T*VQ&      operator--(T*VQ&);
7810   //       T*         operator++(T*VQ&, int);
7811   //       T*         operator--(T*VQ&, int);
7812   void addPlusPlusMinusMinusPointerOverloads() {
7813     for (BuiltinCandidateTypeSet::iterator
7814               Ptr = CandidateTypes[0].pointer_begin(),
7815            PtrEnd = CandidateTypes[0].pointer_end();
7816          Ptr != PtrEnd; ++Ptr) {
7817       // Skip pointer types that aren't pointers to object types.
7818       if (!(*Ptr)->getPointeeType()->isObjectType())
7819         continue;
7820 
7821       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7822         (!(*Ptr).isVolatileQualified() &&
7823          VisibleTypeConversionsQuals.hasVolatile()),
7824         (!(*Ptr).isRestrictQualified() &&
7825          VisibleTypeConversionsQuals.hasRestrict()));
7826     }
7827   }
7828 
7829   // C++ [over.built]p6:
7830   //   For every cv-qualified or cv-unqualified object type T, there
7831   //   exist candidate operator functions of the form
7832   //
7833   //       T&         operator*(T*);
7834   //
7835   // C++ [over.built]p7:
7836   //   For every function type T that does not have cv-qualifiers or a
7837   //   ref-qualifier, there exist candidate operator functions of the form
7838   //       T&         operator*(T*);
7839   void addUnaryStarPointerOverloads() {
7840     for (BuiltinCandidateTypeSet::iterator
7841               Ptr = CandidateTypes[0].pointer_begin(),
7842            PtrEnd = CandidateTypes[0].pointer_end();
7843          Ptr != PtrEnd; ++Ptr) {
7844       QualType ParamTy = *Ptr;
7845       QualType PointeeTy = ParamTy->getPointeeType();
7846       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7847         continue;
7848 
7849       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7850         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7851           continue;
7852 
7853       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7854     }
7855   }
7856 
7857   // C++ [over.built]p9:
7858   //  For every promoted arithmetic type T, there exist candidate
7859   //  operator functions of the form
7860   //
7861   //       T         operator+(T);
7862   //       T         operator-(T);
7863   void addUnaryPlusOrMinusArithmeticOverloads() {
7864     if (!HasArithmeticOrEnumeralCandidateType)
7865       return;
7866 
7867     for (unsigned Arith = FirstPromotedArithmeticType;
7868          Arith < LastPromotedArithmeticType; ++Arith) {
7869       QualType ArithTy = ArithmeticTypes[Arith];
7870       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7871     }
7872 
7873     // Extension: We also add these operators for vector types.
7874     for (BuiltinCandidateTypeSet::iterator
7875               Vec = CandidateTypes[0].vector_begin(),
7876            VecEnd = CandidateTypes[0].vector_end();
7877          Vec != VecEnd; ++Vec) {
7878       QualType VecTy = *Vec;
7879       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7880     }
7881   }
7882 
7883   // C++ [over.built]p8:
7884   //   For every type T, there exist candidate operator functions of
7885   //   the form
7886   //
7887   //       T*         operator+(T*);
7888   void addUnaryPlusPointerOverloads() {
7889     for (BuiltinCandidateTypeSet::iterator
7890               Ptr = CandidateTypes[0].pointer_begin(),
7891            PtrEnd = CandidateTypes[0].pointer_end();
7892          Ptr != PtrEnd; ++Ptr) {
7893       QualType ParamTy = *Ptr;
7894       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7895     }
7896   }
7897 
7898   // C++ [over.built]p10:
7899   //   For every promoted integral type T, there exist candidate
7900   //   operator functions of the form
7901   //
7902   //        T         operator~(T);
7903   void addUnaryTildePromotedIntegralOverloads() {
7904     if (!HasArithmeticOrEnumeralCandidateType)
7905       return;
7906 
7907     for (unsigned Int = FirstPromotedIntegralType;
7908          Int < LastPromotedIntegralType; ++Int) {
7909       QualType IntTy = ArithmeticTypes[Int];
7910       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7911     }
7912 
7913     // Extension: We also add this operator for vector types.
7914     for (BuiltinCandidateTypeSet::iterator
7915               Vec = CandidateTypes[0].vector_begin(),
7916            VecEnd = CandidateTypes[0].vector_end();
7917          Vec != VecEnd; ++Vec) {
7918       QualType VecTy = *Vec;
7919       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7920     }
7921   }
7922 
7923   // C++ [over.match.oper]p16:
7924   //   For every pointer to member type T or type std::nullptr_t, there
7925   //   exist candidate operator functions of the form
7926   //
7927   //        bool operator==(T,T);
7928   //        bool operator!=(T,T);
7929   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7930     /// Set of (canonical) types that we've already handled.
7931     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7932 
7933     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7934       for (BuiltinCandidateTypeSet::iterator
7935                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7936              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7937            MemPtr != MemPtrEnd;
7938            ++MemPtr) {
7939         // Don't add the same builtin candidate twice.
7940         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7941           continue;
7942 
7943         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7944         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7945       }
7946 
7947       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7948         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7949         if (AddedTypes.insert(NullPtrTy).second) {
7950           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7951           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7952         }
7953       }
7954     }
7955   }
7956 
7957   // C++ [over.built]p15:
7958   //
7959   //   For every T, where T is an enumeration type or a pointer type,
7960   //   there exist candidate operator functions of the form
7961   //
7962   //        bool       operator<(T, T);
7963   //        bool       operator>(T, T);
7964   //        bool       operator<=(T, T);
7965   //        bool       operator>=(T, T);
7966   //        bool       operator==(T, T);
7967   //        bool       operator!=(T, T);
7968   void addRelationalPointerOrEnumeralOverloads() {
7969     // C++ [over.match.oper]p3:
7970     //   [...]the built-in candidates include all of the candidate operator
7971     //   functions defined in 13.6 that, compared to the given operator, [...]
7972     //   do not have the same parameter-type-list as any non-template non-member
7973     //   candidate.
7974     //
7975     // Note that in practice, this only affects enumeration types because there
7976     // aren't any built-in candidates of record type, and a user-defined operator
7977     // must have an operand of record or enumeration type. Also, the only other
7978     // overloaded operator with enumeration arguments, operator=,
7979     // cannot be overloaded for enumeration types, so this is the only place
7980     // where we must suppress candidates like this.
7981     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7982       UserDefinedBinaryOperators;
7983 
7984     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7985       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7986           CandidateTypes[ArgIdx].enumeration_end()) {
7987         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7988                                          CEnd = CandidateSet.end();
7989              C != CEnd; ++C) {
7990           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7991             continue;
7992 
7993           if (C->Function->isFunctionTemplateSpecialization())
7994             continue;
7995 
7996           QualType FirstParamType =
7997             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7998           QualType SecondParamType =
7999             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8000 
8001           // Skip if either parameter isn't of enumeral type.
8002           if (!FirstParamType->isEnumeralType() ||
8003               !SecondParamType->isEnumeralType())
8004             continue;
8005 
8006           // Add this operator to the set of known user-defined operators.
8007           UserDefinedBinaryOperators.insert(
8008             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8009                            S.Context.getCanonicalType(SecondParamType)));
8010         }
8011       }
8012     }
8013 
8014     /// Set of (canonical) types that we've already handled.
8015     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8016 
8017     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8018       for (BuiltinCandidateTypeSet::iterator
8019                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8020              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8021            Ptr != PtrEnd; ++Ptr) {
8022         // Don't add the same builtin candidate twice.
8023         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8024           continue;
8025 
8026         QualType ParamTypes[2] = { *Ptr, *Ptr };
8027         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8028       }
8029       for (BuiltinCandidateTypeSet::iterator
8030                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8031              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8032            Enum != EnumEnd; ++Enum) {
8033         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8034 
8035         // Don't add the same builtin candidate twice, or if a user defined
8036         // candidate exists.
8037         if (!AddedTypes.insert(CanonType).second ||
8038             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8039                                                             CanonType)))
8040           continue;
8041 
8042         QualType ParamTypes[2] = { *Enum, *Enum };
8043         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8044       }
8045     }
8046   }
8047 
8048   // C++ [over.built]p13:
8049   //
8050   //   For every cv-qualified or cv-unqualified object type T
8051   //   there exist candidate operator functions of the form
8052   //
8053   //      T*         operator+(T*, ptrdiff_t);
8054   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8055   //      T*         operator-(T*, ptrdiff_t);
8056   //      T*         operator+(ptrdiff_t, T*);
8057   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8058   //
8059   // C++ [over.built]p14:
8060   //
8061   //   For every T, where T is a pointer to object type, there
8062   //   exist candidate operator functions of the form
8063   //
8064   //      ptrdiff_t  operator-(T, T);
8065   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8066     /// Set of (canonical) types that we've already handled.
8067     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8068 
8069     for (int Arg = 0; Arg < 2; ++Arg) {
8070       QualType AsymmetricParamTypes[2] = {
8071         S.Context.getPointerDiffType(),
8072         S.Context.getPointerDiffType(),
8073       };
8074       for (BuiltinCandidateTypeSet::iterator
8075                 Ptr = CandidateTypes[Arg].pointer_begin(),
8076              PtrEnd = CandidateTypes[Arg].pointer_end();
8077            Ptr != PtrEnd; ++Ptr) {
8078         QualType PointeeTy = (*Ptr)->getPointeeType();
8079         if (!PointeeTy->isObjectType())
8080           continue;
8081 
8082         AsymmetricParamTypes[Arg] = *Ptr;
8083         if (Arg == 0 || Op == OO_Plus) {
8084           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8085           // T* operator+(ptrdiff_t, T*);
8086           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8087         }
8088         if (Op == OO_Minus) {
8089           // ptrdiff_t operator-(T, T);
8090           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8091             continue;
8092 
8093           QualType ParamTypes[2] = { *Ptr, *Ptr };
8094           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8095         }
8096       }
8097     }
8098   }
8099 
8100   // C++ [over.built]p12:
8101   //
8102   //   For every pair of promoted arithmetic types L and R, there
8103   //   exist candidate operator functions of the form
8104   //
8105   //        LR         operator*(L, R);
8106   //        LR         operator/(L, R);
8107   //        LR         operator+(L, R);
8108   //        LR         operator-(L, R);
8109   //        bool       operator<(L, R);
8110   //        bool       operator>(L, R);
8111   //        bool       operator<=(L, R);
8112   //        bool       operator>=(L, R);
8113   //        bool       operator==(L, R);
8114   //        bool       operator!=(L, R);
8115   //
8116   //   where LR is the result of the usual arithmetic conversions
8117   //   between types L and R.
8118   //
8119   // C++ [over.built]p24:
8120   //
8121   //   For every pair of promoted arithmetic types L and R, there exist
8122   //   candidate operator functions of the form
8123   //
8124   //        LR       operator?(bool, L, R);
8125   //
8126   //   where LR is the result of the usual arithmetic conversions
8127   //   between types L and R.
8128   // Our candidates ignore the first parameter.
8129   void addGenericBinaryArithmeticOverloads() {
8130     if (!HasArithmeticOrEnumeralCandidateType)
8131       return;
8132 
8133     for (unsigned Left = FirstPromotedArithmeticType;
8134          Left < LastPromotedArithmeticType; ++Left) {
8135       for (unsigned Right = FirstPromotedArithmeticType;
8136            Right < LastPromotedArithmeticType; ++Right) {
8137         QualType LandR[2] = { ArithmeticTypes[Left],
8138                               ArithmeticTypes[Right] };
8139         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8140       }
8141     }
8142 
8143     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8144     // conditional operator for vector types.
8145     for (BuiltinCandidateTypeSet::iterator
8146               Vec1 = CandidateTypes[0].vector_begin(),
8147            Vec1End = CandidateTypes[0].vector_end();
8148          Vec1 != Vec1End; ++Vec1) {
8149       for (BuiltinCandidateTypeSet::iterator
8150                 Vec2 = CandidateTypes[1].vector_begin(),
8151              Vec2End = CandidateTypes[1].vector_end();
8152            Vec2 != Vec2End; ++Vec2) {
8153         QualType LandR[2] = { *Vec1, *Vec2 };
8154         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8155       }
8156     }
8157   }
8158 
8159   // C++ [over.built]p17:
8160   //
8161   //   For every pair of promoted integral types L and R, there
8162   //   exist candidate operator functions of the form
8163   //
8164   //      LR         operator%(L, R);
8165   //      LR         operator&(L, R);
8166   //      LR         operator^(L, R);
8167   //      LR         operator|(L, R);
8168   //      L          operator<<(L, R);
8169   //      L          operator>>(L, R);
8170   //
8171   //   where LR is the result of the usual arithmetic conversions
8172   //   between types L and R.
8173   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8174     if (!HasArithmeticOrEnumeralCandidateType)
8175       return;
8176 
8177     for (unsigned Left = FirstPromotedIntegralType;
8178          Left < LastPromotedIntegralType; ++Left) {
8179       for (unsigned Right = FirstPromotedIntegralType;
8180            Right < LastPromotedIntegralType; ++Right) {
8181         QualType LandR[2] = { ArithmeticTypes[Left],
8182                               ArithmeticTypes[Right] };
8183         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8184       }
8185     }
8186   }
8187 
8188   // C++ [over.built]p20:
8189   //
8190   //   For every pair (T, VQ), where T is an enumeration or
8191   //   pointer to member type and VQ is either volatile or
8192   //   empty, there exist candidate operator functions of the form
8193   //
8194   //        VQ T&      operator=(VQ T&, T);
8195   void addAssignmentMemberPointerOrEnumeralOverloads() {
8196     /// Set of (canonical) types that we've already handled.
8197     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8198 
8199     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8200       for (BuiltinCandidateTypeSet::iterator
8201                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8202              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8203            Enum != EnumEnd; ++Enum) {
8204         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8205           continue;
8206 
8207         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8208       }
8209 
8210       for (BuiltinCandidateTypeSet::iterator
8211                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8212              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8213            MemPtr != MemPtrEnd; ++MemPtr) {
8214         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8215           continue;
8216 
8217         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8218       }
8219     }
8220   }
8221 
8222   // C++ [over.built]p19:
8223   //
8224   //   For every pair (T, VQ), where T is any type and VQ is either
8225   //   volatile or empty, there exist candidate operator functions
8226   //   of the form
8227   //
8228   //        T*VQ&      operator=(T*VQ&, T*);
8229   //
8230   // C++ [over.built]p21:
8231   //
8232   //   For every pair (T, VQ), where T is a cv-qualified or
8233   //   cv-unqualified object type and VQ is either volatile or
8234   //   empty, there exist candidate operator functions of the form
8235   //
8236   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8237   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8238   void addAssignmentPointerOverloads(bool isEqualOp) {
8239     /// Set of (canonical) types that we've already handled.
8240     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8241 
8242     for (BuiltinCandidateTypeSet::iterator
8243               Ptr = CandidateTypes[0].pointer_begin(),
8244            PtrEnd = CandidateTypes[0].pointer_end();
8245          Ptr != PtrEnd; ++Ptr) {
8246       // If this is operator=, keep track of the builtin candidates we added.
8247       if (isEqualOp)
8248         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8249       else if (!(*Ptr)->getPointeeType()->isObjectType())
8250         continue;
8251 
8252       // non-volatile version
8253       QualType ParamTypes[2] = {
8254         S.Context.getLValueReferenceType(*Ptr),
8255         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8256       };
8257       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8258                             /*IsAssigmentOperator=*/ isEqualOp);
8259 
8260       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8261                           VisibleTypeConversionsQuals.hasVolatile();
8262       if (NeedVolatile) {
8263         // volatile version
8264         ParamTypes[0] =
8265           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8266         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8267                               /*IsAssigmentOperator=*/isEqualOp);
8268       }
8269 
8270       if (!(*Ptr).isRestrictQualified() &&
8271           VisibleTypeConversionsQuals.hasRestrict()) {
8272         // restrict version
8273         ParamTypes[0]
8274           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8275         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8276                               /*IsAssigmentOperator=*/isEqualOp);
8277 
8278         if (NeedVolatile) {
8279           // volatile restrict version
8280           ParamTypes[0]
8281             = S.Context.getLValueReferenceType(
8282                 S.Context.getCVRQualifiedType(*Ptr,
8283                                               (Qualifiers::Volatile |
8284                                                Qualifiers::Restrict)));
8285           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8286                                 /*IsAssigmentOperator=*/isEqualOp);
8287         }
8288       }
8289     }
8290 
8291     if (isEqualOp) {
8292       for (BuiltinCandidateTypeSet::iterator
8293                 Ptr = CandidateTypes[1].pointer_begin(),
8294              PtrEnd = CandidateTypes[1].pointer_end();
8295            Ptr != PtrEnd; ++Ptr) {
8296         // Make sure we don't add the same candidate twice.
8297         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8298           continue;
8299 
8300         QualType ParamTypes[2] = {
8301           S.Context.getLValueReferenceType(*Ptr),
8302           *Ptr,
8303         };
8304 
8305         // non-volatile version
8306         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8307                               /*IsAssigmentOperator=*/true);
8308 
8309         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8310                            VisibleTypeConversionsQuals.hasVolatile();
8311         if (NeedVolatile) {
8312           // volatile version
8313           ParamTypes[0] =
8314             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8315           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8316                                 /*IsAssigmentOperator=*/true);
8317         }
8318 
8319         if (!(*Ptr).isRestrictQualified() &&
8320             VisibleTypeConversionsQuals.hasRestrict()) {
8321           // restrict version
8322           ParamTypes[0]
8323             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8324           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8325                                 /*IsAssigmentOperator=*/true);
8326 
8327           if (NeedVolatile) {
8328             // volatile restrict version
8329             ParamTypes[0]
8330               = S.Context.getLValueReferenceType(
8331                   S.Context.getCVRQualifiedType(*Ptr,
8332                                                 (Qualifiers::Volatile |
8333                                                  Qualifiers::Restrict)));
8334             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8335                                   /*IsAssigmentOperator=*/true);
8336           }
8337         }
8338       }
8339     }
8340   }
8341 
8342   // C++ [over.built]p18:
8343   //
8344   //   For every triple (L, VQ, R), where L is an arithmetic type,
8345   //   VQ is either volatile or empty, and R is a promoted
8346   //   arithmetic type, there exist candidate operator functions of
8347   //   the form
8348   //
8349   //        VQ L&      operator=(VQ L&, R);
8350   //        VQ L&      operator*=(VQ L&, R);
8351   //        VQ L&      operator/=(VQ L&, R);
8352   //        VQ L&      operator+=(VQ L&, R);
8353   //        VQ L&      operator-=(VQ L&, R);
8354   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8355     if (!HasArithmeticOrEnumeralCandidateType)
8356       return;
8357 
8358     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8359       for (unsigned Right = FirstPromotedArithmeticType;
8360            Right < LastPromotedArithmeticType; ++Right) {
8361         QualType ParamTypes[2];
8362         ParamTypes[1] = ArithmeticTypes[Right];
8363 
8364         // Add this built-in operator as a candidate (VQ is empty).
8365         ParamTypes[0] =
8366           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8367         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8368                               /*IsAssigmentOperator=*/isEqualOp);
8369 
8370         // Add this built-in operator as a candidate (VQ is 'volatile').
8371         if (VisibleTypeConversionsQuals.hasVolatile()) {
8372           ParamTypes[0] =
8373             S.Context.getVolatileType(ArithmeticTypes[Left]);
8374           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8375           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8376                                 /*IsAssigmentOperator=*/isEqualOp);
8377         }
8378       }
8379     }
8380 
8381     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8382     for (BuiltinCandidateTypeSet::iterator
8383               Vec1 = CandidateTypes[0].vector_begin(),
8384            Vec1End = CandidateTypes[0].vector_end();
8385          Vec1 != Vec1End; ++Vec1) {
8386       for (BuiltinCandidateTypeSet::iterator
8387                 Vec2 = CandidateTypes[1].vector_begin(),
8388              Vec2End = CandidateTypes[1].vector_end();
8389            Vec2 != Vec2End; ++Vec2) {
8390         QualType ParamTypes[2];
8391         ParamTypes[1] = *Vec2;
8392         // Add this built-in operator as a candidate (VQ is empty).
8393         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8394         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8395                               /*IsAssigmentOperator=*/isEqualOp);
8396 
8397         // Add this built-in operator as a candidate (VQ is 'volatile').
8398         if (VisibleTypeConversionsQuals.hasVolatile()) {
8399           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8400           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8401           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402                                 /*IsAssigmentOperator=*/isEqualOp);
8403         }
8404       }
8405     }
8406   }
8407 
8408   // C++ [over.built]p22:
8409   //
8410   //   For every triple (L, VQ, R), where L is an integral type, VQ
8411   //   is either volatile or empty, and R is a promoted integral
8412   //   type, there exist candidate operator functions of the form
8413   //
8414   //        VQ L&       operator%=(VQ L&, R);
8415   //        VQ L&       operator<<=(VQ L&, R);
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   void addAssignmentIntegralOverloads() {
8421     if (!HasArithmeticOrEnumeralCandidateType)
8422       return;
8423 
8424     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8425       for (unsigned Right = FirstPromotedIntegralType;
8426            Right < LastPromotedIntegralType; ++Right) {
8427         QualType ParamTypes[2];
8428         ParamTypes[1] = ArithmeticTypes[Right];
8429 
8430         // Add this built-in operator as a candidate (VQ is empty).
8431         ParamTypes[0] =
8432           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8433         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8434         if (VisibleTypeConversionsQuals.hasVolatile()) {
8435           // Add this built-in operator as a candidate (VQ is 'volatile').
8436           ParamTypes[0] = ArithmeticTypes[Left];
8437           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8438           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8439           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8440         }
8441       }
8442     }
8443   }
8444 
8445   // C++ [over.operator]p23:
8446   //
8447   //   There also exist candidate operator functions of the form
8448   //
8449   //        bool        operator!(bool);
8450   //        bool        operator&&(bool, bool);
8451   //        bool        operator||(bool, bool);
8452   void addExclaimOverload() {
8453     QualType ParamTy = S.Context.BoolTy;
8454     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8455                           /*IsAssignmentOperator=*/false,
8456                           /*NumContextualBoolArguments=*/1);
8457   }
8458   void addAmpAmpOrPipePipeOverload() {
8459     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8460     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8461                           /*IsAssignmentOperator=*/false,
8462                           /*NumContextualBoolArguments=*/2);
8463   }
8464 
8465   // C++ [over.built]p13:
8466   //
8467   //   For every cv-qualified or cv-unqualified object type T there
8468   //   exist candidate operator functions of the form
8469   //
8470   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8471   //        T&         operator[](T*, ptrdiff_t);
8472   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8473   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8474   //        T&         operator[](ptrdiff_t, T*);
8475   void addSubscriptOverloads() {
8476     for (BuiltinCandidateTypeSet::iterator
8477               Ptr = CandidateTypes[0].pointer_begin(),
8478            PtrEnd = CandidateTypes[0].pointer_end();
8479          Ptr != PtrEnd; ++Ptr) {
8480       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8481       QualType PointeeType = (*Ptr)->getPointeeType();
8482       if (!PointeeType->isObjectType())
8483         continue;
8484 
8485       // T& operator[](T*, ptrdiff_t)
8486       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8487     }
8488 
8489     for (BuiltinCandidateTypeSet::iterator
8490               Ptr = CandidateTypes[1].pointer_begin(),
8491            PtrEnd = CandidateTypes[1].pointer_end();
8492          Ptr != PtrEnd; ++Ptr) {
8493       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8494       QualType PointeeType = (*Ptr)->getPointeeType();
8495       if (!PointeeType->isObjectType())
8496         continue;
8497 
8498       // T& operator[](ptrdiff_t, T*)
8499       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8500     }
8501   }
8502 
8503   // C++ [over.built]p11:
8504   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8505   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8506   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8507   //    there exist candidate operator functions of the form
8508   //
8509   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8510   //
8511   //    where CV12 is the union of CV1 and CV2.
8512   void addArrowStarOverloads() {
8513     for (BuiltinCandidateTypeSet::iterator
8514              Ptr = CandidateTypes[0].pointer_begin(),
8515            PtrEnd = CandidateTypes[0].pointer_end();
8516          Ptr != PtrEnd; ++Ptr) {
8517       QualType C1Ty = (*Ptr);
8518       QualType C1;
8519       QualifierCollector Q1;
8520       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8521       if (!isa<RecordType>(C1))
8522         continue;
8523       // heuristic to reduce number of builtin candidates in the set.
8524       // Add volatile/restrict version only if there are conversions to a
8525       // volatile/restrict type.
8526       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8527         continue;
8528       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8529         continue;
8530       for (BuiltinCandidateTypeSet::iterator
8531                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8532              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8533            MemPtr != MemPtrEnd; ++MemPtr) {
8534         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8535         QualType C2 = QualType(mptr->getClass(), 0);
8536         C2 = C2.getUnqualifiedType();
8537         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8538           break;
8539         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8540         // build CV12 T&
8541         QualType T = mptr->getPointeeType();
8542         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8543             T.isVolatileQualified())
8544           continue;
8545         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8546             T.isRestrictQualified())
8547           continue;
8548         T = Q1.apply(S.Context, T);
8549         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8550       }
8551     }
8552   }
8553 
8554   // Note that we don't consider the first argument, since it has been
8555   // contextually converted to bool long ago. The candidates below are
8556   // therefore added as binary.
8557   //
8558   // C++ [over.built]p25:
8559   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8560   //   enumeration type, there exist candidate operator functions of the form
8561   //
8562   //        T        operator?(bool, T, T);
8563   //
8564   void addConditionalOperatorOverloads() {
8565     /// Set of (canonical) types that we've already handled.
8566     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8567 
8568     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8569       for (BuiltinCandidateTypeSet::iterator
8570                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8571              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8572            Ptr != PtrEnd; ++Ptr) {
8573         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8574           continue;
8575 
8576         QualType ParamTypes[2] = { *Ptr, *Ptr };
8577         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8578       }
8579 
8580       for (BuiltinCandidateTypeSet::iterator
8581                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8582              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8583            MemPtr != MemPtrEnd; ++MemPtr) {
8584         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8585           continue;
8586 
8587         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8588         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8589       }
8590 
8591       if (S.getLangOpts().CPlusPlus11) {
8592         for (BuiltinCandidateTypeSet::iterator
8593                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8594                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8595              Enum != EnumEnd; ++Enum) {
8596           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8597             continue;
8598 
8599           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8600             continue;
8601 
8602           QualType ParamTypes[2] = { *Enum, *Enum };
8603           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8604         }
8605       }
8606     }
8607   }
8608 };
8609 
8610 } // end anonymous namespace
8611 
8612 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8613 /// operator overloads to the candidate set (C++ [over.built]), based
8614 /// on the operator @p Op and the arguments given. For example, if the
8615 /// operator is a binary '+', this routine might add "int
8616 /// operator+(int, int)" to cover integer addition.
8617 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8618                                         SourceLocation OpLoc,
8619                                         ArrayRef<Expr *> Args,
8620                                         OverloadCandidateSet &CandidateSet) {
8621   // Find all of the types that the arguments can convert to, but only
8622   // if the operator we're looking at has built-in operator candidates
8623   // that make use of these types. Also record whether we encounter non-record
8624   // candidate types or either arithmetic or enumeral candidate types.
8625   Qualifiers VisibleTypeConversionsQuals;
8626   VisibleTypeConversionsQuals.addConst();
8627   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8628     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8629 
8630   bool HasNonRecordCandidateType = false;
8631   bool HasArithmeticOrEnumeralCandidateType = false;
8632   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8633   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8634     CandidateTypes.emplace_back(*this);
8635     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8636                                                  OpLoc,
8637                                                  true,
8638                                                  (Op == OO_Exclaim ||
8639                                                   Op == OO_AmpAmp ||
8640                                                   Op == OO_PipePipe),
8641                                                  VisibleTypeConversionsQuals);
8642     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8643         CandidateTypes[ArgIdx].hasNonRecordTypes();
8644     HasArithmeticOrEnumeralCandidateType =
8645         HasArithmeticOrEnumeralCandidateType ||
8646         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8647   }
8648 
8649   // Exit early when no non-record types have been added to the candidate set
8650   // for any of the arguments to the operator.
8651   //
8652   // We can't exit early for !, ||, or &&, since there we have always have
8653   // 'bool' overloads.
8654   if (!HasNonRecordCandidateType &&
8655       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8656     return;
8657 
8658   // Setup an object to manage the common state for building overloads.
8659   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8660                                            VisibleTypeConversionsQuals,
8661                                            HasArithmeticOrEnumeralCandidateType,
8662                                            CandidateTypes, CandidateSet);
8663 
8664   // Dispatch over the operation to add in only those overloads which apply.
8665   switch (Op) {
8666   case OO_None:
8667   case NUM_OVERLOADED_OPERATORS:
8668     llvm_unreachable("Expected an overloaded operator");
8669 
8670   case OO_New:
8671   case OO_Delete:
8672   case OO_Array_New:
8673   case OO_Array_Delete:
8674   case OO_Call:
8675     llvm_unreachable(
8676                     "Special operators don't use AddBuiltinOperatorCandidates");
8677 
8678   case OO_Comma:
8679   case OO_Arrow:
8680   case OO_Coawait:
8681     // C++ [over.match.oper]p3:
8682     //   -- For the operator ',', the unary operator '&', the
8683     //      operator '->', or the operator 'co_await', the
8684     //      built-in candidates set is empty.
8685     break;
8686 
8687   case OO_Plus: // '+' is either unary or binary
8688     if (Args.size() == 1)
8689       OpBuilder.addUnaryPlusPointerOverloads();
8690     LLVM_FALLTHROUGH;
8691 
8692   case OO_Minus: // '-' is either unary or binary
8693     if (Args.size() == 1) {
8694       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8695     } else {
8696       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8697       OpBuilder.addGenericBinaryArithmeticOverloads();
8698     }
8699     break;
8700 
8701   case OO_Star: // '*' is either unary or binary
8702     if (Args.size() == 1)
8703       OpBuilder.addUnaryStarPointerOverloads();
8704     else
8705       OpBuilder.addGenericBinaryArithmeticOverloads();
8706     break;
8707 
8708   case OO_Slash:
8709     OpBuilder.addGenericBinaryArithmeticOverloads();
8710     break;
8711 
8712   case OO_PlusPlus:
8713   case OO_MinusMinus:
8714     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8715     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8716     break;
8717 
8718   case OO_EqualEqual:
8719   case OO_ExclaimEqual:
8720     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8721     LLVM_FALLTHROUGH;
8722 
8723   case OO_Less:
8724   case OO_Greater:
8725   case OO_LessEqual:
8726   case OO_GreaterEqual:
8727     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8728     OpBuilder.addGenericBinaryArithmeticOverloads();
8729     break;
8730 
8731   case OO_Spaceship:
8732     llvm_unreachable("<=> expressions not supported yet");
8733 
8734   case OO_Percent:
8735   case OO_Caret:
8736   case OO_Pipe:
8737   case OO_LessLess:
8738   case OO_GreaterGreater:
8739     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8740     break;
8741 
8742   case OO_Amp: // '&' is either unary or binary
8743     if (Args.size() == 1)
8744       // C++ [over.match.oper]p3:
8745       //   -- For the operator ',', the unary operator '&', or the
8746       //      operator '->', the built-in candidates set is empty.
8747       break;
8748 
8749     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8750     break;
8751 
8752   case OO_Tilde:
8753     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8754     break;
8755 
8756   case OO_Equal:
8757     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8758     LLVM_FALLTHROUGH;
8759 
8760   case OO_PlusEqual:
8761   case OO_MinusEqual:
8762     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8763     LLVM_FALLTHROUGH;
8764 
8765   case OO_StarEqual:
8766   case OO_SlashEqual:
8767     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8768     break;
8769 
8770   case OO_PercentEqual:
8771   case OO_LessLessEqual:
8772   case OO_GreaterGreaterEqual:
8773   case OO_AmpEqual:
8774   case OO_CaretEqual:
8775   case OO_PipeEqual:
8776     OpBuilder.addAssignmentIntegralOverloads();
8777     break;
8778 
8779   case OO_Exclaim:
8780     OpBuilder.addExclaimOverload();
8781     break;
8782 
8783   case OO_AmpAmp:
8784   case OO_PipePipe:
8785     OpBuilder.addAmpAmpOrPipePipeOverload();
8786     break;
8787 
8788   case OO_Subscript:
8789     OpBuilder.addSubscriptOverloads();
8790     break;
8791 
8792   case OO_ArrowStar:
8793     OpBuilder.addArrowStarOverloads();
8794     break;
8795 
8796   case OO_Conditional:
8797     OpBuilder.addConditionalOperatorOverloads();
8798     OpBuilder.addGenericBinaryArithmeticOverloads();
8799     break;
8800   }
8801 }
8802 
8803 /// \brief Add function candidates found via argument-dependent lookup
8804 /// to the set of overloading candidates.
8805 ///
8806 /// This routine performs argument-dependent name lookup based on the
8807 /// given function name (which may also be an operator name) and adds
8808 /// all of the overload candidates found by ADL to the overload
8809 /// candidate set (C++ [basic.lookup.argdep]).
8810 void
8811 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8812                                            SourceLocation Loc,
8813                                            ArrayRef<Expr *> Args,
8814                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8815                                            OverloadCandidateSet& CandidateSet,
8816                                            bool PartialOverloading) {
8817   ADLResult Fns;
8818 
8819   // FIXME: This approach for uniquing ADL results (and removing
8820   // redundant candidates from the set) relies on pointer-equality,
8821   // which means we need to key off the canonical decl.  However,
8822   // always going back to the canonical decl might not get us the
8823   // right set of default arguments.  What default arguments are
8824   // we supposed to consider on ADL candidates, anyway?
8825 
8826   // FIXME: Pass in the explicit template arguments?
8827   ArgumentDependentLookup(Name, Loc, Args, Fns);
8828 
8829   // Erase all of the candidates we already knew about.
8830   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8831                                    CandEnd = CandidateSet.end();
8832        Cand != CandEnd; ++Cand)
8833     if (Cand->Function) {
8834       Fns.erase(Cand->Function);
8835       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8836         Fns.erase(FunTmpl);
8837     }
8838 
8839   // For each of the ADL candidates we found, add it to the overload
8840   // set.
8841   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8842     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8843     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8844       if (ExplicitTemplateArgs)
8845         continue;
8846 
8847       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8848                            PartialOverloading);
8849     } else
8850       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8851                                    FoundDecl, ExplicitTemplateArgs,
8852                                    Args, CandidateSet, PartialOverloading);
8853   }
8854 }
8855 
8856 namespace {
8857 enum class Comparison { Equal, Better, Worse };
8858 }
8859 
8860 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8861 /// overload resolution.
8862 ///
8863 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8864 /// Cand1's first N enable_if attributes have precisely the same conditions as
8865 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8866 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8867 ///
8868 /// Note that you can have a pair of candidates such that Cand1's enable_if
8869 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8870 /// worse than Cand1's.
8871 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8872                                        const FunctionDecl *Cand2) {
8873   // Common case: One (or both) decls don't have enable_if attrs.
8874   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8875   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8876   if (!Cand1Attr || !Cand2Attr) {
8877     if (Cand1Attr == Cand2Attr)
8878       return Comparison::Equal;
8879     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8880   }
8881 
8882   // FIXME: The next several lines are just
8883   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8884   // instead of reverse order which is how they're stored in the AST.
8885   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8886   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8887 
8888   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8889   // has fewer enable_if attributes than Cand2.
8890   if (Cand1Attrs.size() < Cand2Attrs.size())
8891     return Comparison::Worse;
8892 
8893   auto Cand1I = Cand1Attrs.begin();
8894   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8895   for (auto &Cand2A : Cand2Attrs) {
8896     Cand1ID.clear();
8897     Cand2ID.clear();
8898 
8899     auto &Cand1A = *Cand1I++;
8900     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8901     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8902     if (Cand1ID != Cand2ID)
8903       return Comparison::Worse;
8904   }
8905 
8906   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8907 }
8908 
8909 /// isBetterOverloadCandidate - Determines whether the first overload
8910 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8911 bool clang::isBetterOverloadCandidate(
8912     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8913     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8914   // Define viable functions to be better candidates than non-viable
8915   // functions.
8916   if (!Cand2.Viable)
8917     return Cand1.Viable;
8918   else if (!Cand1.Viable)
8919     return false;
8920 
8921   // C++ [over.match.best]p1:
8922   //
8923   //   -- if F is a static member function, ICS1(F) is defined such
8924   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8925   //      any function G, and, symmetrically, ICS1(G) is neither
8926   //      better nor worse than ICS1(F).
8927   unsigned StartArg = 0;
8928   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8929     StartArg = 1;
8930 
8931   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8932     // We don't allow incompatible pointer conversions in C++.
8933     if (!S.getLangOpts().CPlusPlus)
8934       return ICS.isStandard() &&
8935              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8936 
8937     // The only ill-formed conversion we allow in C++ is the string literal to
8938     // char* conversion, which is only considered ill-formed after C++11.
8939     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8940            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8941   };
8942 
8943   // Define functions that don't require ill-formed conversions for a given
8944   // argument to be better candidates than functions that do.
8945   unsigned NumArgs = Cand1.Conversions.size();
8946   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8947   bool HasBetterConversion = false;
8948   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8949     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8950     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8951     if (Cand1Bad != Cand2Bad) {
8952       if (Cand1Bad)
8953         return false;
8954       HasBetterConversion = true;
8955     }
8956   }
8957 
8958   if (HasBetterConversion)
8959     return true;
8960 
8961   // C++ [over.match.best]p1:
8962   //   A viable function F1 is defined to be a better function than another
8963   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8964   //   conversion sequence than ICSi(F2), and then...
8965   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8966     switch (CompareImplicitConversionSequences(S, Loc,
8967                                                Cand1.Conversions[ArgIdx],
8968                                                Cand2.Conversions[ArgIdx])) {
8969     case ImplicitConversionSequence::Better:
8970       // Cand1 has a better conversion sequence.
8971       HasBetterConversion = true;
8972       break;
8973 
8974     case ImplicitConversionSequence::Worse:
8975       // Cand1 can't be better than Cand2.
8976       return false;
8977 
8978     case ImplicitConversionSequence::Indistinguishable:
8979       // Do nothing.
8980       break;
8981     }
8982   }
8983 
8984   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8985   //       ICSj(F2), or, if not that,
8986   if (HasBetterConversion)
8987     return true;
8988 
8989   //   -- the context is an initialization by user-defined conversion
8990   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8991   //      from the return type of F1 to the destination type (i.e.,
8992   //      the type of the entity being initialized) is a better
8993   //      conversion sequence than the standard conversion sequence
8994   //      from the return type of F2 to the destination type.
8995   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8996       Cand1.Function && Cand2.Function &&
8997       isa<CXXConversionDecl>(Cand1.Function) &&
8998       isa<CXXConversionDecl>(Cand2.Function)) {
8999     // First check whether we prefer one of the conversion functions over the
9000     // other. This only distinguishes the results in non-standard, extension
9001     // cases such as the conversion from a lambda closure type to a function
9002     // pointer or block.
9003     ImplicitConversionSequence::CompareKind Result =
9004         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9005     if (Result == ImplicitConversionSequence::Indistinguishable)
9006       Result = CompareStandardConversionSequences(S, Loc,
9007                                                   Cand1.FinalConversion,
9008                                                   Cand2.FinalConversion);
9009 
9010     if (Result != ImplicitConversionSequence::Indistinguishable)
9011       return Result == ImplicitConversionSequence::Better;
9012 
9013     // FIXME: Compare kind of reference binding if conversion functions
9014     // convert to a reference type used in direct reference binding, per
9015     // C++14 [over.match.best]p1 section 2 bullet 3.
9016   }
9017 
9018   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9019   // as combined with the resolution to CWG issue 243.
9020   //
9021   // When the context is initialization by constructor ([over.match.ctor] or
9022   // either phase of [over.match.list]), a constructor is preferred over
9023   // a conversion function.
9024   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9025       Cand1.Function && Cand2.Function &&
9026       isa<CXXConstructorDecl>(Cand1.Function) !=
9027           isa<CXXConstructorDecl>(Cand2.Function))
9028     return isa<CXXConstructorDecl>(Cand1.Function);
9029 
9030   //    -- F1 is a non-template function and F2 is a function template
9031   //       specialization, or, if not that,
9032   bool Cand1IsSpecialization = Cand1.Function &&
9033                                Cand1.Function->getPrimaryTemplate();
9034   bool Cand2IsSpecialization = Cand2.Function &&
9035                                Cand2.Function->getPrimaryTemplate();
9036   if (Cand1IsSpecialization != Cand2IsSpecialization)
9037     return Cand2IsSpecialization;
9038 
9039   //   -- F1 and F2 are function template specializations, and the function
9040   //      template for F1 is more specialized than the template for F2
9041   //      according to the partial ordering rules described in 14.5.5.2, or,
9042   //      if not that,
9043   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9044     if (FunctionTemplateDecl *BetterTemplate
9045           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9046                                          Cand2.Function->getPrimaryTemplate(),
9047                                          Loc,
9048                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9049                                                              : TPOC_Call,
9050                                          Cand1.ExplicitCallArguments,
9051                                          Cand2.ExplicitCallArguments))
9052       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9053   }
9054 
9055   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9056   // A derived-class constructor beats an (inherited) base class constructor.
9057   bool Cand1IsInherited =
9058       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9059   bool Cand2IsInherited =
9060       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9061   if (Cand1IsInherited != Cand2IsInherited)
9062     return Cand2IsInherited;
9063   else if (Cand1IsInherited) {
9064     assert(Cand2IsInherited);
9065     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9066     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9067     if (Cand1Class->isDerivedFrom(Cand2Class))
9068       return true;
9069     if (Cand2Class->isDerivedFrom(Cand1Class))
9070       return false;
9071     // Inherited from sibling base classes: still ambiguous.
9072   }
9073 
9074   // Check C++17 tie-breakers for deduction guides.
9075   {
9076     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9077     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9078     if (Guide1 && Guide2) {
9079       //  -- F1 is generated from a deduction-guide and F2 is not
9080       if (Guide1->isImplicit() != Guide2->isImplicit())
9081         return Guide2->isImplicit();
9082 
9083       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9084       if (Guide1->isCopyDeductionCandidate())
9085         return true;
9086     }
9087   }
9088 
9089   // Check for enable_if value-based overload resolution.
9090   if (Cand1.Function && Cand2.Function) {
9091     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9092     if (Cmp != Comparison::Equal)
9093       return Cmp == Comparison::Better;
9094   }
9095 
9096   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9097     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9098     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9099            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9100   }
9101 
9102   bool HasPS1 = Cand1.Function != nullptr &&
9103                 functionHasPassObjectSizeParams(Cand1.Function);
9104   bool HasPS2 = Cand2.Function != nullptr &&
9105                 functionHasPassObjectSizeParams(Cand2.Function);
9106   return HasPS1 != HasPS2 && HasPS1;
9107 }
9108 
9109 /// Determine whether two declarations are "equivalent" for the purposes of
9110 /// name lookup and overload resolution. This applies when the same internal/no
9111 /// linkage entity is defined by two modules (probably by textually including
9112 /// the same header). In such a case, we don't consider the declarations to
9113 /// declare the same entity, but we also don't want lookups with both
9114 /// declarations visible to be ambiguous in some cases (this happens when using
9115 /// a modularized libstdc++).
9116 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9117                                                   const NamedDecl *B) {
9118   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9119   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9120   if (!VA || !VB)
9121     return false;
9122 
9123   // The declarations must be declaring the same name as an internal linkage
9124   // entity in different modules.
9125   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9126           VB->getDeclContext()->getRedeclContext()) ||
9127       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9128           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9129       VA->isExternallyVisible() || VB->isExternallyVisible())
9130     return false;
9131 
9132   // Check that the declarations appear to be equivalent.
9133   //
9134   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9135   // For constants and functions, we should check the initializer or body is
9136   // the same. For non-constant variables, we shouldn't allow it at all.
9137   if (Context.hasSameType(VA->getType(), VB->getType()))
9138     return true;
9139 
9140   // Enum constants within unnamed enumerations will have different types, but
9141   // may still be similar enough to be interchangeable for our purposes.
9142   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9143     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9144       // Only handle anonymous enums. If the enumerations were named and
9145       // equivalent, they would have been merged to the same type.
9146       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9147       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9148       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9149           !Context.hasSameType(EnumA->getIntegerType(),
9150                                EnumB->getIntegerType()))
9151         return false;
9152       // Allow this only if the value is the same for both enumerators.
9153       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9154     }
9155   }
9156 
9157   // Nothing else is sufficiently similar.
9158   return false;
9159 }
9160 
9161 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9162     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9163   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9164 
9165   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9166   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9167       << !M << (M ? M->getFullModuleName() : "");
9168 
9169   for (auto *E : Equiv) {
9170     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9171     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9172         << !M << (M ? M->getFullModuleName() : "");
9173   }
9174 }
9175 
9176 /// \brief Computes the best viable function (C++ 13.3.3)
9177 /// within an overload candidate set.
9178 ///
9179 /// \param Loc The location of the function name (or operator symbol) for
9180 /// which overload resolution occurs.
9181 ///
9182 /// \param Best If overload resolution was successful or found a deleted
9183 /// function, \p Best points to the candidate function found.
9184 ///
9185 /// \returns The result of overload resolution.
9186 OverloadingResult
9187 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9188                                          iterator &Best) {
9189   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9190   std::transform(begin(), end(), std::back_inserter(Candidates),
9191                  [](OverloadCandidate &Cand) { return &Cand; });
9192 
9193   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9194   // are accepted by both clang and NVCC. However, during a particular
9195   // compilation mode only one call variant is viable. We need to
9196   // exclude non-viable overload candidates from consideration based
9197   // only on their host/device attributes. Specifically, if one
9198   // candidate call is WrongSide and the other is SameSide, we ignore
9199   // the WrongSide candidate.
9200   if (S.getLangOpts().CUDA) {
9201     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9202     bool ContainsSameSideCandidate =
9203         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9204           return Cand->Function &&
9205                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9206                      Sema::CFP_SameSide;
9207         });
9208     if (ContainsSameSideCandidate) {
9209       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9210         return Cand->Function &&
9211                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9212                    Sema::CFP_WrongSide;
9213       };
9214       llvm::erase_if(Candidates, IsWrongSideCandidate);
9215     }
9216   }
9217 
9218   // Find the best viable function.
9219   Best = end();
9220   for (auto *Cand : Candidates)
9221     if (Cand->Viable)
9222       if (Best == end() ||
9223           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9224         Best = Cand;
9225 
9226   // If we didn't find any viable functions, abort.
9227   if (Best == end())
9228     return OR_No_Viable_Function;
9229 
9230   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9231 
9232   // Make sure that this function is better than every other viable
9233   // function. If not, we have an ambiguity.
9234   for (auto *Cand : Candidates) {
9235     if (Cand->Viable && Cand != Best &&
9236         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9237       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9238                                                    Cand->Function)) {
9239         EquivalentCands.push_back(Cand->Function);
9240         continue;
9241       }
9242 
9243       Best = end();
9244       return OR_Ambiguous;
9245     }
9246   }
9247 
9248   // Best is the best viable function.
9249   if (Best->Function &&
9250       (Best->Function->isDeleted() ||
9251        S.isFunctionConsideredUnavailable(Best->Function)))
9252     return OR_Deleted;
9253 
9254   if (!EquivalentCands.empty())
9255     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9256                                                     EquivalentCands);
9257 
9258   return OR_Success;
9259 }
9260 
9261 namespace {
9262 
9263 enum OverloadCandidateKind {
9264   oc_function,
9265   oc_method,
9266   oc_constructor,
9267   oc_function_template,
9268   oc_method_template,
9269   oc_constructor_template,
9270   oc_implicit_default_constructor,
9271   oc_implicit_copy_constructor,
9272   oc_implicit_move_constructor,
9273   oc_implicit_copy_assignment,
9274   oc_implicit_move_assignment,
9275   oc_inherited_constructor,
9276   oc_inherited_constructor_template
9277 };
9278 
9279 static OverloadCandidateKind
9280 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9281                           std::string &Description) {
9282   bool isTemplate = false;
9283 
9284   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9285     isTemplate = true;
9286     Description = S.getTemplateArgumentBindingsText(
9287       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9288   }
9289 
9290   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9291     if (!Ctor->isImplicit()) {
9292       if (isa<ConstructorUsingShadowDecl>(Found))
9293         return isTemplate ? oc_inherited_constructor_template
9294                           : oc_inherited_constructor;
9295       else
9296         return isTemplate ? oc_constructor_template : oc_constructor;
9297     }
9298 
9299     if (Ctor->isDefaultConstructor())
9300       return oc_implicit_default_constructor;
9301 
9302     if (Ctor->isMoveConstructor())
9303       return oc_implicit_move_constructor;
9304 
9305     assert(Ctor->isCopyConstructor() &&
9306            "unexpected sort of implicit constructor");
9307     return oc_implicit_copy_constructor;
9308   }
9309 
9310   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9311     // This actually gets spelled 'candidate function' for now, but
9312     // it doesn't hurt to split it out.
9313     if (!Meth->isImplicit())
9314       return isTemplate ? oc_method_template : oc_method;
9315 
9316     if (Meth->isMoveAssignmentOperator())
9317       return oc_implicit_move_assignment;
9318 
9319     if (Meth->isCopyAssignmentOperator())
9320       return oc_implicit_copy_assignment;
9321 
9322     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9323     return oc_method;
9324   }
9325 
9326   return isTemplate ? oc_function_template : oc_function;
9327 }
9328 
9329 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9330   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9331   // set.
9332   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9333     S.Diag(FoundDecl->getLocation(),
9334            diag::note_ovl_candidate_inherited_constructor)
9335       << Shadow->getNominatedBaseClass();
9336 }
9337 
9338 } // end anonymous namespace
9339 
9340 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9341                                     const FunctionDecl *FD) {
9342   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9343     bool AlwaysTrue;
9344     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9345       return false;
9346     if (!AlwaysTrue)
9347       return false;
9348   }
9349   return true;
9350 }
9351 
9352 /// \brief Returns true if we can take the address of the function.
9353 ///
9354 /// \param Complain - If true, we'll emit a diagnostic
9355 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9356 ///   we in overload resolution?
9357 /// \param Loc - The location of the statement we're complaining about. Ignored
9358 ///   if we're not complaining, or if we're in overload resolution.
9359 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9360                                               bool Complain,
9361                                               bool InOverloadResolution,
9362                                               SourceLocation Loc) {
9363   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9364     if (Complain) {
9365       if (InOverloadResolution)
9366         S.Diag(FD->getLocStart(),
9367                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9368       else
9369         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9370     }
9371     return false;
9372   }
9373 
9374   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9375     return P->hasAttr<PassObjectSizeAttr>();
9376   });
9377   if (I == FD->param_end())
9378     return true;
9379 
9380   if (Complain) {
9381     // Add one to ParamNo because it's user-facing
9382     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9383     if (InOverloadResolution)
9384       S.Diag(FD->getLocation(),
9385              diag::note_ovl_candidate_has_pass_object_size_params)
9386           << ParamNo;
9387     else
9388       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9389           << FD << ParamNo;
9390   }
9391   return false;
9392 }
9393 
9394 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9395                                                const FunctionDecl *FD) {
9396   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9397                                            /*InOverloadResolution=*/true,
9398                                            /*Loc=*/SourceLocation());
9399 }
9400 
9401 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9402                                              bool Complain,
9403                                              SourceLocation Loc) {
9404   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9405                                              /*InOverloadResolution=*/false,
9406                                              Loc);
9407 }
9408 
9409 // Notes the location of an overload candidate.
9410 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9411                                  QualType DestType, bool TakingAddress) {
9412   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9413     return;
9414   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9415     return;
9416 
9417   std::string FnDesc;
9418   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9419   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9420                              << (unsigned) K << Fn << FnDesc;
9421 
9422   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9423   Diag(Fn->getLocation(), PD);
9424   MaybeEmitInheritedConstructorNote(*this, Found);
9425 }
9426 
9427 // Notes the location of all overload candidates designated through
9428 // OverloadedExpr
9429 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9430                                      bool TakingAddress) {
9431   assert(OverloadedExpr->getType() == Context.OverloadTy);
9432 
9433   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9434   OverloadExpr *OvlExpr = Ovl.Expression;
9435 
9436   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9437                             IEnd = OvlExpr->decls_end();
9438        I != IEnd; ++I) {
9439     if (FunctionTemplateDecl *FunTmpl =
9440                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9441       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9442                             TakingAddress);
9443     } else if (FunctionDecl *Fun
9444                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9445       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9446     }
9447   }
9448 }
9449 
9450 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9451 /// "lead" diagnostic; it will be given two arguments, the source and
9452 /// target types of the conversion.
9453 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9454                                  Sema &S,
9455                                  SourceLocation CaretLoc,
9456                                  const PartialDiagnostic &PDiag) const {
9457   S.Diag(CaretLoc, PDiag)
9458     << Ambiguous.getFromType() << Ambiguous.getToType();
9459   // FIXME: The note limiting machinery is borrowed from
9460   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9461   // refactoring here.
9462   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9463   unsigned CandsShown = 0;
9464   AmbiguousConversionSequence::const_iterator I, E;
9465   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9466     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9467       break;
9468     ++CandsShown;
9469     S.NoteOverloadCandidate(I->first, I->second);
9470   }
9471   if (I != E)
9472     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9473 }
9474 
9475 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9476                                   unsigned I, bool TakingCandidateAddress) {
9477   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9478   assert(Conv.isBad());
9479   assert(Cand->Function && "for now, candidate must be a function");
9480   FunctionDecl *Fn = Cand->Function;
9481 
9482   // There's a conversion slot for the object argument if this is a
9483   // non-constructor method.  Note that 'I' corresponds the
9484   // conversion-slot index.
9485   bool isObjectArgument = false;
9486   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9487     if (I == 0)
9488       isObjectArgument = true;
9489     else
9490       I--;
9491   }
9492 
9493   std::string FnDesc;
9494   OverloadCandidateKind FnKind =
9495       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9496 
9497   Expr *FromExpr = Conv.Bad.FromExpr;
9498   QualType FromTy = Conv.Bad.getFromType();
9499   QualType ToTy = Conv.Bad.getToType();
9500 
9501   if (FromTy == S.Context.OverloadTy) {
9502     assert(FromExpr && "overload set argument came from implicit argument?");
9503     Expr *E = FromExpr->IgnoreParens();
9504     if (isa<UnaryOperator>(E))
9505       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9506     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9507 
9508     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9509       << (unsigned) FnKind << FnDesc
9510       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9511       << ToTy << Name << I+1;
9512     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9513     return;
9514   }
9515 
9516   // Do some hand-waving analysis to see if the non-viability is due
9517   // to a qualifier mismatch.
9518   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9519   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9520   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9521     CToTy = RT->getPointeeType();
9522   else {
9523     // TODO: detect and diagnose the full richness of const mismatches.
9524     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9525       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9526         CFromTy = FromPT->getPointeeType();
9527         CToTy = ToPT->getPointeeType();
9528       }
9529   }
9530 
9531   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9532       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9533     Qualifiers FromQs = CFromTy.getQualifiers();
9534     Qualifiers ToQs = CToTy.getQualifiers();
9535 
9536     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9537       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9538         << (unsigned) FnKind << FnDesc
9539         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9540         << FromTy
9541         << FromQs.getAddressSpaceAttributePrintValue()
9542         << ToQs.getAddressSpaceAttributePrintValue()
9543         << (unsigned) isObjectArgument << I+1;
9544       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9545       return;
9546     }
9547 
9548     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9549       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9550         << (unsigned) FnKind << FnDesc
9551         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9552         << FromTy
9553         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9554         << (unsigned) isObjectArgument << I+1;
9555       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9556       return;
9557     }
9558 
9559     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9560       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9561       << (unsigned) FnKind << FnDesc
9562       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9563       << FromTy
9564       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9565       << (unsigned) isObjectArgument << I+1;
9566       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9567       return;
9568     }
9569 
9570     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9571       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9572         << (unsigned) FnKind << FnDesc
9573         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9574         << FromTy << FromQs.hasUnaligned() << I+1;
9575       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9576       return;
9577     }
9578 
9579     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9580     assert(CVR && "unexpected qualifiers mismatch");
9581 
9582     if (isObjectArgument) {
9583       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9584         << (unsigned) FnKind << FnDesc
9585         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9586         << FromTy << (CVR - 1);
9587     } else {
9588       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9589         << (unsigned) FnKind << FnDesc
9590         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9591         << FromTy << (CVR - 1) << I+1;
9592     }
9593     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9594     return;
9595   }
9596 
9597   // Special diagnostic for failure to convert an initializer list, since
9598   // telling the user that it has type void is not useful.
9599   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9600     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9601       << (unsigned) FnKind << FnDesc
9602       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9603       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9604     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9605     return;
9606   }
9607 
9608   // Diagnose references or pointers to incomplete types differently,
9609   // since it's far from impossible that the incompleteness triggered
9610   // the failure.
9611   QualType TempFromTy = FromTy.getNonReferenceType();
9612   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9613     TempFromTy = PTy->getPointeeType();
9614   if (TempFromTy->isIncompleteType()) {
9615     // Emit the generic diagnostic and, optionally, add the hints to it.
9616     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9617       << (unsigned) FnKind << FnDesc
9618       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9619       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9620       << (unsigned) (Cand->Fix.Kind);
9621 
9622     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9623     return;
9624   }
9625 
9626   // Diagnose base -> derived pointer conversions.
9627   unsigned BaseToDerivedConversion = 0;
9628   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9629     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9630       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9631                                                FromPtrTy->getPointeeType()) &&
9632           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9633           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9634           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9635                           FromPtrTy->getPointeeType()))
9636         BaseToDerivedConversion = 1;
9637     }
9638   } else if (const ObjCObjectPointerType *FromPtrTy
9639                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9640     if (const ObjCObjectPointerType *ToPtrTy
9641                                         = ToTy->getAs<ObjCObjectPointerType>())
9642       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9643         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9644           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9645                                                 FromPtrTy->getPointeeType()) &&
9646               FromIface->isSuperClassOf(ToIface))
9647             BaseToDerivedConversion = 2;
9648   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9649     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9650         !FromTy->isIncompleteType() &&
9651         !ToRefTy->getPointeeType()->isIncompleteType() &&
9652         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9653       BaseToDerivedConversion = 3;
9654     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9655                ToTy.getNonReferenceType().getCanonicalType() ==
9656                FromTy.getNonReferenceType().getCanonicalType()) {
9657       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9658         << (unsigned) FnKind << FnDesc
9659         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9660         << (unsigned) isObjectArgument << I + 1;
9661       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9662       return;
9663     }
9664   }
9665 
9666   if (BaseToDerivedConversion) {
9667     S.Diag(Fn->getLocation(),
9668            diag::note_ovl_candidate_bad_base_to_derived_conv)
9669       << (unsigned) FnKind << FnDesc
9670       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9671       << (BaseToDerivedConversion - 1)
9672       << FromTy << ToTy << I+1;
9673     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9674     return;
9675   }
9676 
9677   if (isa<ObjCObjectPointerType>(CFromTy) &&
9678       isa<PointerType>(CToTy)) {
9679       Qualifiers FromQs = CFromTy.getQualifiers();
9680       Qualifiers ToQs = CToTy.getQualifiers();
9681       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9682         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9683         << (unsigned) FnKind << FnDesc
9684         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9685         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9686         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9687         return;
9688       }
9689   }
9690 
9691   if (TakingCandidateAddress &&
9692       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9693     return;
9694 
9695   // Emit the generic diagnostic and, optionally, add the hints to it.
9696   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9697   FDiag << (unsigned) FnKind << FnDesc
9698     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9699     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9700     << (unsigned) (Cand->Fix.Kind);
9701 
9702   // If we can fix the conversion, suggest the FixIts.
9703   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9704        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9705     FDiag << *HI;
9706   S.Diag(Fn->getLocation(), FDiag);
9707 
9708   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9709 }
9710 
9711 /// Additional arity mismatch diagnosis specific to a function overload
9712 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9713 /// over a candidate in any candidate set.
9714 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9715                                unsigned NumArgs) {
9716   FunctionDecl *Fn = Cand->Function;
9717   unsigned MinParams = Fn->getMinRequiredArguments();
9718 
9719   // With invalid overloaded operators, it's possible that we think we
9720   // have an arity mismatch when in fact it looks like we have the
9721   // right number of arguments, because only overloaded operators have
9722   // the weird behavior of overloading member and non-member functions.
9723   // Just don't report anything.
9724   if (Fn->isInvalidDecl() &&
9725       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9726     return true;
9727 
9728   if (NumArgs < MinParams) {
9729     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9730            (Cand->FailureKind == ovl_fail_bad_deduction &&
9731             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9732   } else {
9733     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9734            (Cand->FailureKind == ovl_fail_bad_deduction &&
9735             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9736   }
9737 
9738   return false;
9739 }
9740 
9741 /// General arity mismatch diagnosis over a candidate in a candidate set.
9742 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9743                                   unsigned NumFormalArgs) {
9744   assert(isa<FunctionDecl>(D) &&
9745       "The templated declaration should at least be a function"
9746       " when diagnosing bad template argument deduction due to too many"
9747       " or too few arguments");
9748 
9749   FunctionDecl *Fn = cast<FunctionDecl>(D);
9750 
9751   // TODO: treat calls to a missing default constructor as a special case
9752   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9753   unsigned MinParams = Fn->getMinRequiredArguments();
9754 
9755   // at least / at most / exactly
9756   unsigned mode, modeCount;
9757   if (NumFormalArgs < MinParams) {
9758     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9759         FnTy->isTemplateVariadic())
9760       mode = 0; // "at least"
9761     else
9762       mode = 2; // "exactly"
9763     modeCount = MinParams;
9764   } else {
9765     if (MinParams != FnTy->getNumParams())
9766       mode = 1; // "at most"
9767     else
9768       mode = 2; // "exactly"
9769     modeCount = FnTy->getNumParams();
9770   }
9771 
9772   std::string Description;
9773   OverloadCandidateKind FnKind =
9774       ClassifyOverloadCandidate(S, Found, Fn, Description);
9775 
9776   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9777     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9778       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9779       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9780   else
9781     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9782       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9783       << mode << modeCount << NumFormalArgs;
9784   MaybeEmitInheritedConstructorNote(S, Found);
9785 }
9786 
9787 /// Arity mismatch diagnosis specific to a function overload candidate.
9788 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9789                                   unsigned NumFormalArgs) {
9790   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9791     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9792 }
9793 
9794 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9795   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9796     return TD;
9797   llvm_unreachable("Unsupported: Getting the described template declaration"
9798                    " for bad deduction diagnosis");
9799 }
9800 
9801 /// Diagnose a failed template-argument deduction.
9802 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9803                                  DeductionFailureInfo &DeductionFailure,
9804                                  unsigned NumArgs,
9805                                  bool TakingCandidateAddress) {
9806   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9807   NamedDecl *ParamD;
9808   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9809   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9810   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9811   switch (DeductionFailure.Result) {
9812   case Sema::TDK_Success:
9813     llvm_unreachable("TDK_success while diagnosing bad deduction");
9814 
9815   case Sema::TDK_Incomplete: {
9816     assert(ParamD && "no parameter found for incomplete deduction result");
9817     S.Diag(Templated->getLocation(),
9818            diag::note_ovl_candidate_incomplete_deduction)
9819         << ParamD->getDeclName();
9820     MaybeEmitInheritedConstructorNote(S, Found);
9821     return;
9822   }
9823 
9824   case Sema::TDK_Underqualified: {
9825     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9826     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9827 
9828     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9829 
9830     // Param will have been canonicalized, but it should just be a
9831     // qualified version of ParamD, so move the qualifiers to that.
9832     QualifierCollector Qs;
9833     Qs.strip(Param);
9834     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9835     assert(S.Context.hasSameType(Param, NonCanonParam));
9836 
9837     // Arg has also been canonicalized, but there's nothing we can do
9838     // about that.  It also doesn't matter as much, because it won't
9839     // have any template parameters in it (because deduction isn't
9840     // done on dependent types).
9841     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9842 
9843     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9844         << ParamD->getDeclName() << Arg << NonCanonParam;
9845     MaybeEmitInheritedConstructorNote(S, Found);
9846     return;
9847   }
9848 
9849   case Sema::TDK_Inconsistent: {
9850     assert(ParamD && "no parameter found for inconsistent deduction result");
9851     int which = 0;
9852     if (isa<TemplateTypeParmDecl>(ParamD))
9853       which = 0;
9854     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9855       // Deduction might have failed because we deduced arguments of two
9856       // different types for a non-type template parameter.
9857       // FIXME: Use a different TDK value for this.
9858       QualType T1 =
9859           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9860       QualType T2 =
9861           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9862       if (!S.Context.hasSameType(T1, T2)) {
9863         S.Diag(Templated->getLocation(),
9864                diag::note_ovl_candidate_inconsistent_deduction_types)
9865           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9866           << *DeductionFailure.getSecondArg() << T2;
9867         MaybeEmitInheritedConstructorNote(S, Found);
9868         return;
9869       }
9870 
9871       which = 1;
9872     } else {
9873       which = 2;
9874     }
9875 
9876     S.Diag(Templated->getLocation(),
9877            diag::note_ovl_candidate_inconsistent_deduction)
9878         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9879         << *DeductionFailure.getSecondArg();
9880     MaybeEmitInheritedConstructorNote(S, Found);
9881     return;
9882   }
9883 
9884   case Sema::TDK_InvalidExplicitArguments:
9885     assert(ParamD && "no parameter found for invalid explicit arguments");
9886     if (ParamD->getDeclName())
9887       S.Diag(Templated->getLocation(),
9888              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9889           << ParamD->getDeclName();
9890     else {
9891       int index = 0;
9892       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9893         index = TTP->getIndex();
9894       else if (NonTypeTemplateParmDecl *NTTP
9895                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9896         index = NTTP->getIndex();
9897       else
9898         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9899       S.Diag(Templated->getLocation(),
9900              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9901           << (index + 1);
9902     }
9903     MaybeEmitInheritedConstructorNote(S, Found);
9904     return;
9905 
9906   case Sema::TDK_TooManyArguments:
9907   case Sema::TDK_TooFewArguments:
9908     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9909     return;
9910 
9911   case Sema::TDK_InstantiationDepth:
9912     S.Diag(Templated->getLocation(),
9913            diag::note_ovl_candidate_instantiation_depth);
9914     MaybeEmitInheritedConstructorNote(S, Found);
9915     return;
9916 
9917   case Sema::TDK_SubstitutionFailure: {
9918     // Format the template argument list into the argument string.
9919     SmallString<128> TemplateArgString;
9920     if (TemplateArgumentList *Args =
9921             DeductionFailure.getTemplateArgumentList()) {
9922       TemplateArgString = " ";
9923       TemplateArgString += S.getTemplateArgumentBindingsText(
9924           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9925     }
9926 
9927     // If this candidate was disabled by enable_if, say so.
9928     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9929     if (PDiag && PDiag->second.getDiagID() ==
9930           diag::err_typename_nested_not_found_enable_if) {
9931       // FIXME: Use the source range of the condition, and the fully-qualified
9932       //        name of the enable_if template. These are both present in PDiag.
9933       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9934         << "'enable_if'" << TemplateArgString;
9935       return;
9936     }
9937 
9938     // We found a specific requirement that disabled the enable_if.
9939     if (PDiag && PDiag->second.getDiagID() ==
9940         diag::err_typename_nested_not_found_requirement) {
9941       S.Diag(Templated->getLocation(),
9942              diag::note_ovl_candidate_disabled_by_requirement)
9943         << PDiag->second.getStringArg(0) << TemplateArgString;
9944       return;
9945     }
9946 
9947     // Format the SFINAE diagnostic into the argument string.
9948     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9949     //        formatted message in another diagnostic.
9950     SmallString<128> SFINAEArgString;
9951     SourceRange R;
9952     if (PDiag) {
9953       SFINAEArgString = ": ";
9954       R = SourceRange(PDiag->first, PDiag->first);
9955       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9956     }
9957 
9958     S.Diag(Templated->getLocation(),
9959            diag::note_ovl_candidate_substitution_failure)
9960         << TemplateArgString << SFINAEArgString << R;
9961     MaybeEmitInheritedConstructorNote(S, Found);
9962     return;
9963   }
9964 
9965   case Sema::TDK_DeducedMismatch:
9966   case Sema::TDK_DeducedMismatchNested: {
9967     // Format the template argument list into the argument string.
9968     SmallString<128> TemplateArgString;
9969     if (TemplateArgumentList *Args =
9970             DeductionFailure.getTemplateArgumentList()) {
9971       TemplateArgString = " ";
9972       TemplateArgString += S.getTemplateArgumentBindingsText(
9973           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9974     }
9975 
9976     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9977         << (*DeductionFailure.getCallArgIndex() + 1)
9978         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9979         << TemplateArgString
9980         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9981     break;
9982   }
9983 
9984   case Sema::TDK_NonDeducedMismatch: {
9985     // FIXME: Provide a source location to indicate what we couldn't match.
9986     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9987     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9988     if (FirstTA.getKind() == TemplateArgument::Template &&
9989         SecondTA.getKind() == TemplateArgument::Template) {
9990       TemplateName FirstTN = FirstTA.getAsTemplate();
9991       TemplateName SecondTN = SecondTA.getAsTemplate();
9992       if (FirstTN.getKind() == TemplateName::Template &&
9993           SecondTN.getKind() == TemplateName::Template) {
9994         if (FirstTN.getAsTemplateDecl()->getName() ==
9995             SecondTN.getAsTemplateDecl()->getName()) {
9996           // FIXME: This fixes a bad diagnostic where both templates are named
9997           // the same.  This particular case is a bit difficult since:
9998           // 1) It is passed as a string to the diagnostic printer.
9999           // 2) The diagnostic printer only attempts to find a better
10000           //    name for types, not decls.
10001           // Ideally, this should folded into the diagnostic printer.
10002           S.Diag(Templated->getLocation(),
10003                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10004               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10005           return;
10006         }
10007       }
10008     }
10009 
10010     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10011         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10012       return;
10013 
10014     // FIXME: For generic lambda parameters, check if the function is a lambda
10015     // call operator, and if so, emit a prettier and more informative
10016     // diagnostic that mentions 'auto' and lambda in addition to
10017     // (or instead of?) the canonical template type parameters.
10018     S.Diag(Templated->getLocation(),
10019            diag::note_ovl_candidate_non_deduced_mismatch)
10020         << FirstTA << SecondTA;
10021     return;
10022   }
10023   // TODO: diagnose these individually, then kill off
10024   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10025   case Sema::TDK_MiscellaneousDeductionFailure:
10026     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10027     MaybeEmitInheritedConstructorNote(S, Found);
10028     return;
10029   case Sema::TDK_CUDATargetMismatch:
10030     S.Diag(Templated->getLocation(),
10031            diag::note_cuda_ovl_candidate_target_mismatch);
10032     return;
10033   }
10034 }
10035 
10036 /// Diagnose a failed template-argument deduction, for function calls.
10037 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10038                                  unsigned NumArgs,
10039                                  bool TakingCandidateAddress) {
10040   unsigned TDK = Cand->DeductionFailure.Result;
10041   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10042     if (CheckArityMismatch(S, Cand, NumArgs))
10043       return;
10044   }
10045   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10046                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10047 }
10048 
10049 /// CUDA: diagnose an invalid call across targets.
10050 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10051   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10052   FunctionDecl *Callee = Cand->Function;
10053 
10054   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10055                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10056 
10057   std::string FnDesc;
10058   OverloadCandidateKind FnKind =
10059       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10060 
10061   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10062       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10063 
10064   // This could be an implicit constructor for which we could not infer the
10065   // target due to a collsion. Diagnose that case.
10066   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10067   if (Meth != nullptr && Meth->isImplicit()) {
10068     CXXRecordDecl *ParentClass = Meth->getParent();
10069     Sema::CXXSpecialMember CSM;
10070 
10071     switch (FnKind) {
10072     default:
10073       return;
10074     case oc_implicit_default_constructor:
10075       CSM = Sema::CXXDefaultConstructor;
10076       break;
10077     case oc_implicit_copy_constructor:
10078       CSM = Sema::CXXCopyConstructor;
10079       break;
10080     case oc_implicit_move_constructor:
10081       CSM = Sema::CXXMoveConstructor;
10082       break;
10083     case oc_implicit_copy_assignment:
10084       CSM = Sema::CXXCopyAssignment;
10085       break;
10086     case oc_implicit_move_assignment:
10087       CSM = Sema::CXXMoveAssignment;
10088       break;
10089     };
10090 
10091     bool ConstRHS = false;
10092     if (Meth->getNumParams()) {
10093       if (const ReferenceType *RT =
10094               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10095         ConstRHS = RT->getPointeeType().isConstQualified();
10096       }
10097     }
10098 
10099     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10100                                               /* ConstRHS */ ConstRHS,
10101                                               /* Diagnose */ true);
10102   }
10103 }
10104 
10105 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10106   FunctionDecl *Callee = Cand->Function;
10107   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10108 
10109   S.Diag(Callee->getLocation(),
10110          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10111       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10112 }
10113 
10114 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10115   FunctionDecl *Callee = Cand->Function;
10116 
10117   S.Diag(Callee->getLocation(),
10118          diag::note_ovl_candidate_disabled_by_extension);
10119 }
10120 
10121 /// Generates a 'note' diagnostic for an overload candidate.  We've
10122 /// already generated a primary error at the call site.
10123 ///
10124 /// It really does need to be a single diagnostic with its caret
10125 /// pointed at the candidate declaration.  Yes, this creates some
10126 /// major challenges of technical writing.  Yes, this makes pointing
10127 /// out problems with specific arguments quite awkward.  It's still
10128 /// better than generating twenty screens of text for every failed
10129 /// overload.
10130 ///
10131 /// It would be great to be able to express per-candidate problems
10132 /// more richly for those diagnostic clients that cared, but we'd
10133 /// still have to be just as careful with the default diagnostics.
10134 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10135                                   unsigned NumArgs,
10136                                   bool TakingCandidateAddress) {
10137   FunctionDecl *Fn = Cand->Function;
10138 
10139   // Note deleted candidates, but only if they're viable.
10140   if (Cand->Viable) {
10141     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10142       std::string FnDesc;
10143       OverloadCandidateKind FnKind =
10144         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10145 
10146       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10147         << FnKind << FnDesc
10148         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10149       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10150       return;
10151     }
10152 
10153     // We don't really have anything else to say about viable candidates.
10154     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10155     return;
10156   }
10157 
10158   switch (Cand->FailureKind) {
10159   case ovl_fail_too_many_arguments:
10160   case ovl_fail_too_few_arguments:
10161     return DiagnoseArityMismatch(S, Cand, NumArgs);
10162 
10163   case ovl_fail_bad_deduction:
10164     return DiagnoseBadDeduction(S, Cand, NumArgs,
10165                                 TakingCandidateAddress);
10166 
10167   case ovl_fail_illegal_constructor: {
10168     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10169       << (Fn->getPrimaryTemplate() ? 1 : 0);
10170     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10171     return;
10172   }
10173 
10174   case ovl_fail_trivial_conversion:
10175   case ovl_fail_bad_final_conversion:
10176   case ovl_fail_final_conversion_not_exact:
10177     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10178 
10179   case ovl_fail_bad_conversion: {
10180     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10181     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10182       if (Cand->Conversions[I].isBad())
10183         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10184 
10185     // FIXME: this currently happens when we're called from SemaInit
10186     // when user-conversion overload fails.  Figure out how to handle
10187     // those conditions and diagnose them well.
10188     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10189   }
10190 
10191   case ovl_fail_bad_target:
10192     return DiagnoseBadTarget(S, Cand);
10193 
10194   case ovl_fail_enable_if:
10195     return DiagnoseFailedEnableIfAttr(S, Cand);
10196 
10197   case ovl_fail_ext_disabled:
10198     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10199 
10200   case ovl_fail_inhctor_slice:
10201     // It's generally not interesting to note copy/move constructors here.
10202     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10203       return;
10204     S.Diag(Fn->getLocation(),
10205            diag::note_ovl_candidate_inherited_constructor_slice)
10206       << (Fn->getPrimaryTemplate() ? 1 : 0)
10207       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10208     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10209     return;
10210 
10211   case ovl_fail_addr_not_available: {
10212     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10213     (void)Available;
10214     assert(!Available);
10215     break;
10216   }
10217   case ovl_non_default_multiversion_function:
10218     // Do nothing, these should simply be ignored.
10219     break;
10220   }
10221 }
10222 
10223 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10224   // Desugar the type of the surrogate down to a function type,
10225   // retaining as many typedefs as possible while still showing
10226   // the function type (and, therefore, its parameter types).
10227   QualType FnType = Cand->Surrogate->getConversionType();
10228   bool isLValueReference = false;
10229   bool isRValueReference = false;
10230   bool isPointer = false;
10231   if (const LValueReferenceType *FnTypeRef =
10232         FnType->getAs<LValueReferenceType>()) {
10233     FnType = FnTypeRef->getPointeeType();
10234     isLValueReference = true;
10235   } else if (const RValueReferenceType *FnTypeRef =
10236                FnType->getAs<RValueReferenceType>()) {
10237     FnType = FnTypeRef->getPointeeType();
10238     isRValueReference = true;
10239   }
10240   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10241     FnType = FnTypePtr->getPointeeType();
10242     isPointer = true;
10243   }
10244   // Desugar down to a function type.
10245   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10246   // Reconstruct the pointer/reference as appropriate.
10247   if (isPointer) FnType = S.Context.getPointerType(FnType);
10248   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10249   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10250 
10251   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10252     << FnType;
10253 }
10254 
10255 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10256                                          SourceLocation OpLoc,
10257                                          OverloadCandidate *Cand) {
10258   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10259   std::string TypeStr("operator");
10260   TypeStr += Opc;
10261   TypeStr += "(";
10262   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10263   if (Cand->Conversions.size() == 1) {
10264     TypeStr += ")";
10265     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10266   } else {
10267     TypeStr += ", ";
10268     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10269     TypeStr += ")";
10270     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10271   }
10272 }
10273 
10274 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10275                                          OverloadCandidate *Cand) {
10276   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10277     if (ICS.isBad()) break; // all meaningless after first invalid
10278     if (!ICS.isAmbiguous()) continue;
10279 
10280     ICS.DiagnoseAmbiguousConversion(
10281         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10282   }
10283 }
10284 
10285 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10286   if (Cand->Function)
10287     return Cand->Function->getLocation();
10288   if (Cand->IsSurrogate)
10289     return Cand->Surrogate->getLocation();
10290   return SourceLocation();
10291 }
10292 
10293 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10294   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10295   case Sema::TDK_Success:
10296   case Sema::TDK_NonDependentConversionFailure:
10297     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10298 
10299   case Sema::TDK_Invalid:
10300   case Sema::TDK_Incomplete:
10301     return 1;
10302 
10303   case Sema::TDK_Underqualified:
10304   case Sema::TDK_Inconsistent:
10305     return 2;
10306 
10307   case Sema::TDK_SubstitutionFailure:
10308   case Sema::TDK_DeducedMismatch:
10309   case Sema::TDK_DeducedMismatchNested:
10310   case Sema::TDK_NonDeducedMismatch:
10311   case Sema::TDK_MiscellaneousDeductionFailure:
10312   case Sema::TDK_CUDATargetMismatch:
10313     return 3;
10314 
10315   case Sema::TDK_InstantiationDepth:
10316     return 4;
10317 
10318   case Sema::TDK_InvalidExplicitArguments:
10319     return 5;
10320 
10321   case Sema::TDK_TooManyArguments:
10322   case Sema::TDK_TooFewArguments:
10323     return 6;
10324   }
10325   llvm_unreachable("Unhandled deduction result");
10326 }
10327 
10328 namespace {
10329 struct CompareOverloadCandidatesForDisplay {
10330   Sema &S;
10331   SourceLocation Loc;
10332   size_t NumArgs;
10333   OverloadCandidateSet::CandidateSetKind CSK;
10334 
10335   CompareOverloadCandidatesForDisplay(
10336       Sema &S, SourceLocation Loc, size_t NArgs,
10337       OverloadCandidateSet::CandidateSetKind CSK)
10338       : S(S), NumArgs(NArgs), CSK(CSK) {}
10339 
10340   bool operator()(const OverloadCandidate *L,
10341                   const OverloadCandidate *R) {
10342     // Fast-path this check.
10343     if (L == R) return false;
10344 
10345     // Order first by viability.
10346     if (L->Viable) {
10347       if (!R->Viable) return true;
10348 
10349       // TODO: introduce a tri-valued comparison for overload
10350       // candidates.  Would be more worthwhile if we had a sort
10351       // that could exploit it.
10352       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10353         return true;
10354       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10355         return false;
10356     } else if (R->Viable)
10357       return false;
10358 
10359     assert(L->Viable == R->Viable);
10360 
10361     // Criteria by which we can sort non-viable candidates:
10362     if (!L->Viable) {
10363       // 1. Arity mismatches come after other candidates.
10364       if (L->FailureKind == ovl_fail_too_many_arguments ||
10365           L->FailureKind == ovl_fail_too_few_arguments) {
10366         if (R->FailureKind == ovl_fail_too_many_arguments ||
10367             R->FailureKind == ovl_fail_too_few_arguments) {
10368           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10369           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10370           if (LDist == RDist) {
10371             if (L->FailureKind == R->FailureKind)
10372               // Sort non-surrogates before surrogates.
10373               return !L->IsSurrogate && R->IsSurrogate;
10374             // Sort candidates requiring fewer parameters than there were
10375             // arguments given after candidates requiring more parameters
10376             // than there were arguments given.
10377             return L->FailureKind == ovl_fail_too_many_arguments;
10378           }
10379           return LDist < RDist;
10380         }
10381         return false;
10382       }
10383       if (R->FailureKind == ovl_fail_too_many_arguments ||
10384           R->FailureKind == ovl_fail_too_few_arguments)
10385         return true;
10386 
10387       // 2. Bad conversions come first and are ordered by the number
10388       // of bad conversions and quality of good conversions.
10389       if (L->FailureKind == ovl_fail_bad_conversion) {
10390         if (R->FailureKind != ovl_fail_bad_conversion)
10391           return true;
10392 
10393         // The conversion that can be fixed with a smaller number of changes,
10394         // comes first.
10395         unsigned numLFixes = L->Fix.NumConversionsFixed;
10396         unsigned numRFixes = R->Fix.NumConversionsFixed;
10397         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10398         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10399         if (numLFixes != numRFixes) {
10400           return numLFixes < numRFixes;
10401         }
10402 
10403         // If there's any ordering between the defined conversions...
10404         // FIXME: this might not be transitive.
10405         assert(L->Conversions.size() == R->Conversions.size());
10406 
10407         int leftBetter = 0;
10408         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10409         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10410           switch (CompareImplicitConversionSequences(S, Loc,
10411                                                      L->Conversions[I],
10412                                                      R->Conversions[I])) {
10413           case ImplicitConversionSequence::Better:
10414             leftBetter++;
10415             break;
10416 
10417           case ImplicitConversionSequence::Worse:
10418             leftBetter--;
10419             break;
10420 
10421           case ImplicitConversionSequence::Indistinguishable:
10422             break;
10423           }
10424         }
10425         if (leftBetter > 0) return true;
10426         if (leftBetter < 0) return false;
10427 
10428       } else if (R->FailureKind == ovl_fail_bad_conversion)
10429         return false;
10430 
10431       if (L->FailureKind == ovl_fail_bad_deduction) {
10432         if (R->FailureKind != ovl_fail_bad_deduction)
10433           return true;
10434 
10435         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10436           return RankDeductionFailure(L->DeductionFailure)
10437                < RankDeductionFailure(R->DeductionFailure);
10438       } else if (R->FailureKind == ovl_fail_bad_deduction)
10439         return false;
10440 
10441       // TODO: others?
10442     }
10443 
10444     // Sort everything else by location.
10445     SourceLocation LLoc = GetLocationForCandidate(L);
10446     SourceLocation RLoc = GetLocationForCandidate(R);
10447 
10448     // Put candidates without locations (e.g. builtins) at the end.
10449     if (LLoc.isInvalid()) return false;
10450     if (RLoc.isInvalid()) return true;
10451 
10452     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10453   }
10454 };
10455 }
10456 
10457 /// CompleteNonViableCandidate - Normally, overload resolution only
10458 /// computes up to the first bad conversion. Produces the FixIt set if
10459 /// possible.
10460 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10461                                        ArrayRef<Expr *> Args) {
10462   assert(!Cand->Viable);
10463 
10464   // Don't do anything on failures other than bad conversion.
10465   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10466 
10467   // We only want the FixIts if all the arguments can be corrected.
10468   bool Unfixable = false;
10469   // Use a implicit copy initialization to check conversion fixes.
10470   Cand->Fix.setConversionChecker(TryCopyInitialization);
10471 
10472   // Attempt to fix the bad conversion.
10473   unsigned ConvCount = Cand->Conversions.size();
10474   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10475        ++ConvIdx) {
10476     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10477     if (Cand->Conversions[ConvIdx].isInitialized() &&
10478         Cand->Conversions[ConvIdx].isBad()) {
10479       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10480       break;
10481     }
10482   }
10483 
10484   // FIXME: this should probably be preserved from the overload
10485   // operation somehow.
10486   bool SuppressUserConversions = false;
10487 
10488   unsigned ConvIdx = 0;
10489   ArrayRef<QualType> ParamTypes;
10490 
10491   if (Cand->IsSurrogate) {
10492     QualType ConvType
10493       = Cand->Surrogate->getConversionType().getNonReferenceType();
10494     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10495       ConvType = ConvPtrType->getPointeeType();
10496     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10497     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10498     ConvIdx = 1;
10499   } else if (Cand->Function) {
10500     ParamTypes =
10501         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10502     if (isa<CXXMethodDecl>(Cand->Function) &&
10503         !isa<CXXConstructorDecl>(Cand->Function)) {
10504       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10505       ConvIdx = 1;
10506     }
10507   } else {
10508     // Builtin operator.
10509     assert(ConvCount <= 3);
10510     ParamTypes = Cand->BuiltinParamTypes;
10511   }
10512 
10513   // Fill in the rest of the conversions.
10514   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10515     if (Cand->Conversions[ConvIdx].isInitialized()) {
10516       // We've already checked this conversion.
10517     } else if (ArgIdx < ParamTypes.size()) {
10518       if (ParamTypes[ArgIdx]->isDependentType())
10519         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10520             Args[ArgIdx]->getType());
10521       else {
10522         Cand->Conversions[ConvIdx] =
10523             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10524                                   SuppressUserConversions,
10525                                   /*InOverloadResolution=*/true,
10526                                   /*AllowObjCWritebackConversion=*/
10527                                   S.getLangOpts().ObjCAutoRefCount);
10528         // Store the FixIt in the candidate if it exists.
10529         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10530           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10531       }
10532     } else
10533       Cand->Conversions[ConvIdx].setEllipsis();
10534   }
10535 }
10536 
10537 /// PrintOverloadCandidates - When overload resolution fails, prints
10538 /// diagnostic messages containing the candidates in the candidate
10539 /// set.
10540 void OverloadCandidateSet::NoteCandidates(
10541     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10542     StringRef Opc, SourceLocation OpLoc,
10543     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10544   // Sort the candidates by viability and position.  Sorting directly would
10545   // be prohibitive, so we make a set of pointers and sort those.
10546   SmallVector<OverloadCandidate*, 32> Cands;
10547   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10548   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10549     if (!Filter(*Cand))
10550       continue;
10551     if (Cand->Viable)
10552       Cands.push_back(Cand);
10553     else if (OCD == OCD_AllCandidates) {
10554       CompleteNonViableCandidate(S, Cand, Args);
10555       if (Cand->Function || Cand->IsSurrogate)
10556         Cands.push_back(Cand);
10557       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10558       // want to list every possible builtin candidate.
10559     }
10560   }
10561 
10562   std::stable_sort(Cands.begin(), Cands.end(),
10563             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10564 
10565   bool ReportedAmbiguousConversions = false;
10566 
10567   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10568   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10569   unsigned CandsShown = 0;
10570   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10571     OverloadCandidate *Cand = *I;
10572 
10573     // Set an arbitrary limit on the number of candidate functions we'll spam
10574     // the user with.  FIXME: This limit should depend on details of the
10575     // candidate list.
10576     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10577       break;
10578     }
10579     ++CandsShown;
10580 
10581     if (Cand->Function)
10582       NoteFunctionCandidate(S, Cand, Args.size(),
10583                             /*TakingCandidateAddress=*/false);
10584     else if (Cand->IsSurrogate)
10585       NoteSurrogateCandidate(S, Cand);
10586     else {
10587       assert(Cand->Viable &&
10588              "Non-viable built-in candidates are not added to Cands.");
10589       // Generally we only see ambiguities including viable builtin
10590       // operators if overload resolution got screwed up by an
10591       // ambiguous user-defined conversion.
10592       //
10593       // FIXME: It's quite possible for different conversions to see
10594       // different ambiguities, though.
10595       if (!ReportedAmbiguousConversions) {
10596         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10597         ReportedAmbiguousConversions = true;
10598       }
10599 
10600       // If this is a viable builtin, print it.
10601       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10602     }
10603   }
10604 
10605   if (I != E)
10606     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10607 }
10608 
10609 static SourceLocation
10610 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10611   return Cand->Specialization ? Cand->Specialization->getLocation()
10612                               : SourceLocation();
10613 }
10614 
10615 namespace {
10616 struct CompareTemplateSpecCandidatesForDisplay {
10617   Sema &S;
10618   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10619 
10620   bool operator()(const TemplateSpecCandidate *L,
10621                   const TemplateSpecCandidate *R) {
10622     // Fast-path this check.
10623     if (L == R)
10624       return false;
10625 
10626     // Assuming that both candidates are not matches...
10627 
10628     // Sort by the ranking of deduction failures.
10629     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10630       return RankDeductionFailure(L->DeductionFailure) <
10631              RankDeductionFailure(R->DeductionFailure);
10632 
10633     // Sort everything else by location.
10634     SourceLocation LLoc = GetLocationForCandidate(L);
10635     SourceLocation RLoc = GetLocationForCandidate(R);
10636 
10637     // Put candidates without locations (e.g. builtins) at the end.
10638     if (LLoc.isInvalid())
10639       return false;
10640     if (RLoc.isInvalid())
10641       return true;
10642 
10643     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10644   }
10645 };
10646 }
10647 
10648 /// Diagnose a template argument deduction failure.
10649 /// We are treating these failures as overload failures due to bad
10650 /// deductions.
10651 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10652                                                  bool ForTakingAddress) {
10653   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10654                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10655 }
10656 
10657 void TemplateSpecCandidateSet::destroyCandidates() {
10658   for (iterator i = begin(), e = end(); i != e; ++i) {
10659     i->DeductionFailure.Destroy();
10660   }
10661 }
10662 
10663 void TemplateSpecCandidateSet::clear() {
10664   destroyCandidates();
10665   Candidates.clear();
10666 }
10667 
10668 /// NoteCandidates - When no template specialization match is found, prints
10669 /// diagnostic messages containing the non-matching specializations that form
10670 /// the candidate set.
10671 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10672 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10673 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10674   // Sort the candidates by position (assuming no candidate is a match).
10675   // Sorting directly would be prohibitive, so we make a set of pointers
10676   // and sort those.
10677   SmallVector<TemplateSpecCandidate *, 32> Cands;
10678   Cands.reserve(size());
10679   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10680     if (Cand->Specialization)
10681       Cands.push_back(Cand);
10682     // Otherwise, this is a non-matching builtin candidate.  We do not,
10683     // in general, want to list every possible builtin candidate.
10684   }
10685 
10686   std::sort(Cands.begin(), Cands.end(),
10687             CompareTemplateSpecCandidatesForDisplay(S));
10688 
10689   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10690   // for generalization purposes (?).
10691   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10692 
10693   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10694   unsigned CandsShown = 0;
10695   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10696     TemplateSpecCandidate *Cand = *I;
10697 
10698     // Set an arbitrary limit on the number of candidates we'll spam
10699     // the user with.  FIXME: This limit should depend on details of the
10700     // candidate list.
10701     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10702       break;
10703     ++CandsShown;
10704 
10705     assert(Cand->Specialization &&
10706            "Non-matching built-in candidates are not added to Cands.");
10707     Cand->NoteDeductionFailure(S, ForTakingAddress);
10708   }
10709 
10710   if (I != E)
10711     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10712 }
10713 
10714 // [PossiblyAFunctionType]  -->   [Return]
10715 // NonFunctionType --> NonFunctionType
10716 // R (A) --> R(A)
10717 // R (*)(A) --> R (A)
10718 // R (&)(A) --> R (A)
10719 // R (S::*)(A) --> R (A)
10720 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10721   QualType Ret = PossiblyAFunctionType;
10722   if (const PointerType *ToTypePtr =
10723     PossiblyAFunctionType->getAs<PointerType>())
10724     Ret = ToTypePtr->getPointeeType();
10725   else if (const ReferenceType *ToTypeRef =
10726     PossiblyAFunctionType->getAs<ReferenceType>())
10727     Ret = ToTypeRef->getPointeeType();
10728   else if (const MemberPointerType *MemTypePtr =
10729     PossiblyAFunctionType->getAs<MemberPointerType>())
10730     Ret = MemTypePtr->getPointeeType();
10731   Ret =
10732     Context.getCanonicalType(Ret).getUnqualifiedType();
10733   return Ret;
10734 }
10735 
10736 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10737                                  bool Complain = true) {
10738   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10739       S.DeduceReturnType(FD, Loc, Complain))
10740     return true;
10741 
10742   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10743   if (S.getLangOpts().CPlusPlus17 &&
10744       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10745       !S.ResolveExceptionSpec(Loc, FPT))
10746     return true;
10747 
10748   return false;
10749 }
10750 
10751 namespace {
10752 // A helper class to help with address of function resolution
10753 // - allows us to avoid passing around all those ugly parameters
10754 class AddressOfFunctionResolver {
10755   Sema& S;
10756   Expr* SourceExpr;
10757   const QualType& TargetType;
10758   QualType TargetFunctionType; // Extracted function type from target type
10759 
10760   bool Complain;
10761   //DeclAccessPair& ResultFunctionAccessPair;
10762   ASTContext& Context;
10763 
10764   bool TargetTypeIsNonStaticMemberFunction;
10765   bool FoundNonTemplateFunction;
10766   bool StaticMemberFunctionFromBoundPointer;
10767   bool HasComplained;
10768 
10769   OverloadExpr::FindResult OvlExprInfo;
10770   OverloadExpr *OvlExpr;
10771   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10772   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10773   TemplateSpecCandidateSet FailedCandidates;
10774 
10775 public:
10776   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10777                             const QualType &TargetType, bool Complain)
10778       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10779         Complain(Complain), Context(S.getASTContext()),
10780         TargetTypeIsNonStaticMemberFunction(
10781             !!TargetType->getAs<MemberPointerType>()),
10782         FoundNonTemplateFunction(false),
10783         StaticMemberFunctionFromBoundPointer(false),
10784         HasComplained(false),
10785         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10786         OvlExpr(OvlExprInfo.Expression),
10787         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10788     ExtractUnqualifiedFunctionTypeFromTargetType();
10789 
10790     if (TargetFunctionType->isFunctionType()) {
10791       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10792         if (!UME->isImplicitAccess() &&
10793             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10794           StaticMemberFunctionFromBoundPointer = true;
10795     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10796       DeclAccessPair dap;
10797       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10798               OvlExpr, false, &dap)) {
10799         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10800           if (!Method->isStatic()) {
10801             // If the target type is a non-function type and the function found
10802             // is a non-static member function, pretend as if that was the
10803             // target, it's the only possible type to end up with.
10804             TargetTypeIsNonStaticMemberFunction = true;
10805 
10806             // And skip adding the function if its not in the proper form.
10807             // We'll diagnose this due to an empty set of functions.
10808             if (!OvlExprInfo.HasFormOfMemberPointer)
10809               return;
10810           }
10811 
10812         Matches.push_back(std::make_pair(dap, Fn));
10813       }
10814       return;
10815     }
10816 
10817     if (OvlExpr->hasExplicitTemplateArgs())
10818       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10819 
10820     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10821       // C++ [over.over]p4:
10822       //   If more than one function is selected, [...]
10823       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10824         if (FoundNonTemplateFunction)
10825           EliminateAllTemplateMatches();
10826         else
10827           EliminateAllExceptMostSpecializedTemplate();
10828       }
10829     }
10830 
10831     if (S.getLangOpts().CUDA && Matches.size() > 1)
10832       EliminateSuboptimalCudaMatches();
10833   }
10834 
10835   bool hasComplained() const { return HasComplained; }
10836 
10837 private:
10838   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10839     QualType Discard;
10840     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10841            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10842   }
10843 
10844   /// \return true if A is considered a better overload candidate for the
10845   /// desired type than B.
10846   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10847     // If A doesn't have exactly the correct type, we don't want to classify it
10848     // as "better" than anything else. This way, the user is required to
10849     // disambiguate for us if there are multiple candidates and no exact match.
10850     return candidateHasExactlyCorrectType(A) &&
10851            (!candidateHasExactlyCorrectType(B) ||
10852             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10853   }
10854 
10855   /// \return true if we were able to eliminate all but one overload candidate,
10856   /// false otherwise.
10857   bool eliminiateSuboptimalOverloadCandidates() {
10858     // Same algorithm as overload resolution -- one pass to pick the "best",
10859     // another pass to be sure that nothing is better than the best.
10860     auto Best = Matches.begin();
10861     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10862       if (isBetterCandidate(I->second, Best->second))
10863         Best = I;
10864 
10865     const FunctionDecl *BestFn = Best->second;
10866     auto IsBestOrInferiorToBest = [this, BestFn](
10867         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10868       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10869     };
10870 
10871     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10872     // option, so we can potentially give the user a better error
10873     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10874       return false;
10875     Matches[0] = *Best;
10876     Matches.resize(1);
10877     return true;
10878   }
10879 
10880   bool isTargetTypeAFunction() const {
10881     return TargetFunctionType->isFunctionType();
10882   }
10883 
10884   // [ToType]     [Return]
10885 
10886   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10887   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10888   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10889   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10890     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10891   }
10892 
10893   // return true if any matching specializations were found
10894   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10895                                    const DeclAccessPair& CurAccessFunPair) {
10896     if (CXXMethodDecl *Method
10897               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10898       // Skip non-static function templates when converting to pointer, and
10899       // static when converting to member pointer.
10900       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10901         return false;
10902     }
10903     else if (TargetTypeIsNonStaticMemberFunction)
10904       return false;
10905 
10906     // C++ [over.over]p2:
10907     //   If the name is a function template, template argument deduction is
10908     //   done (14.8.2.2), and if the argument deduction succeeds, the
10909     //   resulting template argument list is used to generate a single
10910     //   function template specialization, which is added to the set of
10911     //   overloaded functions considered.
10912     FunctionDecl *Specialization = nullptr;
10913     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10914     if (Sema::TemplateDeductionResult Result
10915           = S.DeduceTemplateArguments(FunctionTemplate,
10916                                       &OvlExplicitTemplateArgs,
10917                                       TargetFunctionType, Specialization,
10918                                       Info, /*IsAddressOfFunction*/true)) {
10919       // Make a note of the failed deduction for diagnostics.
10920       FailedCandidates.addCandidate()
10921           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10922                MakeDeductionFailureInfo(Context, Result, Info));
10923       return false;
10924     }
10925 
10926     // Template argument deduction ensures that we have an exact match or
10927     // compatible pointer-to-function arguments that would be adjusted by ICS.
10928     // This function template specicalization works.
10929     assert(S.isSameOrCompatibleFunctionType(
10930               Context.getCanonicalType(Specialization->getType()),
10931               Context.getCanonicalType(TargetFunctionType)));
10932 
10933     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10934       return false;
10935 
10936     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10937     return true;
10938   }
10939 
10940   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10941                                       const DeclAccessPair& CurAccessFunPair) {
10942     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10943       // Skip non-static functions when converting to pointer, and static
10944       // when converting to member pointer.
10945       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10946         return false;
10947     }
10948     else if (TargetTypeIsNonStaticMemberFunction)
10949       return false;
10950 
10951     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10952       if (S.getLangOpts().CUDA)
10953         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10954           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10955             return false;
10956       if (FunDecl->isMultiVersion()) {
10957         const auto *TA = FunDecl->getAttr<TargetAttr>();
10958         assert(TA && "Multiversioned functions require a target attribute");
10959         if (!TA->isDefaultVersion())
10960           return false;
10961       }
10962 
10963       // If any candidate has a placeholder return type, trigger its deduction
10964       // now.
10965       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10966                                Complain)) {
10967         HasComplained |= Complain;
10968         return false;
10969       }
10970 
10971       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10972         return false;
10973 
10974       // If we're in C, we need to support types that aren't exactly identical.
10975       if (!S.getLangOpts().CPlusPlus ||
10976           candidateHasExactlyCorrectType(FunDecl)) {
10977         Matches.push_back(std::make_pair(
10978             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10979         FoundNonTemplateFunction = true;
10980         return true;
10981       }
10982     }
10983 
10984     return false;
10985   }
10986 
10987   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10988     bool Ret = false;
10989 
10990     // If the overload expression doesn't have the form of a pointer to
10991     // member, don't try to convert it to a pointer-to-member type.
10992     if (IsInvalidFormOfPointerToMemberFunction())
10993       return false;
10994 
10995     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10996                                E = OvlExpr->decls_end();
10997          I != E; ++I) {
10998       // Look through any using declarations to find the underlying function.
10999       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11000 
11001       // C++ [over.over]p3:
11002       //   Non-member functions and static member functions match
11003       //   targets of type "pointer-to-function" or "reference-to-function."
11004       //   Nonstatic member functions match targets of
11005       //   type "pointer-to-member-function."
11006       // Note that according to DR 247, the containing class does not matter.
11007       if (FunctionTemplateDecl *FunctionTemplate
11008                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11009         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11010           Ret = true;
11011       }
11012       // If we have explicit template arguments supplied, skip non-templates.
11013       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11014                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11015         Ret = true;
11016     }
11017     assert(Ret || Matches.empty());
11018     return Ret;
11019   }
11020 
11021   void EliminateAllExceptMostSpecializedTemplate() {
11022     //   [...] and any given function template specialization F1 is
11023     //   eliminated if the set contains a second function template
11024     //   specialization whose function template is more specialized
11025     //   than the function template of F1 according to the partial
11026     //   ordering rules of 14.5.5.2.
11027 
11028     // The algorithm specified above is quadratic. We instead use a
11029     // two-pass algorithm (similar to the one used to identify the
11030     // best viable function in an overload set) that identifies the
11031     // best function template (if it exists).
11032 
11033     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11034     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11035       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11036 
11037     // TODO: It looks like FailedCandidates does not serve much purpose
11038     // here, since the no_viable diagnostic has index 0.
11039     UnresolvedSetIterator Result = S.getMostSpecialized(
11040         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11041         SourceExpr->getLocStart(), S.PDiag(),
11042         S.PDiag(diag::err_addr_ovl_ambiguous)
11043           << Matches[0].second->getDeclName(),
11044         S.PDiag(diag::note_ovl_candidate)
11045           << (unsigned)oc_function_template,
11046         Complain, TargetFunctionType);
11047 
11048     if (Result != MatchesCopy.end()) {
11049       // Make it the first and only element
11050       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11051       Matches[0].second = cast<FunctionDecl>(*Result);
11052       Matches.resize(1);
11053     } else
11054       HasComplained |= Complain;
11055   }
11056 
11057   void EliminateAllTemplateMatches() {
11058     //   [...] any function template specializations in the set are
11059     //   eliminated if the set also contains a non-template function, [...]
11060     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11061       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11062         ++I;
11063       else {
11064         Matches[I] = Matches[--N];
11065         Matches.resize(N);
11066       }
11067     }
11068   }
11069 
11070   void EliminateSuboptimalCudaMatches() {
11071     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11072   }
11073 
11074 public:
11075   void ComplainNoMatchesFound() const {
11076     assert(Matches.empty());
11077     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11078         << OvlExpr->getName() << TargetFunctionType
11079         << OvlExpr->getSourceRange();
11080     if (FailedCandidates.empty())
11081       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11082                                   /*TakingAddress=*/true);
11083     else {
11084       // We have some deduction failure messages. Use them to diagnose
11085       // the function templates, and diagnose the non-template candidates
11086       // normally.
11087       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11088                                  IEnd = OvlExpr->decls_end();
11089            I != IEnd; ++I)
11090         if (FunctionDecl *Fun =
11091                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11092           if (!functionHasPassObjectSizeParams(Fun))
11093             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11094                                     /*TakingAddress=*/true);
11095       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11096     }
11097   }
11098 
11099   bool IsInvalidFormOfPointerToMemberFunction() const {
11100     return TargetTypeIsNonStaticMemberFunction &&
11101       !OvlExprInfo.HasFormOfMemberPointer;
11102   }
11103 
11104   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11105       // TODO: Should we condition this on whether any functions might
11106       // have matched, or is it more appropriate to do that in callers?
11107       // TODO: a fixit wouldn't hurt.
11108       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11109         << TargetType << OvlExpr->getSourceRange();
11110   }
11111 
11112   bool IsStaticMemberFunctionFromBoundPointer() const {
11113     return StaticMemberFunctionFromBoundPointer;
11114   }
11115 
11116   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11117     S.Diag(OvlExpr->getLocStart(),
11118            diag::err_invalid_form_pointer_member_function)
11119       << OvlExpr->getSourceRange();
11120   }
11121 
11122   void ComplainOfInvalidConversion() const {
11123     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11124       << OvlExpr->getName() << TargetType;
11125   }
11126 
11127   void ComplainMultipleMatchesFound() const {
11128     assert(Matches.size() > 1);
11129     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11130       << OvlExpr->getName()
11131       << OvlExpr->getSourceRange();
11132     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11133                                 /*TakingAddress=*/true);
11134   }
11135 
11136   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11137 
11138   int getNumMatches() const { return Matches.size(); }
11139 
11140   FunctionDecl* getMatchingFunctionDecl() const {
11141     if (Matches.size() != 1) return nullptr;
11142     return Matches[0].second;
11143   }
11144 
11145   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11146     if (Matches.size() != 1) return nullptr;
11147     return &Matches[0].first;
11148   }
11149 };
11150 }
11151 
11152 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11153 /// an overloaded function (C++ [over.over]), where @p From is an
11154 /// expression with overloaded function type and @p ToType is the type
11155 /// we're trying to resolve to. For example:
11156 ///
11157 /// @code
11158 /// int f(double);
11159 /// int f(int);
11160 ///
11161 /// int (*pfd)(double) = f; // selects f(double)
11162 /// @endcode
11163 ///
11164 /// This routine returns the resulting FunctionDecl if it could be
11165 /// resolved, and NULL otherwise. When @p Complain is true, this
11166 /// routine will emit diagnostics if there is an error.
11167 FunctionDecl *
11168 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11169                                          QualType TargetType,
11170                                          bool Complain,
11171                                          DeclAccessPair &FoundResult,
11172                                          bool *pHadMultipleCandidates) {
11173   assert(AddressOfExpr->getType() == Context.OverloadTy);
11174 
11175   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11176                                      Complain);
11177   int NumMatches = Resolver.getNumMatches();
11178   FunctionDecl *Fn = nullptr;
11179   bool ShouldComplain = Complain && !Resolver.hasComplained();
11180   if (NumMatches == 0 && ShouldComplain) {
11181     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11182       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11183     else
11184       Resolver.ComplainNoMatchesFound();
11185   }
11186   else if (NumMatches > 1 && ShouldComplain)
11187     Resolver.ComplainMultipleMatchesFound();
11188   else if (NumMatches == 1) {
11189     Fn = Resolver.getMatchingFunctionDecl();
11190     assert(Fn);
11191     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11192       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11193     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11194     if (Complain) {
11195       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11196         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11197       else
11198         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11199     }
11200   }
11201 
11202   if (pHadMultipleCandidates)
11203     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11204   return Fn;
11205 }
11206 
11207 /// \brief Given an expression that refers to an overloaded function, try to
11208 /// resolve that function to a single function that can have its address taken.
11209 /// This will modify `Pair` iff it returns non-null.
11210 ///
11211 /// This routine can only realistically succeed if all but one candidates in the
11212 /// overload set for SrcExpr cannot have their addresses taken.
11213 FunctionDecl *
11214 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11215                                                   DeclAccessPair &Pair) {
11216   OverloadExpr::FindResult R = OverloadExpr::find(E);
11217   OverloadExpr *Ovl = R.Expression;
11218   FunctionDecl *Result = nullptr;
11219   DeclAccessPair DAP;
11220   // Don't use the AddressOfResolver because we're specifically looking for
11221   // cases where we have one overload candidate that lacks
11222   // enable_if/pass_object_size/...
11223   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11224     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11225     if (!FD)
11226       return nullptr;
11227 
11228     if (!checkAddressOfFunctionIsAvailable(FD))
11229       continue;
11230 
11231     // We have more than one result; quit.
11232     if (Result)
11233       return nullptr;
11234     DAP = I.getPair();
11235     Result = FD;
11236   }
11237 
11238   if (Result)
11239     Pair = DAP;
11240   return Result;
11241 }
11242 
11243 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11244 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11245 /// will perform access checks, diagnose the use of the resultant decl, and, if
11246 /// requested, potentially perform a function-to-pointer decay.
11247 ///
11248 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11249 /// Otherwise, returns true. This may emit diagnostics and return true.
11250 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11251     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11252   Expr *E = SrcExpr.get();
11253   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11254 
11255   DeclAccessPair DAP;
11256   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11257   if (!Found)
11258     return false;
11259 
11260   // Emitting multiple diagnostics for a function that is both inaccessible and
11261   // unavailable is consistent with our behavior elsewhere. So, always check
11262   // for both.
11263   DiagnoseUseOfDecl(Found, E->getExprLoc());
11264   CheckAddressOfMemberAccess(E, DAP);
11265   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11266   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11267     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11268   else
11269     SrcExpr = Fixed;
11270   return true;
11271 }
11272 
11273 /// \brief Given an expression that refers to an overloaded function, try to
11274 /// resolve that overloaded function expression down to a single function.
11275 ///
11276 /// This routine can only resolve template-ids that refer to a single function
11277 /// template, where that template-id refers to a single template whose template
11278 /// arguments are either provided by the template-id or have defaults,
11279 /// as described in C++0x [temp.arg.explicit]p3.
11280 ///
11281 /// If no template-ids are found, no diagnostics are emitted and NULL is
11282 /// returned.
11283 FunctionDecl *
11284 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11285                                                   bool Complain,
11286                                                   DeclAccessPair *FoundResult) {
11287   // C++ [over.over]p1:
11288   //   [...] [Note: any redundant set of parentheses surrounding the
11289   //   overloaded function name is ignored (5.1). ]
11290   // C++ [over.over]p1:
11291   //   [...] The overloaded function name can be preceded by the &
11292   //   operator.
11293 
11294   // If we didn't actually find any template-ids, we're done.
11295   if (!ovl->hasExplicitTemplateArgs())
11296     return nullptr;
11297 
11298   TemplateArgumentListInfo ExplicitTemplateArgs;
11299   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11300   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11301 
11302   // Look through all of the overloaded functions, searching for one
11303   // whose type matches exactly.
11304   FunctionDecl *Matched = nullptr;
11305   for (UnresolvedSetIterator I = ovl->decls_begin(),
11306          E = ovl->decls_end(); I != E; ++I) {
11307     // C++0x [temp.arg.explicit]p3:
11308     //   [...] In contexts where deduction is done and fails, or in contexts
11309     //   where deduction is not done, if a template argument list is
11310     //   specified and it, along with any default template arguments,
11311     //   identifies a single function template specialization, then the
11312     //   template-id is an lvalue for the function template specialization.
11313     FunctionTemplateDecl *FunctionTemplate
11314       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11315 
11316     // C++ [over.over]p2:
11317     //   If the name is a function template, template argument deduction is
11318     //   done (14.8.2.2), and if the argument deduction succeeds, the
11319     //   resulting template argument list is used to generate a single
11320     //   function template specialization, which is added to the set of
11321     //   overloaded functions considered.
11322     FunctionDecl *Specialization = nullptr;
11323     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11324     if (TemplateDeductionResult Result
11325           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11326                                     Specialization, Info,
11327                                     /*IsAddressOfFunction*/true)) {
11328       // Make a note of the failed deduction for diagnostics.
11329       // TODO: Actually use the failed-deduction info?
11330       FailedCandidates.addCandidate()
11331           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11332                MakeDeductionFailureInfo(Context, Result, Info));
11333       continue;
11334     }
11335 
11336     assert(Specialization && "no specialization and no error?");
11337 
11338     // Multiple matches; we can't resolve to a single declaration.
11339     if (Matched) {
11340       if (Complain) {
11341         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11342           << ovl->getName();
11343         NoteAllOverloadCandidates(ovl);
11344       }
11345       return nullptr;
11346     }
11347 
11348     Matched = Specialization;
11349     if (FoundResult) *FoundResult = I.getPair();
11350   }
11351 
11352   if (Matched &&
11353       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11354     return nullptr;
11355 
11356   return Matched;
11357 }
11358 
11359 // Resolve and fix an overloaded expression that can be resolved
11360 // because it identifies a single function template specialization.
11361 //
11362 // Last three arguments should only be supplied if Complain = true
11363 //
11364 // Return true if it was logically possible to so resolve the
11365 // expression, regardless of whether or not it succeeded.  Always
11366 // returns true if 'complain' is set.
11367 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11368                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11369                       bool complain, SourceRange OpRangeForComplaining,
11370                                            QualType DestTypeForComplaining,
11371                                             unsigned DiagIDForComplaining) {
11372   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11373 
11374   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11375 
11376   DeclAccessPair found;
11377   ExprResult SingleFunctionExpression;
11378   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11379                            ovl.Expression, /*complain*/ false, &found)) {
11380     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11381       SrcExpr = ExprError();
11382       return true;
11383     }
11384 
11385     // It is only correct to resolve to an instance method if we're
11386     // resolving a form that's permitted to be a pointer to member.
11387     // Otherwise we'll end up making a bound member expression, which
11388     // is illegal in all the contexts we resolve like this.
11389     if (!ovl.HasFormOfMemberPointer &&
11390         isa<CXXMethodDecl>(fn) &&
11391         cast<CXXMethodDecl>(fn)->isInstance()) {
11392       if (!complain) return false;
11393 
11394       Diag(ovl.Expression->getExprLoc(),
11395            diag::err_bound_member_function)
11396         << 0 << ovl.Expression->getSourceRange();
11397 
11398       // TODO: I believe we only end up here if there's a mix of
11399       // static and non-static candidates (otherwise the expression
11400       // would have 'bound member' type, not 'overload' type).
11401       // Ideally we would note which candidate was chosen and why
11402       // the static candidates were rejected.
11403       SrcExpr = ExprError();
11404       return true;
11405     }
11406 
11407     // Fix the expression to refer to 'fn'.
11408     SingleFunctionExpression =
11409         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11410 
11411     // If desired, do function-to-pointer decay.
11412     if (doFunctionPointerConverion) {
11413       SingleFunctionExpression =
11414         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11415       if (SingleFunctionExpression.isInvalid()) {
11416         SrcExpr = ExprError();
11417         return true;
11418       }
11419     }
11420   }
11421 
11422   if (!SingleFunctionExpression.isUsable()) {
11423     if (complain) {
11424       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11425         << ovl.Expression->getName()
11426         << DestTypeForComplaining
11427         << OpRangeForComplaining
11428         << ovl.Expression->getQualifierLoc().getSourceRange();
11429       NoteAllOverloadCandidates(SrcExpr.get());
11430 
11431       SrcExpr = ExprError();
11432       return true;
11433     }
11434 
11435     return false;
11436   }
11437 
11438   SrcExpr = SingleFunctionExpression;
11439   return true;
11440 }
11441 
11442 /// \brief Add a single candidate to the overload set.
11443 static void AddOverloadedCallCandidate(Sema &S,
11444                                        DeclAccessPair FoundDecl,
11445                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11446                                        ArrayRef<Expr *> Args,
11447                                        OverloadCandidateSet &CandidateSet,
11448                                        bool PartialOverloading,
11449                                        bool KnownValid) {
11450   NamedDecl *Callee = FoundDecl.getDecl();
11451   if (isa<UsingShadowDecl>(Callee))
11452     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11453 
11454   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11455     if (ExplicitTemplateArgs) {
11456       assert(!KnownValid && "Explicit template arguments?");
11457       return;
11458     }
11459     // Prevent ill-formed function decls to be added as overload candidates.
11460     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11461       return;
11462 
11463     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11464                            /*SuppressUsedConversions=*/false,
11465                            PartialOverloading);
11466     return;
11467   }
11468 
11469   if (FunctionTemplateDecl *FuncTemplate
11470       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11471     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11472                                    ExplicitTemplateArgs, Args, CandidateSet,
11473                                    /*SuppressUsedConversions=*/false,
11474                                    PartialOverloading);
11475     return;
11476   }
11477 
11478   assert(!KnownValid && "unhandled case in overloaded call candidate");
11479 }
11480 
11481 /// \brief Add the overload candidates named by callee and/or found by argument
11482 /// dependent lookup to the given overload set.
11483 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11484                                        ArrayRef<Expr *> Args,
11485                                        OverloadCandidateSet &CandidateSet,
11486                                        bool PartialOverloading) {
11487 
11488 #ifndef NDEBUG
11489   // Verify that ArgumentDependentLookup is consistent with the rules
11490   // in C++0x [basic.lookup.argdep]p3:
11491   //
11492   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11493   //   and let Y be the lookup set produced by argument dependent
11494   //   lookup (defined as follows). If X contains
11495   //
11496   //     -- a declaration of a class member, or
11497   //
11498   //     -- a block-scope function declaration that is not a
11499   //        using-declaration, or
11500   //
11501   //     -- a declaration that is neither a function or a function
11502   //        template
11503   //
11504   //   then Y is empty.
11505 
11506   if (ULE->requiresADL()) {
11507     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11508            E = ULE->decls_end(); I != E; ++I) {
11509       assert(!(*I)->getDeclContext()->isRecord());
11510       assert(isa<UsingShadowDecl>(*I) ||
11511              !(*I)->getDeclContext()->isFunctionOrMethod());
11512       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11513     }
11514   }
11515 #endif
11516 
11517   // It would be nice to avoid this copy.
11518   TemplateArgumentListInfo TABuffer;
11519   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11520   if (ULE->hasExplicitTemplateArgs()) {
11521     ULE->copyTemplateArgumentsInto(TABuffer);
11522     ExplicitTemplateArgs = &TABuffer;
11523   }
11524 
11525   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11526          E = ULE->decls_end(); I != E; ++I)
11527     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11528                                CandidateSet, PartialOverloading,
11529                                /*KnownValid*/ true);
11530 
11531   if (ULE->requiresADL())
11532     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11533                                          Args, ExplicitTemplateArgs,
11534                                          CandidateSet, PartialOverloading);
11535 }
11536 
11537 /// Determine whether a declaration with the specified name could be moved into
11538 /// a different namespace.
11539 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11540   switch (Name.getCXXOverloadedOperator()) {
11541   case OO_New: case OO_Array_New:
11542   case OO_Delete: case OO_Array_Delete:
11543     return false;
11544 
11545   default:
11546     return true;
11547   }
11548 }
11549 
11550 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11551 /// template, where the non-dependent name was declared after the template
11552 /// was defined. This is common in code written for a compilers which do not
11553 /// correctly implement two-stage name lookup.
11554 ///
11555 /// Returns true if a viable candidate was found and a diagnostic was issued.
11556 static bool
11557 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11558                        const CXXScopeSpec &SS, LookupResult &R,
11559                        OverloadCandidateSet::CandidateSetKind CSK,
11560                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11561                        ArrayRef<Expr *> Args,
11562                        bool *DoDiagnoseEmptyLookup = nullptr) {
11563   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11564     return false;
11565 
11566   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11567     if (DC->isTransparentContext())
11568       continue;
11569 
11570     SemaRef.LookupQualifiedName(R, DC);
11571 
11572     if (!R.empty()) {
11573       R.suppressDiagnostics();
11574 
11575       if (isa<CXXRecordDecl>(DC)) {
11576         // Don't diagnose names we find in classes; we get much better
11577         // diagnostics for these from DiagnoseEmptyLookup.
11578         R.clear();
11579         if (DoDiagnoseEmptyLookup)
11580           *DoDiagnoseEmptyLookup = true;
11581         return false;
11582       }
11583 
11584       OverloadCandidateSet Candidates(FnLoc, CSK);
11585       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11586         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11587                                    ExplicitTemplateArgs, Args,
11588                                    Candidates, false, /*KnownValid*/ false);
11589 
11590       OverloadCandidateSet::iterator Best;
11591       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11592         // No viable functions. Don't bother the user with notes for functions
11593         // which don't work and shouldn't be found anyway.
11594         R.clear();
11595         return false;
11596       }
11597 
11598       // Find the namespaces where ADL would have looked, and suggest
11599       // declaring the function there instead.
11600       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11601       Sema::AssociatedClassSet AssociatedClasses;
11602       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11603                                                  AssociatedNamespaces,
11604                                                  AssociatedClasses);
11605       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11606       if (canBeDeclaredInNamespace(R.getLookupName())) {
11607         DeclContext *Std = SemaRef.getStdNamespace();
11608         for (Sema::AssociatedNamespaceSet::iterator
11609                it = AssociatedNamespaces.begin(),
11610                end = AssociatedNamespaces.end(); it != end; ++it) {
11611           // Never suggest declaring a function within namespace 'std'.
11612           if (Std && Std->Encloses(*it))
11613             continue;
11614 
11615           // Never suggest declaring a function within a namespace with a
11616           // reserved name, like __gnu_cxx.
11617           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11618           if (NS &&
11619               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11620             continue;
11621 
11622           SuggestedNamespaces.insert(*it);
11623         }
11624       }
11625 
11626       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11627         << R.getLookupName();
11628       if (SuggestedNamespaces.empty()) {
11629         SemaRef.Diag(Best->Function->getLocation(),
11630                      diag::note_not_found_by_two_phase_lookup)
11631           << R.getLookupName() << 0;
11632       } else if (SuggestedNamespaces.size() == 1) {
11633         SemaRef.Diag(Best->Function->getLocation(),
11634                      diag::note_not_found_by_two_phase_lookup)
11635           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11636       } else {
11637         // FIXME: It would be useful to list the associated namespaces here,
11638         // but the diagnostics infrastructure doesn't provide a way to produce
11639         // a localized representation of a list of items.
11640         SemaRef.Diag(Best->Function->getLocation(),
11641                      diag::note_not_found_by_two_phase_lookup)
11642           << R.getLookupName() << 2;
11643       }
11644 
11645       // Try to recover by calling this function.
11646       return true;
11647     }
11648 
11649     R.clear();
11650   }
11651 
11652   return false;
11653 }
11654 
11655 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11656 /// template, where the non-dependent operator was declared after the template
11657 /// was defined.
11658 ///
11659 /// Returns true if a viable candidate was found and a diagnostic was issued.
11660 static bool
11661 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11662                                SourceLocation OpLoc,
11663                                ArrayRef<Expr *> Args) {
11664   DeclarationName OpName =
11665     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11666   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11667   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11668                                 OverloadCandidateSet::CSK_Operator,
11669                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11670 }
11671 
11672 namespace {
11673 class BuildRecoveryCallExprRAII {
11674   Sema &SemaRef;
11675 public:
11676   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11677     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11678     SemaRef.IsBuildingRecoveryCallExpr = true;
11679   }
11680 
11681   ~BuildRecoveryCallExprRAII() {
11682     SemaRef.IsBuildingRecoveryCallExpr = false;
11683   }
11684 };
11685 
11686 }
11687 
11688 static std::unique_ptr<CorrectionCandidateCallback>
11689 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11690               bool HasTemplateArgs, bool AllowTypoCorrection) {
11691   if (!AllowTypoCorrection)
11692     return llvm::make_unique<NoTypoCorrectionCCC>();
11693   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11694                                                   HasTemplateArgs, ME);
11695 }
11696 
11697 /// Attempts to recover from a call where no functions were found.
11698 ///
11699 /// Returns true if new candidates were found.
11700 static ExprResult
11701 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11702                       UnresolvedLookupExpr *ULE,
11703                       SourceLocation LParenLoc,
11704                       MutableArrayRef<Expr *> Args,
11705                       SourceLocation RParenLoc,
11706                       bool EmptyLookup, bool AllowTypoCorrection) {
11707   // Do not try to recover if it is already building a recovery call.
11708   // This stops infinite loops for template instantiations like
11709   //
11710   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11711   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11712   //
11713   if (SemaRef.IsBuildingRecoveryCallExpr)
11714     return ExprError();
11715   BuildRecoveryCallExprRAII RCE(SemaRef);
11716 
11717   CXXScopeSpec SS;
11718   SS.Adopt(ULE->getQualifierLoc());
11719   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11720 
11721   TemplateArgumentListInfo TABuffer;
11722   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11723   if (ULE->hasExplicitTemplateArgs()) {
11724     ULE->copyTemplateArgumentsInto(TABuffer);
11725     ExplicitTemplateArgs = &TABuffer;
11726   }
11727 
11728   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11729                  Sema::LookupOrdinaryName);
11730   bool DoDiagnoseEmptyLookup = EmptyLookup;
11731   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11732                               OverloadCandidateSet::CSK_Normal,
11733                               ExplicitTemplateArgs, Args,
11734                               &DoDiagnoseEmptyLookup) &&
11735     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11736         S, SS, R,
11737         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11738                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11739         ExplicitTemplateArgs, Args)))
11740     return ExprError();
11741 
11742   assert(!R.empty() && "lookup results empty despite recovery");
11743 
11744   // If recovery created an ambiguity, just bail out.
11745   if (R.isAmbiguous()) {
11746     R.suppressDiagnostics();
11747     return ExprError();
11748   }
11749 
11750   // Build an implicit member call if appropriate.  Just drop the
11751   // casts and such from the call, we don't really care.
11752   ExprResult NewFn = ExprError();
11753   if ((*R.begin())->isCXXClassMember())
11754     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11755                                                     ExplicitTemplateArgs, S);
11756   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11757     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11758                                         ExplicitTemplateArgs);
11759   else
11760     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11761 
11762   if (NewFn.isInvalid())
11763     return ExprError();
11764 
11765   // This shouldn't cause an infinite loop because we're giving it
11766   // an expression with viable lookup results, which should never
11767   // end up here.
11768   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11769                                MultiExprArg(Args.data(), Args.size()),
11770                                RParenLoc);
11771 }
11772 
11773 /// \brief Constructs and populates an OverloadedCandidateSet from
11774 /// the given function.
11775 /// \returns true when an the ExprResult output parameter has been set.
11776 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11777                                   UnresolvedLookupExpr *ULE,
11778                                   MultiExprArg Args,
11779                                   SourceLocation RParenLoc,
11780                                   OverloadCandidateSet *CandidateSet,
11781                                   ExprResult *Result) {
11782 #ifndef NDEBUG
11783   if (ULE->requiresADL()) {
11784     // To do ADL, we must have found an unqualified name.
11785     assert(!ULE->getQualifier() && "qualified name with ADL");
11786 
11787     // We don't perform ADL for implicit declarations of builtins.
11788     // Verify that this was correctly set up.
11789     FunctionDecl *F;
11790     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11791         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11792         F->getBuiltinID() && F->isImplicit())
11793       llvm_unreachable("performing ADL for builtin");
11794 
11795     // We don't perform ADL in C.
11796     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11797   }
11798 #endif
11799 
11800   UnbridgedCastsSet UnbridgedCasts;
11801   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11802     *Result = ExprError();
11803     return true;
11804   }
11805 
11806   // Add the functions denoted by the callee to the set of candidate
11807   // functions, including those from argument-dependent lookup.
11808   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11809 
11810   if (getLangOpts().MSVCCompat &&
11811       CurContext->isDependentContext() && !isSFINAEContext() &&
11812       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11813 
11814     OverloadCandidateSet::iterator Best;
11815     if (CandidateSet->empty() ||
11816         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11817             OR_No_Viable_Function) {
11818       // In Microsoft mode, if we are inside a template class member function then
11819       // create a type dependent CallExpr. The goal is to postpone name lookup
11820       // to instantiation time to be able to search into type dependent base
11821       // classes.
11822       CallExpr *CE = new (Context) CallExpr(
11823           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11824       CE->setTypeDependent(true);
11825       CE->setValueDependent(true);
11826       CE->setInstantiationDependent(true);
11827       *Result = CE;
11828       return true;
11829     }
11830   }
11831 
11832   if (CandidateSet->empty())
11833     return false;
11834 
11835   UnbridgedCasts.restore();
11836   return false;
11837 }
11838 
11839 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11840 /// the completed call expression. If overload resolution fails, emits
11841 /// diagnostics and returns ExprError()
11842 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11843                                            UnresolvedLookupExpr *ULE,
11844                                            SourceLocation LParenLoc,
11845                                            MultiExprArg Args,
11846                                            SourceLocation RParenLoc,
11847                                            Expr *ExecConfig,
11848                                            OverloadCandidateSet *CandidateSet,
11849                                            OverloadCandidateSet::iterator *Best,
11850                                            OverloadingResult OverloadResult,
11851                                            bool AllowTypoCorrection) {
11852   if (CandidateSet->empty())
11853     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11854                                  RParenLoc, /*EmptyLookup=*/true,
11855                                  AllowTypoCorrection);
11856 
11857   switch (OverloadResult) {
11858   case OR_Success: {
11859     FunctionDecl *FDecl = (*Best)->Function;
11860     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11861     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11862       return ExprError();
11863     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11864     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11865                                          ExecConfig);
11866   }
11867 
11868   case OR_No_Viable_Function: {
11869     // Try to recover by looking for viable functions which the user might
11870     // have meant to call.
11871     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11872                                                 Args, RParenLoc,
11873                                                 /*EmptyLookup=*/false,
11874                                                 AllowTypoCorrection);
11875     if (!Recovery.isInvalid())
11876       return Recovery;
11877 
11878     // If the user passes in a function that we can't take the address of, we
11879     // generally end up emitting really bad error messages. Here, we attempt to
11880     // emit better ones.
11881     for (const Expr *Arg : Args) {
11882       if (!Arg->getType()->isFunctionType())
11883         continue;
11884       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11885         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11886         if (FD &&
11887             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11888                                                        Arg->getExprLoc()))
11889           return ExprError();
11890       }
11891     }
11892 
11893     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11894         << ULE->getName() << Fn->getSourceRange();
11895     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11896     break;
11897   }
11898 
11899   case OR_Ambiguous:
11900     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11901       << ULE->getName() << Fn->getSourceRange();
11902     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11903     break;
11904 
11905   case OR_Deleted: {
11906     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11907       << (*Best)->Function->isDeleted()
11908       << ULE->getName()
11909       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11910       << Fn->getSourceRange();
11911     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11912 
11913     // We emitted an error for the unvailable/deleted function call but keep
11914     // the call in the AST.
11915     FunctionDecl *FDecl = (*Best)->Function;
11916     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11917     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11918                                          ExecConfig);
11919   }
11920   }
11921 
11922   // Overload resolution failed.
11923   return ExprError();
11924 }
11925 
11926 static void markUnaddressableCandidatesUnviable(Sema &S,
11927                                                 OverloadCandidateSet &CS) {
11928   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11929     if (I->Viable &&
11930         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11931       I->Viable = false;
11932       I->FailureKind = ovl_fail_addr_not_available;
11933     }
11934   }
11935 }
11936 
11937 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11938 /// (which eventually refers to the declaration Func) and the call
11939 /// arguments Args/NumArgs, attempt to resolve the function call down
11940 /// to a specific function. If overload resolution succeeds, returns
11941 /// the call expression produced by overload resolution.
11942 /// Otherwise, emits diagnostics and returns ExprError.
11943 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11944                                          UnresolvedLookupExpr *ULE,
11945                                          SourceLocation LParenLoc,
11946                                          MultiExprArg Args,
11947                                          SourceLocation RParenLoc,
11948                                          Expr *ExecConfig,
11949                                          bool AllowTypoCorrection,
11950                                          bool CalleesAddressIsTaken) {
11951   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11952                                     OverloadCandidateSet::CSK_Normal);
11953   ExprResult result;
11954 
11955   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11956                              &result))
11957     return result;
11958 
11959   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11960   // functions that aren't addressible are considered unviable.
11961   if (CalleesAddressIsTaken)
11962     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11963 
11964   OverloadCandidateSet::iterator Best;
11965   OverloadingResult OverloadResult =
11966       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11967 
11968   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11969                                   RParenLoc, ExecConfig, &CandidateSet,
11970                                   &Best, OverloadResult,
11971                                   AllowTypoCorrection);
11972 }
11973 
11974 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11975   return Functions.size() > 1 ||
11976     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11977 }
11978 
11979 /// \brief Create a unary operation that may resolve to an overloaded
11980 /// operator.
11981 ///
11982 /// \param OpLoc The location of the operator itself (e.g., '*').
11983 ///
11984 /// \param Opc The UnaryOperatorKind that describes this operator.
11985 ///
11986 /// \param Fns The set of non-member functions that will be
11987 /// considered by overload resolution. The caller needs to build this
11988 /// set based on the context using, e.g.,
11989 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11990 /// set should not contain any member functions; those will be added
11991 /// by CreateOverloadedUnaryOp().
11992 ///
11993 /// \param Input The input argument.
11994 ExprResult
11995 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11996                               const UnresolvedSetImpl &Fns,
11997                               Expr *Input, bool PerformADL) {
11998   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11999   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12000   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12001   // TODO: provide better source location info.
12002   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12003 
12004   if (checkPlaceholderForOverload(*this, Input))
12005     return ExprError();
12006 
12007   Expr *Args[2] = { Input, nullptr };
12008   unsigned NumArgs = 1;
12009 
12010   // For post-increment and post-decrement, add the implicit '0' as
12011   // the second argument, so that we know this is a post-increment or
12012   // post-decrement.
12013   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12014     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12015     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12016                                      SourceLocation());
12017     NumArgs = 2;
12018   }
12019 
12020   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12021 
12022   if (Input->isTypeDependent()) {
12023     if (Fns.empty())
12024       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12025                                          VK_RValue, OK_Ordinary, OpLoc, false);
12026 
12027     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12028     UnresolvedLookupExpr *Fn
12029       = UnresolvedLookupExpr::Create(Context, NamingClass,
12030                                      NestedNameSpecifierLoc(), OpNameInfo,
12031                                      /*ADL*/ true, IsOverloaded(Fns),
12032                                      Fns.begin(), Fns.end());
12033     return new (Context)
12034         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12035                             VK_RValue, OpLoc, FPOptions());
12036   }
12037 
12038   // Build an empty overload set.
12039   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12040 
12041   // Add the candidates from the given function set.
12042   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12043 
12044   // Add operator candidates that are member functions.
12045   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12046 
12047   // Add candidates from ADL.
12048   if (PerformADL) {
12049     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12050                                          /*ExplicitTemplateArgs*/nullptr,
12051                                          CandidateSet);
12052   }
12053 
12054   // Add builtin operator candidates.
12055   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12056 
12057   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12058 
12059   // Perform overload resolution.
12060   OverloadCandidateSet::iterator Best;
12061   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12062   case OR_Success: {
12063     // We found a built-in operator or an overloaded operator.
12064     FunctionDecl *FnDecl = Best->Function;
12065 
12066     if (FnDecl) {
12067       Expr *Base = nullptr;
12068       // We matched an overloaded operator. Build a call to that
12069       // operator.
12070 
12071       // Convert the arguments.
12072       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12073         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12074 
12075         ExprResult InputRes =
12076           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12077                                               Best->FoundDecl, Method);
12078         if (InputRes.isInvalid())
12079           return ExprError();
12080         Base = Input = InputRes.get();
12081       } else {
12082         // Convert the arguments.
12083         ExprResult InputInit
12084           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12085                                                       Context,
12086                                                       FnDecl->getParamDecl(0)),
12087                                       SourceLocation(),
12088                                       Input);
12089         if (InputInit.isInvalid())
12090           return ExprError();
12091         Input = InputInit.get();
12092       }
12093 
12094       // Build the actual expression node.
12095       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12096                                                 Base, HadMultipleCandidates,
12097                                                 OpLoc);
12098       if (FnExpr.isInvalid())
12099         return ExprError();
12100 
12101       // Determine the result type.
12102       QualType ResultTy = FnDecl->getReturnType();
12103       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12104       ResultTy = ResultTy.getNonLValueExprType(Context);
12105 
12106       Args[0] = Input;
12107       CallExpr *TheCall =
12108         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12109                                           ResultTy, VK, OpLoc, FPOptions());
12110 
12111       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12112         return ExprError();
12113 
12114       if (CheckFunctionCall(FnDecl, TheCall,
12115                             FnDecl->getType()->castAs<FunctionProtoType>()))
12116         return ExprError();
12117 
12118       return MaybeBindToTemporary(TheCall);
12119     } else {
12120       // We matched a built-in operator. Convert the arguments, then
12121       // break out so that we will build the appropriate built-in
12122       // operator node.
12123       ExprResult InputRes = PerformImplicitConversion(
12124           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12125       if (InputRes.isInvalid())
12126         return ExprError();
12127       Input = InputRes.get();
12128       break;
12129     }
12130   }
12131 
12132   case OR_No_Viable_Function:
12133     // This is an erroneous use of an operator which can be overloaded by
12134     // a non-member function. Check for non-member operators which were
12135     // defined too late to be candidates.
12136     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12137       // FIXME: Recover by calling the found function.
12138       return ExprError();
12139 
12140     // No viable function; fall through to handling this as a
12141     // built-in operator, which will produce an error message for us.
12142     break;
12143 
12144   case OR_Ambiguous:
12145     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12146         << UnaryOperator::getOpcodeStr(Opc)
12147         << Input->getType()
12148         << Input->getSourceRange();
12149     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12150                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12151     return ExprError();
12152 
12153   case OR_Deleted:
12154     Diag(OpLoc, diag::err_ovl_deleted_oper)
12155       << Best->Function->isDeleted()
12156       << UnaryOperator::getOpcodeStr(Opc)
12157       << getDeletedOrUnavailableSuffix(Best->Function)
12158       << Input->getSourceRange();
12159     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12160                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12161     return ExprError();
12162   }
12163 
12164   // Either we found no viable overloaded operator or we matched a
12165   // built-in operator. In either case, fall through to trying to
12166   // build a built-in operation.
12167   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12168 }
12169 
12170 /// \brief Create a binary operation that may resolve to an overloaded
12171 /// operator.
12172 ///
12173 /// \param OpLoc The location of the operator itself (e.g., '+').
12174 ///
12175 /// \param Opc The BinaryOperatorKind that describes this operator.
12176 ///
12177 /// \param Fns The set of non-member functions that will be
12178 /// considered by overload resolution. The caller needs to build this
12179 /// set based on the context using, e.g.,
12180 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12181 /// set should not contain any member functions; those will be added
12182 /// by CreateOverloadedBinOp().
12183 ///
12184 /// \param LHS Left-hand argument.
12185 /// \param RHS Right-hand argument.
12186 ExprResult
12187 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12188                             BinaryOperatorKind Opc,
12189                             const UnresolvedSetImpl &Fns,
12190                             Expr *LHS, Expr *RHS, bool PerformADL) {
12191   Expr *Args[2] = { LHS, RHS };
12192   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12193 
12194   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12195   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12196 
12197   // If either side is type-dependent, create an appropriate dependent
12198   // expression.
12199   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12200     if (Fns.empty()) {
12201       // If there are no functions to store, just build a dependent
12202       // BinaryOperator or CompoundAssignment.
12203       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12204         return new (Context) BinaryOperator(
12205             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12206             OpLoc, FPFeatures);
12207 
12208       return new (Context) CompoundAssignOperator(
12209           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12210           Context.DependentTy, Context.DependentTy, OpLoc,
12211           FPFeatures);
12212     }
12213 
12214     // FIXME: save results of ADL from here?
12215     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12216     // TODO: provide better source location info in DNLoc component.
12217     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12218     UnresolvedLookupExpr *Fn
12219       = UnresolvedLookupExpr::Create(Context, NamingClass,
12220                                      NestedNameSpecifierLoc(), OpNameInfo,
12221                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12222                                      Fns.begin(), Fns.end());
12223     return new (Context)
12224         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12225                             VK_RValue, OpLoc, FPFeatures);
12226   }
12227 
12228   // Always do placeholder-like conversions on the RHS.
12229   if (checkPlaceholderForOverload(*this, Args[1]))
12230     return ExprError();
12231 
12232   // Do placeholder-like conversion on the LHS; note that we should
12233   // not get here with a PseudoObject LHS.
12234   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12235   if (checkPlaceholderForOverload(*this, Args[0]))
12236     return ExprError();
12237 
12238   // If this is the assignment operator, we only perform overload resolution
12239   // if the left-hand side is a class or enumeration type. This is actually
12240   // a hack. The standard requires that we do overload resolution between the
12241   // various built-in candidates, but as DR507 points out, this can lead to
12242   // problems. So we do it this way, which pretty much follows what GCC does.
12243   // Note that we go the traditional code path for compound assignment forms.
12244   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12245     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12246 
12247   // If this is the .* operator, which is not overloadable, just
12248   // create a built-in binary operator.
12249   if (Opc == BO_PtrMemD)
12250     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12251 
12252   // Build an empty overload set.
12253   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12254 
12255   // Add the candidates from the given function set.
12256   AddFunctionCandidates(Fns, Args, CandidateSet);
12257 
12258   // Add operator candidates that are member functions.
12259   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12260 
12261   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12262   // performed for an assignment operator (nor for operator[] nor operator->,
12263   // which don't get here).
12264   if (Opc != BO_Assign && PerformADL)
12265     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12266                                          /*ExplicitTemplateArgs*/ nullptr,
12267                                          CandidateSet);
12268 
12269   // Add builtin operator candidates.
12270   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12271 
12272   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12273 
12274   // Perform overload resolution.
12275   OverloadCandidateSet::iterator Best;
12276   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12277     case OR_Success: {
12278       // We found a built-in operator or an overloaded operator.
12279       FunctionDecl *FnDecl = Best->Function;
12280 
12281       if (FnDecl) {
12282         Expr *Base = nullptr;
12283         // We matched an overloaded operator. Build a call to that
12284         // operator.
12285 
12286         // Convert the arguments.
12287         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12288           // Best->Access is only meaningful for class members.
12289           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12290 
12291           ExprResult Arg1 =
12292             PerformCopyInitialization(
12293               InitializedEntity::InitializeParameter(Context,
12294                                                      FnDecl->getParamDecl(0)),
12295               SourceLocation(), Args[1]);
12296           if (Arg1.isInvalid())
12297             return ExprError();
12298 
12299           ExprResult Arg0 =
12300             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12301                                                 Best->FoundDecl, Method);
12302           if (Arg0.isInvalid())
12303             return ExprError();
12304           Base = Args[0] = Arg0.getAs<Expr>();
12305           Args[1] = RHS = Arg1.getAs<Expr>();
12306         } else {
12307           // Convert the arguments.
12308           ExprResult Arg0 = PerformCopyInitialization(
12309             InitializedEntity::InitializeParameter(Context,
12310                                                    FnDecl->getParamDecl(0)),
12311             SourceLocation(), Args[0]);
12312           if (Arg0.isInvalid())
12313             return ExprError();
12314 
12315           ExprResult Arg1 =
12316             PerformCopyInitialization(
12317               InitializedEntity::InitializeParameter(Context,
12318                                                      FnDecl->getParamDecl(1)),
12319               SourceLocation(), Args[1]);
12320           if (Arg1.isInvalid())
12321             return ExprError();
12322           Args[0] = LHS = Arg0.getAs<Expr>();
12323           Args[1] = RHS = Arg1.getAs<Expr>();
12324         }
12325 
12326         // Build the actual expression node.
12327         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12328                                                   Best->FoundDecl, Base,
12329                                                   HadMultipleCandidates, OpLoc);
12330         if (FnExpr.isInvalid())
12331           return ExprError();
12332 
12333         // Determine the result type.
12334         QualType ResultTy = FnDecl->getReturnType();
12335         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12336         ResultTy = ResultTy.getNonLValueExprType(Context);
12337 
12338         CXXOperatorCallExpr *TheCall =
12339           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12340                                             Args, ResultTy, VK, OpLoc,
12341                                             FPFeatures);
12342 
12343         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12344                                 FnDecl))
12345           return ExprError();
12346 
12347         ArrayRef<const Expr *> ArgsArray(Args, 2);
12348         const Expr *ImplicitThis = nullptr;
12349         // Cut off the implicit 'this'.
12350         if (isa<CXXMethodDecl>(FnDecl)) {
12351           ImplicitThis = ArgsArray[0];
12352           ArgsArray = ArgsArray.slice(1);
12353         }
12354 
12355         // Check for a self move.
12356         if (Op == OO_Equal)
12357           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12358 
12359         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12360                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12361                   VariadicDoesNotApply);
12362 
12363         return MaybeBindToTemporary(TheCall);
12364       } else {
12365         // We matched a built-in operator. Convert the arguments, then
12366         // break out so that we will build the appropriate built-in
12367         // operator node.
12368         ExprResult ArgsRes0 =
12369             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12370                                       Best->Conversions[0], AA_Passing);
12371         if (ArgsRes0.isInvalid())
12372           return ExprError();
12373         Args[0] = ArgsRes0.get();
12374 
12375         ExprResult ArgsRes1 =
12376             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12377                                       Best->Conversions[1], AA_Passing);
12378         if (ArgsRes1.isInvalid())
12379           return ExprError();
12380         Args[1] = ArgsRes1.get();
12381         break;
12382       }
12383     }
12384 
12385     case OR_No_Viable_Function: {
12386       // C++ [over.match.oper]p9:
12387       //   If the operator is the operator , [...] and there are no
12388       //   viable functions, then the operator is assumed to be the
12389       //   built-in operator and interpreted according to clause 5.
12390       if (Opc == BO_Comma)
12391         break;
12392 
12393       // For class as left operand for assignment or compound assigment
12394       // operator do not fall through to handling in built-in, but report that
12395       // no overloaded assignment operator found
12396       ExprResult Result = ExprError();
12397       if (Args[0]->getType()->isRecordType() &&
12398           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12399         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12400              << BinaryOperator::getOpcodeStr(Opc)
12401              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12402         if (Args[0]->getType()->isIncompleteType()) {
12403           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12404             << Args[0]->getType()
12405             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12406         }
12407       } else {
12408         // This is an erroneous use of an operator which can be overloaded by
12409         // a non-member function. Check for non-member operators which were
12410         // defined too late to be candidates.
12411         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12412           // FIXME: Recover by calling the found function.
12413           return ExprError();
12414 
12415         // No viable function; try to create a built-in operation, which will
12416         // produce an error. Then, show the non-viable candidates.
12417         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12418       }
12419       assert(Result.isInvalid() &&
12420              "C++ binary operator overloading is missing candidates!");
12421       if (Result.isInvalid())
12422         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12423                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12424       return Result;
12425     }
12426 
12427     case OR_Ambiguous:
12428       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12429           << BinaryOperator::getOpcodeStr(Opc)
12430           << Args[0]->getType() << Args[1]->getType()
12431           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12432       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12433                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12434       return ExprError();
12435 
12436     case OR_Deleted:
12437       if (isImplicitlyDeleted(Best->Function)) {
12438         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12439         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12440           << Context.getRecordType(Method->getParent())
12441           << getSpecialMember(Method);
12442 
12443         // The user probably meant to call this special member. Just
12444         // explain why it's deleted.
12445         NoteDeletedFunction(Method);
12446         return ExprError();
12447       } else {
12448         Diag(OpLoc, diag::err_ovl_deleted_oper)
12449           << Best->Function->isDeleted()
12450           << BinaryOperator::getOpcodeStr(Opc)
12451           << getDeletedOrUnavailableSuffix(Best->Function)
12452           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12453       }
12454       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12455                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12456       return ExprError();
12457   }
12458 
12459   // We matched a built-in operator; build it.
12460   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12461 }
12462 
12463 ExprResult
12464 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12465                                          SourceLocation RLoc,
12466                                          Expr *Base, Expr *Idx) {
12467   Expr *Args[2] = { Base, Idx };
12468   DeclarationName OpName =
12469       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12470 
12471   // If either side is type-dependent, create an appropriate dependent
12472   // expression.
12473   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12474 
12475     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12476     // CHECKME: no 'operator' keyword?
12477     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12478     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12479     UnresolvedLookupExpr *Fn
12480       = UnresolvedLookupExpr::Create(Context, NamingClass,
12481                                      NestedNameSpecifierLoc(), OpNameInfo,
12482                                      /*ADL*/ true, /*Overloaded*/ false,
12483                                      UnresolvedSetIterator(),
12484                                      UnresolvedSetIterator());
12485     // Can't add any actual overloads yet
12486 
12487     return new (Context)
12488         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12489                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12490   }
12491 
12492   // Handle placeholders on both operands.
12493   if (checkPlaceholderForOverload(*this, Args[0]))
12494     return ExprError();
12495   if (checkPlaceholderForOverload(*this, Args[1]))
12496     return ExprError();
12497 
12498   // Build an empty overload set.
12499   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12500 
12501   // Subscript can only be overloaded as a member function.
12502 
12503   // Add operator candidates that are member functions.
12504   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12505 
12506   // Add builtin operator candidates.
12507   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12508 
12509   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12510 
12511   // Perform overload resolution.
12512   OverloadCandidateSet::iterator Best;
12513   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12514     case OR_Success: {
12515       // We found a built-in operator or an overloaded operator.
12516       FunctionDecl *FnDecl = Best->Function;
12517 
12518       if (FnDecl) {
12519         // We matched an overloaded operator. Build a call to that
12520         // operator.
12521 
12522         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12523 
12524         // Convert the arguments.
12525         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12526         ExprResult Arg0 =
12527           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12528                                               Best->FoundDecl, Method);
12529         if (Arg0.isInvalid())
12530           return ExprError();
12531         Args[0] = Arg0.get();
12532 
12533         // Convert the arguments.
12534         ExprResult InputInit
12535           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12536                                                       Context,
12537                                                       FnDecl->getParamDecl(0)),
12538                                       SourceLocation(),
12539                                       Args[1]);
12540         if (InputInit.isInvalid())
12541           return ExprError();
12542 
12543         Args[1] = InputInit.getAs<Expr>();
12544 
12545         // Build the actual expression node.
12546         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12547         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12548         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12549                                                   Best->FoundDecl,
12550                                                   Base,
12551                                                   HadMultipleCandidates,
12552                                                   OpLocInfo.getLoc(),
12553                                                   OpLocInfo.getInfo());
12554         if (FnExpr.isInvalid())
12555           return ExprError();
12556 
12557         // Determine the result type
12558         QualType ResultTy = FnDecl->getReturnType();
12559         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12560         ResultTy = ResultTy.getNonLValueExprType(Context);
12561 
12562         CXXOperatorCallExpr *TheCall =
12563           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12564                                             FnExpr.get(), Args,
12565                                             ResultTy, VK, RLoc,
12566                                             FPOptions());
12567 
12568         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12569           return ExprError();
12570 
12571         if (CheckFunctionCall(Method, TheCall,
12572                               Method->getType()->castAs<FunctionProtoType>()))
12573           return ExprError();
12574 
12575         return MaybeBindToTemporary(TheCall);
12576       } else {
12577         // We matched a built-in operator. Convert the arguments, then
12578         // break out so that we will build the appropriate built-in
12579         // operator node.
12580         ExprResult ArgsRes0 =
12581             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12582                                       Best->Conversions[0], AA_Passing);
12583         if (ArgsRes0.isInvalid())
12584           return ExprError();
12585         Args[0] = ArgsRes0.get();
12586 
12587         ExprResult ArgsRes1 =
12588             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12589                                       Best->Conversions[1], AA_Passing);
12590         if (ArgsRes1.isInvalid())
12591           return ExprError();
12592         Args[1] = ArgsRes1.get();
12593 
12594         break;
12595       }
12596     }
12597 
12598     case OR_No_Viable_Function: {
12599       if (CandidateSet.empty())
12600         Diag(LLoc, diag::err_ovl_no_oper)
12601           << Args[0]->getType() << /*subscript*/ 0
12602           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12603       else
12604         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12605           << Args[0]->getType()
12606           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12607       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12608                                   "[]", LLoc);
12609       return ExprError();
12610     }
12611 
12612     case OR_Ambiguous:
12613       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12614           << "[]"
12615           << Args[0]->getType() << Args[1]->getType()
12616           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12617       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12618                                   "[]", LLoc);
12619       return ExprError();
12620 
12621     case OR_Deleted:
12622       Diag(LLoc, diag::err_ovl_deleted_oper)
12623         << Best->Function->isDeleted() << "[]"
12624         << getDeletedOrUnavailableSuffix(Best->Function)
12625         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12626       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12627                                   "[]", LLoc);
12628       return ExprError();
12629     }
12630 
12631   // We matched a built-in operator; build it.
12632   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12633 }
12634 
12635 /// BuildCallToMemberFunction - Build a call to a member
12636 /// function. MemExpr is the expression that refers to the member
12637 /// function (and includes the object parameter), Args/NumArgs are the
12638 /// arguments to the function call (not including the object
12639 /// parameter). The caller needs to validate that the member
12640 /// expression refers to a non-static member function or an overloaded
12641 /// member function.
12642 ExprResult
12643 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12644                                 SourceLocation LParenLoc,
12645                                 MultiExprArg Args,
12646                                 SourceLocation RParenLoc) {
12647   assert(MemExprE->getType() == Context.BoundMemberTy ||
12648          MemExprE->getType() == Context.OverloadTy);
12649 
12650   // Dig out the member expression. This holds both the object
12651   // argument and the member function we're referring to.
12652   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12653 
12654   // Determine whether this is a call to a pointer-to-member function.
12655   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12656     assert(op->getType() == Context.BoundMemberTy);
12657     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12658 
12659     QualType fnType =
12660       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12661 
12662     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12663     QualType resultType = proto->getCallResultType(Context);
12664     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12665 
12666     // Check that the object type isn't more qualified than the
12667     // member function we're calling.
12668     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12669 
12670     QualType objectType = op->getLHS()->getType();
12671     if (op->getOpcode() == BO_PtrMemI)
12672       objectType = objectType->castAs<PointerType>()->getPointeeType();
12673     Qualifiers objectQuals = objectType.getQualifiers();
12674 
12675     Qualifiers difference = objectQuals - funcQuals;
12676     difference.removeObjCGCAttr();
12677     difference.removeAddressSpace();
12678     if (difference) {
12679       std::string qualsString = difference.getAsString();
12680       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12681         << fnType.getUnqualifiedType()
12682         << qualsString
12683         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12684     }
12685 
12686     CXXMemberCallExpr *call
12687       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12688                                         resultType, valueKind, RParenLoc);
12689 
12690     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12691                             call, nullptr))
12692       return ExprError();
12693 
12694     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12695       return ExprError();
12696 
12697     if (CheckOtherCall(call, proto))
12698       return ExprError();
12699 
12700     return MaybeBindToTemporary(call);
12701   }
12702 
12703   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12704     return new (Context)
12705         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12706 
12707   UnbridgedCastsSet UnbridgedCasts;
12708   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12709     return ExprError();
12710 
12711   MemberExpr *MemExpr;
12712   CXXMethodDecl *Method = nullptr;
12713   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12714   NestedNameSpecifier *Qualifier = nullptr;
12715   if (isa<MemberExpr>(NakedMemExpr)) {
12716     MemExpr = cast<MemberExpr>(NakedMemExpr);
12717     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12718     FoundDecl = MemExpr->getFoundDecl();
12719     Qualifier = MemExpr->getQualifier();
12720     UnbridgedCasts.restore();
12721   } else {
12722     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12723     Qualifier = UnresExpr->getQualifier();
12724 
12725     QualType ObjectType = UnresExpr->getBaseType();
12726     Expr::Classification ObjectClassification
12727       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12728                             : UnresExpr->getBase()->Classify(Context);
12729 
12730     // Add overload candidates
12731     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12732                                       OverloadCandidateSet::CSK_Normal);
12733 
12734     // FIXME: avoid copy.
12735     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12736     if (UnresExpr->hasExplicitTemplateArgs()) {
12737       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12738       TemplateArgs = &TemplateArgsBuffer;
12739     }
12740 
12741     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12742            E = UnresExpr->decls_end(); I != E; ++I) {
12743 
12744       NamedDecl *Func = *I;
12745       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12746       if (isa<UsingShadowDecl>(Func))
12747         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12748 
12749 
12750       // Microsoft supports direct constructor calls.
12751       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12752         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12753                              Args, CandidateSet);
12754       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12755         // If explicit template arguments were provided, we can't call a
12756         // non-template member function.
12757         if (TemplateArgs)
12758           continue;
12759 
12760         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12761                            ObjectClassification, Args, CandidateSet,
12762                            /*SuppressUserConversions=*/false);
12763       } else {
12764         AddMethodTemplateCandidate(
12765             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12766             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12767             /*SuppressUsedConversions=*/false);
12768       }
12769     }
12770 
12771     DeclarationName DeclName = UnresExpr->getMemberName();
12772 
12773     UnbridgedCasts.restore();
12774 
12775     OverloadCandidateSet::iterator Best;
12776     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12777                                             Best)) {
12778     case OR_Success:
12779       Method = cast<CXXMethodDecl>(Best->Function);
12780       FoundDecl = Best->FoundDecl;
12781       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12782       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12783         return ExprError();
12784       // If FoundDecl is different from Method (such as if one is a template
12785       // and the other a specialization), make sure DiagnoseUseOfDecl is
12786       // called on both.
12787       // FIXME: This would be more comprehensively addressed by modifying
12788       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12789       // being used.
12790       if (Method != FoundDecl.getDecl() &&
12791                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12792         return ExprError();
12793       break;
12794 
12795     case OR_No_Viable_Function:
12796       Diag(UnresExpr->getMemberLoc(),
12797            diag::err_ovl_no_viable_member_function_in_call)
12798         << DeclName << MemExprE->getSourceRange();
12799       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12800       // FIXME: Leaking incoming expressions!
12801       return ExprError();
12802 
12803     case OR_Ambiguous:
12804       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12805         << DeclName << MemExprE->getSourceRange();
12806       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12807       // FIXME: Leaking incoming expressions!
12808       return ExprError();
12809 
12810     case OR_Deleted:
12811       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12812         << Best->Function->isDeleted()
12813         << DeclName
12814         << getDeletedOrUnavailableSuffix(Best->Function)
12815         << MemExprE->getSourceRange();
12816       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12817       // FIXME: Leaking incoming expressions!
12818       return ExprError();
12819     }
12820 
12821     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12822 
12823     // If overload resolution picked a static member, build a
12824     // non-member call based on that function.
12825     if (Method->isStatic()) {
12826       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12827                                    RParenLoc);
12828     }
12829 
12830     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12831   }
12832 
12833   QualType ResultType = Method->getReturnType();
12834   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12835   ResultType = ResultType.getNonLValueExprType(Context);
12836 
12837   assert(Method && "Member call to something that isn't a method?");
12838   CXXMemberCallExpr *TheCall =
12839     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12840                                     ResultType, VK, RParenLoc);
12841 
12842   // Check for a valid return type.
12843   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12844                           TheCall, Method))
12845     return ExprError();
12846 
12847   // Convert the object argument (for a non-static member function call).
12848   // We only need to do this if there was actually an overload; otherwise
12849   // it was done at lookup.
12850   if (!Method->isStatic()) {
12851     ExprResult ObjectArg =
12852       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12853                                           FoundDecl, Method);
12854     if (ObjectArg.isInvalid())
12855       return ExprError();
12856     MemExpr->setBase(ObjectArg.get());
12857   }
12858 
12859   // Convert the rest of the arguments
12860   const FunctionProtoType *Proto =
12861     Method->getType()->getAs<FunctionProtoType>();
12862   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12863                               RParenLoc))
12864     return ExprError();
12865 
12866   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12867 
12868   if (CheckFunctionCall(Method, TheCall, Proto))
12869     return ExprError();
12870 
12871   // In the case the method to call was not selected by the overloading
12872   // resolution process, we still need to handle the enable_if attribute. Do
12873   // that here, so it will not hide previous -- and more relevant -- errors.
12874   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12875     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12876       Diag(MemE->getMemberLoc(),
12877            diag::err_ovl_no_viable_member_function_in_call)
12878           << Method << Method->getSourceRange();
12879       Diag(Method->getLocation(),
12880            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12881           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12882       return ExprError();
12883     }
12884   }
12885 
12886   if ((isa<CXXConstructorDecl>(CurContext) ||
12887        isa<CXXDestructorDecl>(CurContext)) &&
12888       TheCall->getMethodDecl()->isPure()) {
12889     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12890 
12891     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12892         MemExpr->performsVirtualDispatch(getLangOpts())) {
12893       Diag(MemExpr->getLocStart(),
12894            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12895         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12896         << MD->getParent()->getDeclName();
12897 
12898       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12899       if (getLangOpts().AppleKext)
12900         Diag(MemExpr->getLocStart(),
12901              diag::note_pure_qualified_call_kext)
12902              << MD->getParent()->getDeclName()
12903              << MD->getDeclName();
12904     }
12905   }
12906 
12907   if (CXXDestructorDecl *DD =
12908           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12909     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12910     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12911     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12912                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12913                          MemExpr->getMemberLoc());
12914   }
12915 
12916   return MaybeBindToTemporary(TheCall);
12917 }
12918 
12919 /// BuildCallToObjectOfClassType - Build a call to an object of class
12920 /// type (C++ [over.call.object]), which can end up invoking an
12921 /// overloaded function call operator (@c operator()) or performing a
12922 /// user-defined conversion on the object argument.
12923 ExprResult
12924 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12925                                    SourceLocation LParenLoc,
12926                                    MultiExprArg Args,
12927                                    SourceLocation RParenLoc) {
12928   if (checkPlaceholderForOverload(*this, Obj))
12929     return ExprError();
12930   ExprResult Object = Obj;
12931 
12932   UnbridgedCastsSet UnbridgedCasts;
12933   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12934     return ExprError();
12935 
12936   assert(Object.get()->getType()->isRecordType() &&
12937          "Requires object type argument");
12938   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12939 
12940   // C++ [over.call.object]p1:
12941   //  If the primary-expression E in the function call syntax
12942   //  evaluates to a class object of type "cv T", then the set of
12943   //  candidate functions includes at least the function call
12944   //  operators of T. The function call operators of T are obtained by
12945   //  ordinary lookup of the name operator() in the context of
12946   //  (E).operator().
12947   OverloadCandidateSet CandidateSet(LParenLoc,
12948                                     OverloadCandidateSet::CSK_Operator);
12949   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12950 
12951   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12952                           diag::err_incomplete_object_call, Object.get()))
12953     return true;
12954 
12955   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12956   LookupQualifiedName(R, Record->getDecl());
12957   R.suppressDiagnostics();
12958 
12959   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12960        Oper != OperEnd; ++Oper) {
12961     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12962                        Object.get()->Classify(Context), Args, CandidateSet,
12963                        /*SuppressUserConversions=*/false);
12964   }
12965 
12966   // C++ [over.call.object]p2:
12967   //   In addition, for each (non-explicit in C++0x) conversion function
12968   //   declared in T of the form
12969   //
12970   //        operator conversion-type-id () cv-qualifier;
12971   //
12972   //   where cv-qualifier is the same cv-qualification as, or a
12973   //   greater cv-qualification than, cv, and where conversion-type-id
12974   //   denotes the type "pointer to function of (P1,...,Pn) returning
12975   //   R", or the type "reference to pointer to function of
12976   //   (P1,...,Pn) returning R", or the type "reference to function
12977   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12978   //   is also considered as a candidate function. Similarly,
12979   //   surrogate call functions are added to the set of candidate
12980   //   functions for each conversion function declared in an
12981   //   accessible base class provided the function is not hidden
12982   //   within T by another intervening declaration.
12983   const auto &Conversions =
12984       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12985   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12986     NamedDecl *D = *I;
12987     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12988     if (isa<UsingShadowDecl>(D))
12989       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12990 
12991     // Skip over templated conversion functions; they aren't
12992     // surrogates.
12993     if (isa<FunctionTemplateDecl>(D))
12994       continue;
12995 
12996     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12997     if (!Conv->isExplicit()) {
12998       // Strip the reference type (if any) and then the pointer type (if
12999       // any) to get down to what might be a function type.
13000       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13001       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13002         ConvType = ConvPtrType->getPointeeType();
13003 
13004       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13005       {
13006         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13007                               Object.get(), Args, CandidateSet);
13008       }
13009     }
13010   }
13011 
13012   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13013 
13014   // Perform overload resolution.
13015   OverloadCandidateSet::iterator Best;
13016   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13017                                           Best)) {
13018   case OR_Success:
13019     // Overload resolution succeeded; we'll build the appropriate call
13020     // below.
13021     break;
13022 
13023   case OR_No_Viable_Function:
13024     if (CandidateSet.empty())
13025       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13026         << Object.get()->getType() << /*call*/ 1
13027         << Object.get()->getSourceRange();
13028     else
13029       Diag(Object.get()->getLocStart(),
13030            diag::err_ovl_no_viable_object_call)
13031         << Object.get()->getType() << Object.get()->getSourceRange();
13032     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13033     break;
13034 
13035   case OR_Ambiguous:
13036     Diag(Object.get()->getLocStart(),
13037          diag::err_ovl_ambiguous_object_call)
13038       << Object.get()->getType() << Object.get()->getSourceRange();
13039     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13040     break;
13041 
13042   case OR_Deleted:
13043     Diag(Object.get()->getLocStart(),
13044          diag::err_ovl_deleted_object_call)
13045       << Best->Function->isDeleted()
13046       << Object.get()->getType()
13047       << getDeletedOrUnavailableSuffix(Best->Function)
13048       << Object.get()->getSourceRange();
13049     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13050     break;
13051   }
13052 
13053   if (Best == CandidateSet.end())
13054     return true;
13055 
13056   UnbridgedCasts.restore();
13057 
13058   if (Best->Function == nullptr) {
13059     // Since there is no function declaration, this is one of the
13060     // surrogate candidates. Dig out the conversion function.
13061     CXXConversionDecl *Conv
13062       = cast<CXXConversionDecl>(
13063                          Best->Conversions[0].UserDefined.ConversionFunction);
13064 
13065     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13066                               Best->FoundDecl);
13067     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13068       return ExprError();
13069     assert(Conv == Best->FoundDecl.getDecl() &&
13070              "Found Decl & conversion-to-functionptr should be same, right?!");
13071     // We selected one of the surrogate functions that converts the
13072     // object parameter to a function pointer. Perform the conversion
13073     // on the object argument, then let ActOnCallExpr finish the job.
13074 
13075     // Create an implicit member expr to refer to the conversion operator.
13076     // and then call it.
13077     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13078                                              Conv, HadMultipleCandidates);
13079     if (Call.isInvalid())
13080       return ExprError();
13081     // Record usage of conversion in an implicit cast.
13082     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13083                                     CK_UserDefinedConversion, Call.get(),
13084                                     nullptr, VK_RValue);
13085 
13086     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13087   }
13088 
13089   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13090 
13091   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13092   // that calls this method, using Object for the implicit object
13093   // parameter and passing along the remaining arguments.
13094   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13095 
13096   // An error diagnostic has already been printed when parsing the declaration.
13097   if (Method->isInvalidDecl())
13098     return ExprError();
13099 
13100   const FunctionProtoType *Proto =
13101     Method->getType()->getAs<FunctionProtoType>();
13102 
13103   unsigned NumParams = Proto->getNumParams();
13104 
13105   DeclarationNameInfo OpLocInfo(
13106                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13107   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13108   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13109                                            Obj, HadMultipleCandidates,
13110                                            OpLocInfo.getLoc(),
13111                                            OpLocInfo.getInfo());
13112   if (NewFn.isInvalid())
13113     return true;
13114 
13115   // Build the full argument list for the method call (the implicit object
13116   // parameter is placed at the beginning of the list).
13117   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13118   MethodArgs[0] = Object.get();
13119   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13120 
13121   // Once we've built TheCall, all of the expressions are properly
13122   // owned.
13123   QualType ResultTy = Method->getReturnType();
13124   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13125   ResultTy = ResultTy.getNonLValueExprType(Context);
13126 
13127   CXXOperatorCallExpr *TheCall = new (Context)
13128       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13129                           VK, RParenLoc, FPOptions());
13130 
13131   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13132     return true;
13133 
13134   // We may have default arguments. If so, we need to allocate more
13135   // slots in the call for them.
13136   if (Args.size() < NumParams)
13137     TheCall->setNumArgs(Context, NumParams + 1);
13138 
13139   bool IsError = false;
13140 
13141   // Initialize the implicit object parameter.
13142   ExprResult ObjRes =
13143     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13144                                         Best->FoundDecl, Method);
13145   if (ObjRes.isInvalid())
13146     IsError = true;
13147   else
13148     Object = ObjRes;
13149   TheCall->setArg(0, Object.get());
13150 
13151   // Check the argument types.
13152   for (unsigned i = 0; i != NumParams; i++) {
13153     Expr *Arg;
13154     if (i < Args.size()) {
13155       Arg = Args[i];
13156 
13157       // Pass the argument.
13158 
13159       ExprResult InputInit
13160         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13161                                                     Context,
13162                                                     Method->getParamDecl(i)),
13163                                     SourceLocation(), Arg);
13164 
13165       IsError |= InputInit.isInvalid();
13166       Arg = InputInit.getAs<Expr>();
13167     } else {
13168       ExprResult DefArg
13169         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13170       if (DefArg.isInvalid()) {
13171         IsError = true;
13172         break;
13173       }
13174 
13175       Arg = DefArg.getAs<Expr>();
13176     }
13177 
13178     TheCall->setArg(i + 1, Arg);
13179   }
13180 
13181   // If this is a variadic call, handle args passed through "...".
13182   if (Proto->isVariadic()) {
13183     // Promote the arguments (C99 6.5.2.2p7).
13184     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13185       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13186                                                         nullptr);
13187       IsError |= Arg.isInvalid();
13188       TheCall->setArg(i + 1, Arg.get());
13189     }
13190   }
13191 
13192   if (IsError) return true;
13193 
13194   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13195 
13196   if (CheckFunctionCall(Method, TheCall, Proto))
13197     return true;
13198 
13199   return MaybeBindToTemporary(TheCall);
13200 }
13201 
13202 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13203 ///  (if one exists), where @c Base is an expression of class type and
13204 /// @c Member is the name of the member we're trying to find.
13205 ExprResult
13206 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13207                                bool *NoArrowOperatorFound) {
13208   assert(Base->getType()->isRecordType() &&
13209          "left-hand side must have class type");
13210 
13211   if (checkPlaceholderForOverload(*this, Base))
13212     return ExprError();
13213 
13214   SourceLocation Loc = Base->getExprLoc();
13215 
13216   // C++ [over.ref]p1:
13217   //
13218   //   [...] An expression x->m is interpreted as (x.operator->())->m
13219   //   for a class object x of type T if T::operator->() exists and if
13220   //   the operator is selected as the best match function by the
13221   //   overload resolution mechanism (13.3).
13222   DeclarationName OpName =
13223     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13224   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13225   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13226 
13227   if (RequireCompleteType(Loc, Base->getType(),
13228                           diag::err_typecheck_incomplete_tag, Base))
13229     return ExprError();
13230 
13231   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13232   LookupQualifiedName(R, BaseRecord->getDecl());
13233   R.suppressDiagnostics();
13234 
13235   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13236        Oper != OperEnd; ++Oper) {
13237     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13238                        None, CandidateSet, /*SuppressUserConversions=*/false);
13239   }
13240 
13241   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13242 
13243   // Perform overload resolution.
13244   OverloadCandidateSet::iterator Best;
13245   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13246   case OR_Success:
13247     // Overload resolution succeeded; we'll build the call below.
13248     break;
13249 
13250   case OR_No_Viable_Function:
13251     if (CandidateSet.empty()) {
13252       QualType BaseType = Base->getType();
13253       if (NoArrowOperatorFound) {
13254         // Report this specific error to the caller instead of emitting a
13255         // diagnostic, as requested.
13256         *NoArrowOperatorFound = true;
13257         return ExprError();
13258       }
13259       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13260         << BaseType << Base->getSourceRange();
13261       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13262         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13263           << FixItHint::CreateReplacement(OpLoc, ".");
13264       }
13265     } else
13266       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13267         << "operator->" << Base->getSourceRange();
13268     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13269     return ExprError();
13270 
13271   case OR_Ambiguous:
13272     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13273       << "->" << Base->getType() << Base->getSourceRange();
13274     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13275     return ExprError();
13276 
13277   case OR_Deleted:
13278     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13279       << Best->Function->isDeleted()
13280       << "->"
13281       << getDeletedOrUnavailableSuffix(Best->Function)
13282       << Base->getSourceRange();
13283     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13284     return ExprError();
13285   }
13286 
13287   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13288 
13289   // Convert the object parameter.
13290   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13291   ExprResult BaseResult =
13292     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13293                                         Best->FoundDecl, Method);
13294   if (BaseResult.isInvalid())
13295     return ExprError();
13296   Base = BaseResult.get();
13297 
13298   // Build the operator call.
13299   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13300                                             Base, HadMultipleCandidates, OpLoc);
13301   if (FnExpr.isInvalid())
13302     return ExprError();
13303 
13304   QualType ResultTy = Method->getReturnType();
13305   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13306   ResultTy = ResultTy.getNonLValueExprType(Context);
13307   CXXOperatorCallExpr *TheCall =
13308     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13309                                       Base, ResultTy, VK, OpLoc, FPOptions());
13310 
13311   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13312     return ExprError();
13313 
13314   if (CheckFunctionCall(Method, TheCall,
13315                         Method->getType()->castAs<FunctionProtoType>()))
13316     return ExprError();
13317 
13318   return MaybeBindToTemporary(TheCall);
13319 }
13320 
13321 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13322 /// a literal operator described by the provided lookup results.
13323 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13324                                           DeclarationNameInfo &SuffixInfo,
13325                                           ArrayRef<Expr*> Args,
13326                                           SourceLocation LitEndLoc,
13327                                        TemplateArgumentListInfo *TemplateArgs) {
13328   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13329 
13330   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13331                                     OverloadCandidateSet::CSK_Normal);
13332   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13333                         /*SuppressUserConversions=*/true);
13334 
13335   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13336 
13337   // Perform overload resolution. This will usually be trivial, but might need
13338   // to perform substitutions for a literal operator template.
13339   OverloadCandidateSet::iterator Best;
13340   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13341   case OR_Success:
13342   case OR_Deleted:
13343     break;
13344 
13345   case OR_No_Viable_Function:
13346     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13347       << R.getLookupName();
13348     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13349     return ExprError();
13350 
13351   case OR_Ambiguous:
13352     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13353     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13354     return ExprError();
13355   }
13356 
13357   FunctionDecl *FD = Best->Function;
13358   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13359                                         nullptr, HadMultipleCandidates,
13360                                         SuffixInfo.getLoc(),
13361                                         SuffixInfo.getInfo());
13362   if (Fn.isInvalid())
13363     return true;
13364 
13365   // Check the argument types. This should almost always be a no-op, except
13366   // that array-to-pointer decay is applied to string literals.
13367   Expr *ConvArgs[2];
13368   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13369     ExprResult InputInit = PerformCopyInitialization(
13370       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13371       SourceLocation(), Args[ArgIdx]);
13372     if (InputInit.isInvalid())
13373       return true;
13374     ConvArgs[ArgIdx] = InputInit.get();
13375   }
13376 
13377   QualType ResultTy = FD->getReturnType();
13378   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13379   ResultTy = ResultTy.getNonLValueExprType(Context);
13380 
13381   UserDefinedLiteral *UDL =
13382     new (Context) UserDefinedLiteral(Context, Fn.get(),
13383                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13384                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13385 
13386   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13387     return ExprError();
13388 
13389   if (CheckFunctionCall(FD, UDL, nullptr))
13390     return ExprError();
13391 
13392   return MaybeBindToTemporary(UDL);
13393 }
13394 
13395 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13396 /// given LookupResult is non-empty, it is assumed to describe a member which
13397 /// will be invoked. Otherwise, the function will be found via argument
13398 /// dependent lookup.
13399 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13400 /// otherwise CallExpr is set to ExprError() and some non-success value
13401 /// is returned.
13402 Sema::ForRangeStatus
13403 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13404                                 SourceLocation RangeLoc,
13405                                 const DeclarationNameInfo &NameInfo,
13406                                 LookupResult &MemberLookup,
13407                                 OverloadCandidateSet *CandidateSet,
13408                                 Expr *Range, ExprResult *CallExpr) {
13409   Scope *S = nullptr;
13410 
13411   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13412   if (!MemberLookup.empty()) {
13413     ExprResult MemberRef =
13414         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13415                                  /*IsPtr=*/false, CXXScopeSpec(),
13416                                  /*TemplateKWLoc=*/SourceLocation(),
13417                                  /*FirstQualifierInScope=*/nullptr,
13418                                  MemberLookup,
13419                                  /*TemplateArgs=*/nullptr, S);
13420     if (MemberRef.isInvalid()) {
13421       *CallExpr = ExprError();
13422       return FRS_DiagnosticIssued;
13423     }
13424     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13425     if (CallExpr->isInvalid()) {
13426       *CallExpr = ExprError();
13427       return FRS_DiagnosticIssued;
13428     }
13429   } else {
13430     UnresolvedSet<0> FoundNames;
13431     UnresolvedLookupExpr *Fn =
13432       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13433                                    NestedNameSpecifierLoc(), NameInfo,
13434                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13435                                    FoundNames.begin(), FoundNames.end());
13436 
13437     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13438                                                     CandidateSet, CallExpr);
13439     if (CandidateSet->empty() || CandidateSetError) {
13440       *CallExpr = ExprError();
13441       return FRS_NoViableFunction;
13442     }
13443     OverloadCandidateSet::iterator Best;
13444     OverloadingResult OverloadResult =
13445         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13446 
13447     if (OverloadResult == OR_No_Viable_Function) {
13448       *CallExpr = ExprError();
13449       return FRS_NoViableFunction;
13450     }
13451     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13452                                          Loc, nullptr, CandidateSet, &Best,
13453                                          OverloadResult,
13454                                          /*AllowTypoCorrection=*/false);
13455     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13456       *CallExpr = ExprError();
13457       return FRS_DiagnosticIssued;
13458     }
13459   }
13460   return FRS_Success;
13461 }
13462 
13463 
13464 /// FixOverloadedFunctionReference - E is an expression that refers to
13465 /// a C++ overloaded function (possibly with some parentheses and
13466 /// perhaps a '&' around it). We have resolved the overloaded function
13467 /// to the function declaration Fn, so patch up the expression E to
13468 /// refer (possibly indirectly) to Fn. Returns the new expr.
13469 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13470                                            FunctionDecl *Fn) {
13471   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13472     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13473                                                    Found, Fn);
13474     if (SubExpr == PE->getSubExpr())
13475       return PE;
13476 
13477     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13478   }
13479 
13480   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13481     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13482                                                    Found, Fn);
13483     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13484                                SubExpr->getType()) &&
13485            "Implicit cast type cannot be determined from overload");
13486     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13487     if (SubExpr == ICE->getSubExpr())
13488       return ICE;
13489 
13490     return ImplicitCastExpr::Create(Context, ICE->getType(),
13491                                     ICE->getCastKind(),
13492                                     SubExpr, nullptr,
13493                                     ICE->getValueKind());
13494   }
13495 
13496   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13497     if (!GSE->isResultDependent()) {
13498       Expr *SubExpr =
13499           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13500       if (SubExpr == GSE->getResultExpr())
13501         return GSE;
13502 
13503       // Replace the resulting type information before rebuilding the generic
13504       // selection expression.
13505       ArrayRef<Expr *> A = GSE->getAssocExprs();
13506       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13507       unsigned ResultIdx = GSE->getResultIndex();
13508       AssocExprs[ResultIdx] = SubExpr;
13509 
13510       return new (Context) GenericSelectionExpr(
13511           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13512           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13513           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13514           ResultIdx);
13515     }
13516     // Rather than fall through to the unreachable, return the original generic
13517     // selection expression.
13518     return GSE;
13519   }
13520 
13521   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13522     assert(UnOp->getOpcode() == UO_AddrOf &&
13523            "Can only take the address of an overloaded function");
13524     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13525       if (Method->isStatic()) {
13526         // Do nothing: static member functions aren't any different
13527         // from non-member functions.
13528       } else {
13529         // Fix the subexpression, which really has to be an
13530         // UnresolvedLookupExpr holding an overloaded member function
13531         // or template.
13532         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13533                                                        Found, Fn);
13534         if (SubExpr == UnOp->getSubExpr())
13535           return UnOp;
13536 
13537         assert(isa<DeclRefExpr>(SubExpr)
13538                && "fixed to something other than a decl ref");
13539         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13540                && "fixed to a member ref with no nested name qualifier");
13541 
13542         // We have taken the address of a pointer to member
13543         // function. Perform the computation here so that we get the
13544         // appropriate pointer to member type.
13545         QualType ClassType
13546           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13547         QualType MemPtrType
13548           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13549         // Under the MS ABI, lock down the inheritance model now.
13550         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13551           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13552 
13553         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13554                                            VK_RValue, OK_Ordinary,
13555                                            UnOp->getOperatorLoc(), false);
13556       }
13557     }
13558     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13559                                                    Found, Fn);
13560     if (SubExpr == UnOp->getSubExpr())
13561       return UnOp;
13562 
13563     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13564                                      Context.getPointerType(SubExpr->getType()),
13565                                        VK_RValue, OK_Ordinary,
13566                                        UnOp->getOperatorLoc(), false);
13567   }
13568 
13569   // C++ [except.spec]p17:
13570   //   An exception-specification is considered to be needed when:
13571   //   - in an expression the function is the unique lookup result or the
13572   //     selected member of a set of overloaded functions
13573   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13574     ResolveExceptionSpec(E->getExprLoc(), FPT);
13575 
13576   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13577     // FIXME: avoid copy.
13578     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13579     if (ULE->hasExplicitTemplateArgs()) {
13580       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13581       TemplateArgs = &TemplateArgsBuffer;
13582     }
13583 
13584     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13585                                            ULE->getQualifierLoc(),
13586                                            ULE->getTemplateKeywordLoc(),
13587                                            Fn,
13588                                            /*enclosing*/ false, // FIXME?
13589                                            ULE->getNameLoc(),
13590                                            Fn->getType(),
13591                                            VK_LValue,
13592                                            Found.getDecl(),
13593                                            TemplateArgs);
13594     MarkDeclRefReferenced(DRE);
13595     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13596     return DRE;
13597   }
13598 
13599   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13600     // FIXME: avoid copy.
13601     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13602     if (MemExpr->hasExplicitTemplateArgs()) {
13603       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13604       TemplateArgs = &TemplateArgsBuffer;
13605     }
13606 
13607     Expr *Base;
13608 
13609     // If we're filling in a static method where we used to have an
13610     // implicit member access, rewrite to a simple decl ref.
13611     if (MemExpr->isImplicitAccess()) {
13612       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13613         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13614                                                MemExpr->getQualifierLoc(),
13615                                                MemExpr->getTemplateKeywordLoc(),
13616                                                Fn,
13617                                                /*enclosing*/ false,
13618                                                MemExpr->getMemberLoc(),
13619                                                Fn->getType(),
13620                                                VK_LValue,
13621                                                Found.getDecl(),
13622                                                TemplateArgs);
13623         MarkDeclRefReferenced(DRE);
13624         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13625         return DRE;
13626       } else {
13627         SourceLocation Loc = MemExpr->getMemberLoc();
13628         if (MemExpr->getQualifier())
13629           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13630         CheckCXXThisCapture(Loc);
13631         Base = new (Context) CXXThisExpr(Loc,
13632                                          MemExpr->getBaseType(),
13633                                          /*isImplicit=*/true);
13634       }
13635     } else
13636       Base = MemExpr->getBase();
13637 
13638     ExprValueKind valueKind;
13639     QualType type;
13640     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13641       valueKind = VK_LValue;
13642       type = Fn->getType();
13643     } else {
13644       valueKind = VK_RValue;
13645       type = Context.BoundMemberTy;
13646     }
13647 
13648     MemberExpr *ME = MemberExpr::Create(
13649         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13650         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13651         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13652         OK_Ordinary);
13653     ME->setHadMultipleCandidates(true);
13654     MarkMemberReferenced(ME);
13655     return ME;
13656   }
13657 
13658   llvm_unreachable("Invalid reference to overloaded function");
13659 }
13660 
13661 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13662                                                 DeclAccessPair Found,
13663                                                 FunctionDecl *Fn) {
13664   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13665 }
13666