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->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       llvm::APSInt IntConstantValue;
333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334       assert(Initializer && "Unknown conversion expression");
335 
336       // If it's value-dependent, we can't tell whether it's narrowing.
337       if (Initializer->isValueDependent())
338         return NK_Dependent_Narrowing;
339 
340       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
341         // Convert the integer to the floating type.
342         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
343         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
344                                 llvm::APFloat::rmNearestTiesToEven);
345         // And back.
346         llvm::APSInt ConvertedValue = IntConstantValue;
347         bool ignored;
348         Result.convertToInteger(ConvertedValue,
349                                 llvm::APFloat::rmTowardZero, &ignored);
350         // If the resulting value is different, this was a narrowing conversion.
351         if (IntConstantValue != ConvertedValue) {
352           ConstantValue = APValue(IntConstantValue);
353           ConstantType = Initializer->getType();
354           return NK_Constant_Narrowing;
355         }
356       } else {
357         // Variables are always narrowings.
358         return NK_Variable_Narrowing;
359       }
360     }
361     return NK_Not_Narrowing;
362 
363   // -- from long double to double or float, or from double to float, except
364   //    where the source is a constant expression and the actual value after
365   //    conversion is within the range of values that can be represented (even
366   //    if it cannot be represented exactly), or
367   case ICK_Floating_Conversion:
368     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
369         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
370       // FromType is larger than ToType.
371       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
372 
373       // If it's value-dependent, we can't tell whether it's narrowing.
374       if (Initializer->isValueDependent())
375         return NK_Dependent_Narrowing;
376 
377       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
378         // Constant!
379         assert(ConstantValue.isFloat());
380         llvm::APFloat FloatVal = ConstantValue.getFloat();
381         // Convert the source value into the target type.
382         bool ignored;
383         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
384           Ctx.getFloatTypeSemantics(ToType),
385           llvm::APFloat::rmNearestTiesToEven, &ignored);
386         // If there was no overflow, the source value is within the range of
387         // values that can be represented.
388         if (ConvertStatus & llvm::APFloat::opOverflow) {
389           ConstantType = Initializer->getType();
390           return NK_Constant_Narrowing;
391         }
392       } else {
393         return NK_Variable_Narrowing;
394       }
395     }
396     return NK_Not_Narrowing;
397 
398   // -- from an integer type or unscoped enumeration type to an integer type
399   //    that cannot represent all the values of the original type, except where
400   //    the source is a constant expression and the actual value after
401   //    conversion will fit into the target type and will produce the original
402   //    value when converted back to the original type.
403   case ICK_Integral_Conversion:
404   IntegralConversion: {
405     assert(FromType->isIntegralOrUnscopedEnumerationType());
406     assert(ToType->isIntegralOrUnscopedEnumerationType());
407     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
408     const unsigned FromWidth = Ctx.getIntWidth(FromType);
409     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
410     const unsigned ToWidth = Ctx.getIntWidth(ToType);
411 
412     if (FromWidth > ToWidth ||
413         (FromWidth == ToWidth && FromSigned != ToSigned) ||
414         (FromSigned && !ToSigned)) {
415       // Not all values of FromType can be represented in ToType.
416       llvm::APSInt InitializerValue;
417       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
418 
419       // If it's value-dependent, we can't tell whether it's narrowing.
420       if (Initializer->isValueDependent())
421         return NK_Dependent_Narrowing;
422 
423       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
424         // Such conversions on variables are always narrowing.
425         return NK_Variable_Narrowing;
426       }
427       bool Narrowing = false;
428       if (FromWidth < ToWidth) {
429         // Negative -> unsigned is narrowing. Otherwise, more bits is never
430         // narrowing.
431         if (InitializerValue.isSigned() && InitializerValue.isNegative())
432           Narrowing = true;
433       } else {
434         // Add a bit to the InitializerValue so we don't have to worry about
435         // signed vs. unsigned comparisons.
436         InitializerValue = InitializerValue.extend(
437           InitializerValue.getBitWidth() + 1);
438         // Convert the initializer to and from the target width and signed-ness.
439         llvm::APSInt ConvertedValue = InitializerValue;
440         ConvertedValue = ConvertedValue.trunc(ToWidth);
441         ConvertedValue.setIsSigned(ToSigned);
442         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
443         ConvertedValue.setIsSigned(InitializerValue.isSigned());
444         // If the result is different, this was a narrowing conversion.
445         if (ConvertedValue != InitializerValue)
446           Narrowing = true;
447       }
448       if (Narrowing) {
449         ConstantType = Initializer->getType();
450         ConstantValue = APValue(InitializerValue);
451         return NK_Constant_Narrowing;
452       }
453     }
454     return NK_Not_Narrowing;
455   }
456 
457   default:
458     // Other kinds of conversions are not narrowings.
459     return NK_Not_Narrowing;
460   }
461 }
462 
463 /// dump - Print this standard conversion sequence to standard
464 /// error. Useful for debugging overloading issues.
465 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
466   raw_ostream &OS = llvm::errs();
467   bool PrintedSomething = false;
468   if (First != ICK_Identity) {
469     OS << GetImplicitConversionName(First);
470     PrintedSomething = true;
471   }
472 
473   if (Second != ICK_Identity) {
474     if (PrintedSomething) {
475       OS << " -> ";
476     }
477     OS << GetImplicitConversionName(Second);
478 
479     if (CopyConstructor) {
480       OS << " (by copy constructor)";
481     } else if (DirectBinding) {
482       OS << " (direct reference binding)";
483     } else if (ReferenceBinding) {
484       OS << " (reference binding)";
485     }
486     PrintedSomething = true;
487   }
488 
489   if (Third != ICK_Identity) {
490     if (PrintedSomething) {
491       OS << " -> ";
492     }
493     OS << GetImplicitConversionName(Third);
494     PrintedSomething = true;
495   }
496 
497   if (!PrintedSomething) {
498     OS << "No conversions required";
499   }
500 }
501 
502 /// dump - Print this user-defined conversion sequence to standard
503 /// error. Useful for debugging overloading issues.
504 void UserDefinedConversionSequence::dump() const {
505   raw_ostream &OS = llvm::errs();
506   if (Before.First || Before.Second || Before.Third) {
507     Before.dump();
508     OS << " -> ";
509   }
510   if (ConversionFunction)
511     OS << '\'' << *ConversionFunction << '\'';
512   else
513     OS << "aggregate initialization";
514   if (After.First || After.Second || After.Third) {
515     OS << " -> ";
516     After.dump();
517   }
518 }
519 
520 /// dump - Print this implicit conversion sequence to standard
521 /// error. Useful for debugging overloading issues.
522 void ImplicitConversionSequence::dump() const {
523   raw_ostream &OS = llvm::errs();
524   if (isStdInitializerListElement())
525     OS << "Worst std::initializer_list element conversion: ";
526   switch (ConversionKind) {
527   case StandardConversion:
528     OS << "Standard conversion: ";
529     Standard.dump();
530     break;
531   case UserDefinedConversion:
532     OS << "User-defined conversion: ";
533     UserDefined.dump();
534     break;
535   case EllipsisConversion:
536     OS << "Ellipsis conversion";
537     break;
538   case AmbiguousConversion:
539     OS << "Ambiguous conversion";
540     break;
541   case BadConversion:
542     OS << "Bad conversion";
543     break;
544   }
545 
546   OS << "\n";
547 }
548 
549 void AmbiguousConversionSequence::construct() {
550   new (&conversions()) ConversionSet();
551 }
552 
553 void AmbiguousConversionSequence::destruct() {
554   conversions().~ConversionSet();
555 }
556 
557 void
558 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
559   FromTypePtr = O.FromTypePtr;
560   ToTypePtr = O.ToTypePtr;
561   new (&conversions()) ConversionSet(O.conversions());
562 }
563 
564 namespace {
565   // Structure used by DeductionFailureInfo to store
566   // template argument information.
567   struct DFIArguments {
568     TemplateArgument FirstArg;
569     TemplateArgument SecondArg;
570   };
571   // Structure used by DeductionFailureInfo to store
572   // template parameter and template argument information.
573   struct DFIParamWithArguments : DFIArguments {
574     TemplateParameter Param;
575   };
576   // Structure used by DeductionFailureInfo to store template argument
577   // information and the index of the problematic call argument.
578   struct DFIDeducedMismatchArgs : DFIArguments {
579     TemplateArgumentList *TemplateArgs;
580     unsigned CallArgIndex;
581   };
582 }
583 
584 /// \brief Convert from Sema's representation of template deduction information
585 /// to the form used in overload-candidate information.
586 DeductionFailureInfo
587 clang::MakeDeductionFailureInfo(ASTContext &Context,
588                                 Sema::TemplateDeductionResult TDK,
589                                 TemplateDeductionInfo &Info) {
590   DeductionFailureInfo Result;
591   Result.Result = static_cast<unsigned>(TDK);
592   Result.HasDiagnostic = false;
593   switch (TDK) {
594   case Sema::TDK_Invalid:
595   case Sema::TDK_InstantiationDepth:
596   case Sema::TDK_TooManyArguments:
597   case Sema::TDK_TooFewArguments:
598   case Sema::TDK_MiscellaneousDeductionFailure:
599   case Sema::TDK_CUDATargetMismatch:
600     Result.Data = nullptr;
601     break;
602 
603   case Sema::TDK_Incomplete:
604   case Sema::TDK_InvalidExplicitArguments:
605     Result.Data = Info.Param.getOpaqueValue();
606     break;
607 
608   case Sema::TDK_DeducedMismatch:
609   case Sema::TDK_DeducedMismatchNested: {
610     // FIXME: Should allocate from normal heap so that we can free this later.
611     auto *Saved = new (Context) DFIDeducedMismatchArgs;
612     Saved->FirstArg = Info.FirstArg;
613     Saved->SecondArg = Info.SecondArg;
614     Saved->TemplateArgs = Info.take();
615     Saved->CallArgIndex = Info.CallArgIndex;
616     Result.Data = Saved;
617     break;
618   }
619 
620   case Sema::TDK_NonDeducedMismatch: {
621     // FIXME: Should allocate from normal heap so that we can free this later.
622     DFIArguments *Saved = new (Context) DFIArguments;
623     Saved->FirstArg = Info.FirstArg;
624     Saved->SecondArg = Info.SecondArg;
625     Result.Data = Saved;
626     break;
627   }
628 
629   case Sema::TDK_Inconsistent:
630   case Sema::TDK_Underqualified: {
631     // FIXME: Should allocate from normal heap so that we can free this later.
632     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
633     Saved->Param = Info.Param;
634     Saved->FirstArg = Info.FirstArg;
635     Saved->SecondArg = Info.SecondArg;
636     Result.Data = Saved;
637     break;
638   }
639 
640   case Sema::TDK_SubstitutionFailure:
641     Result.Data = Info.take();
642     if (Info.hasSFINAEDiagnostic()) {
643       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
644           SourceLocation(), PartialDiagnostic::NullDiagnostic());
645       Info.takeSFINAEDiagnostic(*Diag);
646       Result.HasDiagnostic = true;
647     }
648     break;
649 
650   case Sema::TDK_Success:
651   case Sema::TDK_NonDependentConversionFailure:
652     llvm_unreachable("not a deduction failure");
653   }
654 
655   return Result;
656 }
657 
658 void DeductionFailureInfo::Destroy() {
659   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
660   case Sema::TDK_Success:
661   case Sema::TDK_Invalid:
662   case Sema::TDK_InstantiationDepth:
663   case Sema::TDK_Incomplete:
664   case Sema::TDK_TooManyArguments:
665   case Sema::TDK_TooFewArguments:
666   case Sema::TDK_InvalidExplicitArguments:
667   case Sema::TDK_CUDATargetMismatch:
668   case Sema::TDK_NonDependentConversionFailure:
669     break;
670 
671   case Sema::TDK_Inconsistent:
672   case Sema::TDK_Underqualified:
673   case Sema::TDK_DeducedMismatch:
674   case Sema::TDK_DeducedMismatchNested:
675   case Sema::TDK_NonDeducedMismatch:
676     // FIXME: Destroy the data?
677     Data = nullptr;
678     break;
679 
680   case Sema::TDK_SubstitutionFailure:
681     // FIXME: Destroy the template argument list?
682     Data = nullptr;
683     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
684       Diag->~PartialDiagnosticAt();
685       HasDiagnostic = false;
686     }
687     break;
688 
689   // Unhandled
690   case Sema::TDK_MiscellaneousDeductionFailure:
691     break;
692   }
693 }
694 
695 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
696   if (HasDiagnostic)
697     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
698   return nullptr;
699 }
700 
701 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
702   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
703   case Sema::TDK_Success:
704   case Sema::TDK_Invalid:
705   case Sema::TDK_InstantiationDepth:
706   case Sema::TDK_TooManyArguments:
707   case Sema::TDK_TooFewArguments:
708   case Sema::TDK_SubstitutionFailure:
709   case Sema::TDK_DeducedMismatch:
710   case Sema::TDK_DeducedMismatchNested:
711   case Sema::TDK_NonDeducedMismatch:
712   case Sema::TDK_CUDATargetMismatch:
713   case Sema::TDK_NonDependentConversionFailure:
714     return TemplateParameter();
715 
716   case Sema::TDK_Incomplete:
717   case Sema::TDK_InvalidExplicitArguments:
718     return TemplateParameter::getFromOpaqueValue(Data);
719 
720   case Sema::TDK_Inconsistent:
721   case Sema::TDK_Underqualified:
722     return static_cast<DFIParamWithArguments*>(Data)->Param;
723 
724   // Unhandled
725   case Sema::TDK_MiscellaneousDeductionFailure:
726     break;
727   }
728 
729   return TemplateParameter();
730 }
731 
732 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
733   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
734   case Sema::TDK_Success:
735   case Sema::TDK_Invalid:
736   case Sema::TDK_InstantiationDepth:
737   case Sema::TDK_TooManyArguments:
738   case Sema::TDK_TooFewArguments:
739   case Sema::TDK_Incomplete:
740   case Sema::TDK_InvalidExplicitArguments:
741   case Sema::TDK_Inconsistent:
742   case Sema::TDK_Underqualified:
743   case Sema::TDK_NonDeducedMismatch:
744   case Sema::TDK_CUDATargetMismatch:
745   case Sema::TDK_NonDependentConversionFailure:
746     return nullptr;
747 
748   case Sema::TDK_DeducedMismatch:
749   case Sema::TDK_DeducedMismatchNested:
750     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
751 
752   case Sema::TDK_SubstitutionFailure:
753     return static_cast<TemplateArgumentList*>(Data);
754 
755   // Unhandled
756   case Sema::TDK_MiscellaneousDeductionFailure:
757     break;
758   }
759 
760   return nullptr;
761 }
762 
763 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
764   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
765   case Sema::TDK_Success:
766   case Sema::TDK_Invalid:
767   case Sema::TDK_InstantiationDepth:
768   case Sema::TDK_Incomplete:
769   case Sema::TDK_TooManyArguments:
770   case Sema::TDK_TooFewArguments:
771   case Sema::TDK_InvalidExplicitArguments:
772   case Sema::TDK_SubstitutionFailure:
773   case Sema::TDK_CUDATargetMismatch:
774   case Sema::TDK_NonDependentConversionFailure:
775     return nullptr;
776 
777   case Sema::TDK_Inconsistent:
778   case Sema::TDK_Underqualified:
779   case Sema::TDK_DeducedMismatch:
780   case Sema::TDK_DeducedMismatchNested:
781   case Sema::TDK_NonDeducedMismatch:
782     return &static_cast<DFIArguments*>(Data)->FirstArg;
783 
784   // Unhandled
785   case Sema::TDK_MiscellaneousDeductionFailure:
786     break;
787   }
788 
789   return nullptr;
790 }
791 
792 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
793   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
794   case Sema::TDK_Success:
795   case Sema::TDK_Invalid:
796   case Sema::TDK_InstantiationDepth:
797   case Sema::TDK_Incomplete:
798   case Sema::TDK_TooManyArguments:
799   case Sema::TDK_TooFewArguments:
800   case Sema::TDK_InvalidExplicitArguments:
801   case Sema::TDK_SubstitutionFailure:
802   case Sema::TDK_CUDATargetMismatch:
803   case Sema::TDK_NonDependentConversionFailure:
804     return nullptr;
805 
806   case Sema::TDK_Inconsistent:
807   case Sema::TDK_Underqualified:
808   case Sema::TDK_DeducedMismatch:
809   case Sema::TDK_DeducedMismatchNested:
810   case Sema::TDK_NonDeducedMismatch:
811     return &static_cast<DFIArguments*>(Data)->SecondArg;
812 
813   // Unhandled
814   case Sema::TDK_MiscellaneousDeductionFailure:
815     break;
816   }
817 
818   return nullptr;
819 }
820 
821 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
822   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
823   case Sema::TDK_DeducedMismatch:
824   case Sema::TDK_DeducedMismatchNested:
825     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
826 
827   default:
828     return llvm::None;
829   }
830 }
831 
832 void OverloadCandidateSet::destroyCandidates() {
833   for (iterator i = begin(), e = end(); i != e; ++i) {
834     for (auto &C : i->Conversions)
835       C.~ImplicitConversionSequence();
836     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
837       i->DeductionFailure.Destroy();
838   }
839 }
840 
841 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
842   destroyCandidates();
843   SlabAllocator.Reset();
844   NumInlineBytesUsed = 0;
845   Candidates.clear();
846   Functions.clear();
847   Kind = CSK;
848 }
849 
850 namespace {
851   class UnbridgedCastsSet {
852     struct Entry {
853       Expr **Addr;
854       Expr *Saved;
855     };
856     SmallVector<Entry, 2> Entries;
857 
858   public:
859     void save(Sema &S, Expr *&E) {
860       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
861       Entry entry = { &E, E };
862       Entries.push_back(entry);
863       E = S.stripARCUnbridgedCast(E);
864     }
865 
866     void restore() {
867       for (SmallVectorImpl<Entry>::iterator
868              i = Entries.begin(), e = Entries.end(); i != e; ++i)
869         *i->Addr = i->Saved;
870     }
871   };
872 }
873 
874 /// checkPlaceholderForOverload - Do any interesting placeholder-like
875 /// preprocessing on the given expression.
876 ///
877 /// \param unbridgedCasts a collection to which to add unbridged casts;
878 ///   without this, they will be immediately diagnosed as errors
879 ///
880 /// Return true on unrecoverable error.
881 static bool
882 checkPlaceholderForOverload(Sema &S, Expr *&E,
883                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
884   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
885     // We can't handle overloaded expressions here because overload
886     // resolution might reasonably tweak them.
887     if (placeholder->getKind() == BuiltinType::Overload) return false;
888 
889     // If the context potentially accepts unbridged ARC casts, strip
890     // the unbridged cast and add it to the collection for later restoration.
891     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
892         unbridgedCasts) {
893       unbridgedCasts->save(S, E);
894       return false;
895     }
896 
897     // Go ahead and check everything else.
898     ExprResult result = S.CheckPlaceholderExpr(E);
899     if (result.isInvalid())
900       return true;
901 
902     E = result.get();
903     return false;
904   }
905 
906   // Nothing to do.
907   return false;
908 }
909 
910 /// checkArgPlaceholdersForOverload - Check a set of call operands for
911 /// placeholders.
912 static bool checkArgPlaceholdersForOverload(Sema &S,
913                                             MultiExprArg Args,
914                                             UnbridgedCastsSet &unbridged) {
915   for (unsigned i = 0, e = Args.size(); i != e; ++i)
916     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
917       return true;
918 
919   return false;
920 }
921 
922 /// Determine whether the given New declaration is an overload of the
923 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
924 /// New and Old cannot be overloaded, e.g., if New has the same signature as
925 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
926 /// functions (or function templates) at all. When it does return Ovl_Match or
927 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
928 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
929 /// declaration.
930 ///
931 /// Example: Given the following input:
932 ///
933 ///   void f(int, float); // #1
934 ///   void f(int, int); // #2
935 ///   int f(int, int); // #3
936 ///
937 /// When we process #1, there is no previous declaration of "f", so IsOverload
938 /// will not be used.
939 ///
940 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
941 /// the parameter types, we see that #1 and #2 are overloaded (since they have
942 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
943 /// unchanged.
944 ///
945 /// When we process #3, Old is an overload set containing #1 and #2. We compare
946 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
947 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
948 /// functions are not part of the signature), IsOverload returns Ovl_Match and
949 /// MatchedDecl will be set to point to the FunctionDecl for #2.
950 ///
951 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
952 /// by a using declaration. The rules for whether to hide shadow declarations
953 /// ignore some properties which otherwise figure into a function template's
954 /// signature.
955 Sema::OverloadKind
956 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
957                     NamedDecl *&Match, bool NewIsUsingDecl) {
958   for (LookupResult::iterator I = Old.begin(), E = Old.end();
959          I != E; ++I) {
960     NamedDecl *OldD = *I;
961 
962     bool OldIsUsingDecl = false;
963     if (isa<UsingShadowDecl>(OldD)) {
964       OldIsUsingDecl = true;
965 
966       // We can always introduce two using declarations into the same
967       // context, even if they have identical signatures.
968       if (NewIsUsingDecl) continue;
969 
970       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
971     }
972 
973     // A using-declaration does not conflict with another declaration
974     // if one of them is hidden.
975     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
976       continue;
977 
978     // If either declaration was introduced by a using declaration,
979     // we'll need to use slightly different rules for matching.
980     // Essentially, these rules are the normal rules, except that
981     // function templates hide function templates with different
982     // return types or template parameter lists.
983     bool UseMemberUsingDeclRules =
984       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
985       !New->getFriendObjectKind();
986 
987     if (FunctionDecl *OldF = OldD->getAsFunction()) {
988       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
989         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
990           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
991           continue;
992         }
993 
994         if (!isa<FunctionTemplateDecl>(OldD) &&
995             !shouldLinkPossiblyHiddenDecl(*I, New))
996           continue;
997 
998         Match = *I;
999         return Ovl_Match;
1000       }
1001     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1002       // We can overload with these, which can show up when doing
1003       // redeclaration checks for UsingDecls.
1004       assert(Old.getLookupKind() == LookupUsingDeclName);
1005     } else if (isa<TagDecl>(OldD)) {
1006       // We can always overload with tags by hiding them.
1007     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1008       // Optimistically assume that an unresolved using decl will
1009       // overload; if it doesn't, we'll have to diagnose during
1010       // template instantiation.
1011       //
1012       // Exception: if the scope is dependent and this is not a class
1013       // member, the using declaration can only introduce an enumerator.
1014       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else {
1019       // (C++ 13p1):
1020       //   Only function declarations can be overloaded; object and type
1021       //   declarations cannot be overloaded.
1022       Match = *I;
1023       return Ovl_NonFunction;
1024     }
1025   }
1026 
1027   return Ovl_Overload;
1028 }
1029 
1030 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1031                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1032   // C++ [basic.start.main]p2: This function shall not be overloaded.
1033   if (New->isMain())
1034     return false;
1035 
1036   // MSVCRT user defined entry points cannot be overloaded.
1037   if (New->isMSVCRTEntryPoint())
1038     return false;
1039 
1040   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1041   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1042 
1043   // C++ [temp.fct]p2:
1044   //   A function template can be overloaded with other function templates
1045   //   and with normal (non-template) functions.
1046   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1047     return true;
1048 
1049   // Is the function New an overload of the function Old?
1050   QualType OldQType = Context.getCanonicalType(Old->getType());
1051   QualType NewQType = Context.getCanonicalType(New->getType());
1052 
1053   // Compare the signatures (C++ 1.3.10) of the two functions to
1054   // determine whether they are overloads. If we find any mismatch
1055   // in the signature, they are overloads.
1056 
1057   // If either of these functions is a K&R-style function (no
1058   // prototype), then we consider them to have matching signatures.
1059   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1060       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1061     return false;
1062 
1063   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1064   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1065 
1066   // The signature of a function includes the types of its
1067   // parameters (C++ 1.3.10), which includes the presence or absence
1068   // of the ellipsis; see C++ DR 357).
1069   if (OldQType != NewQType &&
1070       (OldType->getNumParams() != NewType->getNumParams() ||
1071        OldType->isVariadic() != NewType->isVariadic() ||
1072        !FunctionParamTypesAreEqual(OldType, NewType)))
1073     return true;
1074 
1075   // C++ [temp.over.link]p4:
1076   //   The signature of a function template consists of its function
1077   //   signature, its return type and its template parameter list. The names
1078   //   of the template parameters are significant only for establishing the
1079   //   relationship between the template parameters and the rest of the
1080   //   signature.
1081   //
1082   // We check the return type and template parameter lists for function
1083   // templates first; the remaining checks follow.
1084   //
1085   // However, we don't consider either of these when deciding whether
1086   // a member introduced by a shadow declaration is hidden.
1087   if (!UseMemberUsingDeclRules && NewTemplate &&
1088       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1089                                        OldTemplate->getTemplateParameters(),
1090                                        false, TPL_TemplateMatch) ||
1091        OldType->getReturnType() != NewType->getReturnType()))
1092     return true;
1093 
1094   // If the function is a class member, its signature includes the
1095   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1096   //
1097   // As part of this, also check whether one of the member functions
1098   // is static, in which case they are not overloads (C++
1099   // 13.1p2). While not part of the definition of the signature,
1100   // this check is important to determine whether these functions
1101   // can be overloaded.
1102   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1103   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1104   if (OldMethod && NewMethod &&
1105       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1106     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1107       if (!UseMemberUsingDeclRules &&
1108           (OldMethod->getRefQualifier() == RQ_None ||
1109            NewMethod->getRefQualifier() == RQ_None)) {
1110         // C++0x [over.load]p2:
1111         //   - Member function declarations with the same name and the same
1112         //     parameter-type-list as well as member function template
1113         //     declarations with the same name, the same parameter-type-list, and
1114         //     the same template parameter lists cannot be overloaded if any of
1115         //     them, but not all, have a ref-qualifier (8.3.5).
1116         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1117           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1118         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1119       }
1120       return true;
1121     }
1122 
1123     // We may not have applied the implicit const for a constexpr member
1124     // function yet (because we haven't yet resolved whether this is a static
1125     // or non-static member function). Add it now, on the assumption that this
1126     // is a redeclaration of OldMethod.
1127     unsigned OldQuals = OldMethod->getTypeQualifiers();
1128     unsigned NewQuals = NewMethod->getTypeQualifiers();
1129     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1130         !isa<CXXConstructorDecl>(NewMethod))
1131       NewQuals |= Qualifiers::Const;
1132 
1133     // We do not allow overloading based off of '__restrict'.
1134     OldQuals &= ~Qualifiers::Restrict;
1135     NewQuals &= ~Qualifiers::Restrict;
1136     if (OldQuals != NewQuals)
1137       return true;
1138   }
1139 
1140   // Though pass_object_size is placed on parameters and takes an argument, we
1141   // consider it to be a function-level modifier for the sake of function
1142   // identity. Either the function has one or more parameters with
1143   // pass_object_size or it doesn't.
1144   if (functionHasPassObjectSizeParams(New) !=
1145       functionHasPassObjectSizeParams(Old))
1146     return true;
1147 
1148   // enable_if attributes are an order-sensitive part of the signature.
1149   for (specific_attr_iterator<EnableIfAttr>
1150          NewI = New->specific_attr_begin<EnableIfAttr>(),
1151          NewE = New->specific_attr_end<EnableIfAttr>(),
1152          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1153          OldE = Old->specific_attr_end<EnableIfAttr>();
1154        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1155     if (NewI == NewE || OldI == OldE)
1156       return true;
1157     llvm::FoldingSetNodeID NewID, OldID;
1158     NewI->getCond()->Profile(NewID, Context, true);
1159     OldI->getCond()->Profile(OldID, Context, true);
1160     if (NewID != OldID)
1161       return true;
1162   }
1163 
1164   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1165     // Don't allow overloading of destructors.  (In theory we could, but it
1166     // would be a giant change to clang.)
1167     if (isa<CXXDestructorDecl>(New))
1168       return false;
1169 
1170     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1171                        OldTarget = IdentifyCUDATarget(Old);
1172     if (NewTarget == CFT_InvalidTarget)
1173       return false;
1174 
1175     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1176 
1177     // Allow overloading of functions with same signature and different CUDA
1178     // target attributes.
1179     return NewTarget != OldTarget;
1180   }
1181 
1182   // The signatures match; this is not an overload.
1183   return false;
1184 }
1185 
1186 /// \brief Checks availability of the function depending on the current
1187 /// function context. Inside an unavailable function, unavailability is ignored.
1188 ///
1189 /// \returns true if \arg FD is unavailable and current context is inside
1190 /// an available function, false otherwise.
1191 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1192   if (!FD->isUnavailable())
1193     return false;
1194 
1195   // Walk up the context of the caller.
1196   Decl *C = cast<Decl>(CurContext);
1197   do {
1198     if (C->isUnavailable())
1199       return false;
1200   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1201   return true;
1202 }
1203 
1204 /// \brief Tries a user-defined conversion from From to ToType.
1205 ///
1206 /// Produces an implicit conversion sequence for when a standard conversion
1207 /// is not an option. See TryImplicitConversion for more information.
1208 static ImplicitConversionSequence
1209 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1210                          bool SuppressUserConversions,
1211                          bool AllowExplicit,
1212                          bool InOverloadResolution,
1213                          bool CStyle,
1214                          bool AllowObjCWritebackConversion,
1215                          bool AllowObjCConversionOnExplicit) {
1216   ImplicitConversionSequence ICS;
1217 
1218   if (SuppressUserConversions) {
1219     // We're not in the case above, so there is no conversion that
1220     // we can perform.
1221     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1222     return ICS;
1223   }
1224 
1225   // Attempt user-defined conversion.
1226   OverloadCandidateSet Conversions(From->getExprLoc(),
1227                                    OverloadCandidateSet::CSK_Normal);
1228   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1229                                   Conversions, AllowExplicit,
1230                                   AllowObjCConversionOnExplicit)) {
1231   case OR_Success:
1232   case OR_Deleted:
1233     ICS.setUserDefined();
1234     // C++ [over.ics.user]p4:
1235     //   A conversion of an expression of class type to the same class
1236     //   type is given Exact Match rank, and a conversion of an
1237     //   expression of class type to a base class of that type is
1238     //   given Conversion rank, in spite of the fact that a copy
1239     //   constructor (i.e., a user-defined conversion function) is
1240     //   called for those cases.
1241     if (CXXConstructorDecl *Constructor
1242           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1243       QualType FromCanon
1244         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1245       QualType ToCanon
1246         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1247       if (Constructor->isCopyConstructor() &&
1248           (FromCanon == ToCanon ||
1249            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1250         // Turn this into a "standard" conversion sequence, so that it
1251         // gets ranked with standard conversion sequences.
1252         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1253         ICS.setStandard();
1254         ICS.Standard.setAsIdentityConversion();
1255         ICS.Standard.setFromType(From->getType());
1256         ICS.Standard.setAllToTypes(ToType);
1257         ICS.Standard.CopyConstructor = Constructor;
1258         ICS.Standard.FoundCopyConstructor = Found;
1259         if (ToCanon != FromCanon)
1260           ICS.Standard.Second = ICK_Derived_To_Base;
1261       }
1262     }
1263     break;
1264 
1265   case OR_Ambiguous:
1266     ICS.setAmbiguous();
1267     ICS.Ambiguous.setFromType(From->getType());
1268     ICS.Ambiguous.setToType(ToType);
1269     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1270          Cand != Conversions.end(); ++Cand)
1271       if (Cand->Viable)
1272         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1273     break;
1274 
1275     // Fall through.
1276   case OR_No_Viable_Function:
1277     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1278     break;
1279   }
1280 
1281   return ICS;
1282 }
1283 
1284 /// TryImplicitConversion - Attempt to perform an implicit conversion
1285 /// from the given expression (Expr) to the given type (ToType). This
1286 /// function returns an implicit conversion sequence that can be used
1287 /// to perform the initialization. Given
1288 ///
1289 ///   void f(float f);
1290 ///   void g(int i) { f(i); }
1291 ///
1292 /// this routine would produce an implicit conversion sequence to
1293 /// describe the initialization of f from i, which will be a standard
1294 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1295 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1296 //
1297 /// Note that this routine only determines how the conversion can be
1298 /// performed; it does not actually perform the conversion. As such,
1299 /// it will not produce any diagnostics if no conversion is available,
1300 /// but will instead return an implicit conversion sequence of kind
1301 /// "BadConversion".
1302 ///
1303 /// If @p SuppressUserConversions, then user-defined conversions are
1304 /// not permitted.
1305 /// If @p AllowExplicit, then explicit user-defined conversions are
1306 /// permitted.
1307 ///
1308 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1309 /// writeback conversion, which allows __autoreleasing id* parameters to
1310 /// be initialized with __strong id* or __weak id* arguments.
1311 static ImplicitConversionSequence
1312 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1313                       bool SuppressUserConversions,
1314                       bool AllowExplicit,
1315                       bool InOverloadResolution,
1316                       bool CStyle,
1317                       bool AllowObjCWritebackConversion,
1318                       bool AllowObjCConversionOnExplicit) {
1319   ImplicitConversionSequence ICS;
1320   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1321                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1322     ICS.setStandard();
1323     return ICS;
1324   }
1325 
1326   if (!S.getLangOpts().CPlusPlus) {
1327     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1328     return ICS;
1329   }
1330 
1331   // C++ [over.ics.user]p4:
1332   //   A conversion of an expression of class type to the same class
1333   //   type is given Exact Match rank, and a conversion of an
1334   //   expression of class type to a base class of that type is
1335   //   given Conversion rank, in spite of the fact that a copy/move
1336   //   constructor (i.e., a user-defined conversion function) is
1337   //   called for those cases.
1338   QualType FromType = From->getType();
1339   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1340       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1341        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1342     ICS.setStandard();
1343     ICS.Standard.setAsIdentityConversion();
1344     ICS.Standard.setFromType(FromType);
1345     ICS.Standard.setAllToTypes(ToType);
1346 
1347     // We don't actually check at this point whether there is a valid
1348     // copy/move constructor, since overloading just assumes that it
1349     // exists. When we actually perform initialization, we'll find the
1350     // appropriate constructor to copy the returned object, if needed.
1351     ICS.Standard.CopyConstructor = nullptr;
1352 
1353     // Determine whether this is considered a derived-to-base conversion.
1354     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1355       ICS.Standard.Second = ICK_Derived_To_Base;
1356 
1357     return ICS;
1358   }
1359 
1360   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1361                                   AllowExplicit, InOverloadResolution, CStyle,
1362                                   AllowObjCWritebackConversion,
1363                                   AllowObjCConversionOnExplicit);
1364 }
1365 
1366 ImplicitConversionSequence
1367 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1368                             bool SuppressUserConversions,
1369                             bool AllowExplicit,
1370                             bool InOverloadResolution,
1371                             bool CStyle,
1372                             bool AllowObjCWritebackConversion) {
1373   return ::TryImplicitConversion(*this, From, ToType,
1374                                  SuppressUserConversions, AllowExplicit,
1375                                  InOverloadResolution, CStyle,
1376                                  AllowObjCWritebackConversion,
1377                                  /*AllowObjCConversionOnExplicit=*/false);
1378 }
1379 
1380 /// PerformImplicitConversion - Perform an implicit conversion of the
1381 /// expression From to the type ToType. Returns the
1382 /// converted expression. Flavor is the kind of conversion we're
1383 /// performing, used in the error message. If @p AllowExplicit,
1384 /// explicit user-defined conversions are permitted.
1385 ExprResult
1386 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1387                                 AssignmentAction Action, bool AllowExplicit) {
1388   ImplicitConversionSequence ICS;
1389   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1390 }
1391 
1392 ExprResult
1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1394                                 AssignmentAction Action, bool AllowExplicit,
1395                                 ImplicitConversionSequence& ICS) {
1396   if (checkPlaceholderForOverload(*this, From))
1397     return ExprError();
1398 
1399   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1400   bool AllowObjCWritebackConversion
1401     = getLangOpts().ObjCAutoRefCount &&
1402       (Action == AA_Passing || Action == AA_Sending);
1403   if (getLangOpts().ObjC1)
1404     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1405                                       ToType, From->getType(), From);
1406   ICS = ::TryImplicitConversion(*this, From, ToType,
1407                                 /*SuppressUserConversions=*/false,
1408                                 AllowExplicit,
1409                                 /*InOverloadResolution=*/false,
1410                                 /*CStyle=*/false,
1411                                 AllowObjCWritebackConversion,
1412                                 /*AllowObjCConversionOnExplicit=*/false);
1413   return PerformImplicitConversion(From, ToType, ICS, Action);
1414 }
1415 
1416 /// \brief Determine whether the conversion from FromType to ToType is a valid
1417 /// conversion that strips "noexcept" or "noreturn" off the nested function
1418 /// type.
1419 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1420                                 QualType &ResultTy) {
1421   if (Context.hasSameUnqualifiedType(FromType, ToType))
1422     return false;
1423 
1424   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1425   //                    or F(t noexcept) -> F(t)
1426   // where F adds one of the following at most once:
1427   //   - a pointer
1428   //   - a member pointer
1429   //   - a block pointer
1430   // Changes here need matching changes in FindCompositePointerType.
1431   CanQualType CanTo = Context.getCanonicalType(ToType);
1432   CanQualType CanFrom = Context.getCanonicalType(FromType);
1433   Type::TypeClass TyClass = CanTo->getTypeClass();
1434   if (TyClass != CanFrom->getTypeClass()) return false;
1435   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1436     if (TyClass == Type::Pointer) {
1437       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1438       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1439     } else if (TyClass == Type::BlockPointer) {
1440       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1441       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1442     } else if (TyClass == Type::MemberPointer) {
1443       auto ToMPT = CanTo.getAs<MemberPointerType>();
1444       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1445       // A function pointer conversion cannot change the class of the function.
1446       if (ToMPT->getClass() != FromMPT->getClass())
1447         return false;
1448       CanTo = ToMPT->getPointeeType();
1449       CanFrom = FromMPT->getPointeeType();
1450     } else {
1451       return false;
1452     }
1453 
1454     TyClass = CanTo->getTypeClass();
1455     if (TyClass != CanFrom->getTypeClass()) return false;
1456     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1457       return false;
1458   }
1459 
1460   const auto *FromFn = cast<FunctionType>(CanFrom);
1461   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1462 
1463   const auto *ToFn = cast<FunctionType>(CanTo);
1464   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1465 
1466   bool Changed = false;
1467 
1468   // Drop 'noreturn' if not present in target type.
1469   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1470     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1471     Changed = true;
1472   }
1473 
1474   // Drop 'noexcept' if not present in target type.
1475   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1476     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1477     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1478       FromFn = cast<FunctionType>(
1479           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1480                                                    EST_None)
1481                  .getTypePtr());
1482       Changed = true;
1483     }
1484 
1485     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1486     // only if the ExtParameterInfo lists of the two function prototypes can be
1487     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1488     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1489     bool CanUseToFPT, CanUseFromFPT;
1490     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1491                                       CanUseFromFPT, NewParamInfos) &&
1492         CanUseToFPT && !CanUseFromFPT) {
1493       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1494       ExtInfo.ExtParameterInfos =
1495           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1496       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1497                                             FromFPT->getParamTypes(), ExtInfo);
1498       FromFn = QT->getAs<FunctionType>();
1499       Changed = true;
1500     }
1501   }
1502 
1503   if (!Changed)
1504     return false;
1505 
1506   assert(QualType(FromFn, 0).isCanonical());
1507   if (QualType(FromFn, 0) != CanTo) return false;
1508 
1509   ResultTy = ToType;
1510   return true;
1511 }
1512 
1513 /// \brief Determine whether the conversion from FromType to ToType is a valid
1514 /// vector conversion.
1515 ///
1516 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1517 /// conversion.
1518 static bool IsVectorConversion(Sema &S, QualType FromType,
1519                                QualType ToType, ImplicitConversionKind &ICK) {
1520   // We need at least one of these types to be a vector type to have a vector
1521   // conversion.
1522   if (!ToType->isVectorType() && !FromType->isVectorType())
1523     return false;
1524 
1525   // Identical types require no conversions.
1526   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1527     return false;
1528 
1529   // There are no conversions between extended vector types, only identity.
1530   if (ToType->isExtVectorType()) {
1531     // There are no conversions between extended vector types other than the
1532     // identity conversion.
1533     if (FromType->isExtVectorType())
1534       return false;
1535 
1536     // Vector splat from any arithmetic type to a vector.
1537     if (FromType->isArithmeticType()) {
1538       ICK = ICK_Vector_Splat;
1539       return true;
1540     }
1541   }
1542 
1543   // We can perform the conversion between vector types in the following cases:
1544   // 1)vector types are equivalent AltiVec and GCC vector types
1545   // 2)lax vector conversions are permitted and the vector types are of the
1546   //   same size
1547   if (ToType->isVectorType() && FromType->isVectorType()) {
1548     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1549         S.isLaxVectorConversion(FromType, ToType)) {
1550       ICK = ICK_Vector_Conversion;
1551       return true;
1552     }
1553   }
1554 
1555   return false;
1556 }
1557 
1558 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1559                                 bool InOverloadResolution,
1560                                 StandardConversionSequence &SCS,
1561                                 bool CStyle);
1562 
1563 /// IsStandardConversion - Determines whether there is a standard
1564 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1565 /// expression From to the type ToType. Standard conversion sequences
1566 /// only consider non-class types; for conversions that involve class
1567 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1568 /// contain the standard conversion sequence required to perform this
1569 /// conversion and this routine will return true. Otherwise, this
1570 /// routine will return false and the value of SCS is unspecified.
1571 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1572                                  bool InOverloadResolution,
1573                                  StandardConversionSequence &SCS,
1574                                  bool CStyle,
1575                                  bool AllowObjCWritebackConversion) {
1576   QualType FromType = From->getType();
1577 
1578   // Standard conversions (C++ [conv])
1579   SCS.setAsIdentityConversion();
1580   SCS.IncompatibleObjC = false;
1581   SCS.setFromType(FromType);
1582   SCS.CopyConstructor = nullptr;
1583 
1584   // There are no standard conversions for class types in C++, so
1585   // abort early. When overloading in C, however, we do permit them.
1586   if (S.getLangOpts().CPlusPlus &&
1587       (FromType->isRecordType() || ToType->isRecordType()))
1588     return false;
1589 
1590   // The first conversion can be an lvalue-to-rvalue conversion,
1591   // array-to-pointer conversion, or function-to-pointer conversion
1592   // (C++ 4p1).
1593 
1594   if (FromType == S.Context.OverloadTy) {
1595     DeclAccessPair AccessPair;
1596     if (FunctionDecl *Fn
1597           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1598                                                  AccessPair)) {
1599       // We were able to resolve the address of the overloaded function,
1600       // so we can convert to the type of that function.
1601       FromType = Fn->getType();
1602       SCS.setFromType(FromType);
1603 
1604       // we can sometimes resolve &foo<int> regardless of ToType, so check
1605       // if the type matches (identity) or we are converting to bool
1606       if (!S.Context.hasSameUnqualifiedType(
1607                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1608         QualType resultTy;
1609         // if the function type matches except for [[noreturn]], it's ok
1610         if (!S.IsFunctionConversion(FromType,
1611               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1612           // otherwise, only a boolean conversion is standard
1613           if (!ToType->isBooleanType())
1614             return false;
1615       }
1616 
1617       // Check if the "from" expression is taking the address of an overloaded
1618       // function and recompute the FromType accordingly. Take advantage of the
1619       // fact that non-static member functions *must* have such an address-of
1620       // expression.
1621       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1622       if (Method && !Method->isStatic()) {
1623         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1624                "Non-unary operator on non-static member address");
1625         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1626                == UO_AddrOf &&
1627                "Non-address-of operator on non-static member address");
1628         const Type *ClassType
1629           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1630         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1631       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1632         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1633                UO_AddrOf &&
1634                "Non-address-of operator for overloaded function expression");
1635         FromType = S.Context.getPointerType(FromType);
1636       }
1637 
1638       // Check that we've computed the proper type after overload resolution.
1639       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1640       // be calling it from within an NDEBUG block.
1641       assert(S.Context.hasSameType(
1642         FromType,
1643         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1644     } else {
1645       return false;
1646     }
1647   }
1648   // Lvalue-to-rvalue conversion (C++11 4.1):
1649   //   A glvalue (3.10) of a non-function, non-array type T can
1650   //   be converted to a prvalue.
1651   bool argIsLValue = From->isGLValue();
1652   if (argIsLValue &&
1653       !FromType->isFunctionType() && !FromType->isArrayType() &&
1654       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1655     SCS.First = ICK_Lvalue_To_Rvalue;
1656 
1657     // C11 6.3.2.1p2:
1658     //   ... if the lvalue has atomic type, the value has the non-atomic version
1659     //   of the type of the lvalue ...
1660     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1661       FromType = Atomic->getValueType();
1662 
1663     // If T is a non-class type, the type of the rvalue is the
1664     // cv-unqualified version of T. Otherwise, the type of the rvalue
1665     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1666     // just strip the qualifiers because they don't matter.
1667     FromType = FromType.getUnqualifiedType();
1668   } else if (FromType->isArrayType()) {
1669     // Array-to-pointer conversion (C++ 4.2)
1670     SCS.First = ICK_Array_To_Pointer;
1671 
1672     // An lvalue or rvalue of type "array of N T" or "array of unknown
1673     // bound of T" can be converted to an rvalue of type "pointer to
1674     // T" (C++ 4.2p1).
1675     FromType = S.Context.getArrayDecayedType(FromType);
1676 
1677     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1678       // This conversion is deprecated in C++03 (D.4)
1679       SCS.DeprecatedStringLiteralToCharPtr = true;
1680 
1681       // For the purpose of ranking in overload resolution
1682       // (13.3.3.1.1), this conversion is considered an
1683       // array-to-pointer conversion followed by a qualification
1684       // conversion (4.4). (C++ 4.2p2)
1685       SCS.Second = ICK_Identity;
1686       SCS.Third = ICK_Qualification;
1687       SCS.QualificationIncludesObjCLifetime = false;
1688       SCS.setAllToTypes(FromType);
1689       return true;
1690     }
1691   } else if (FromType->isFunctionType() && argIsLValue) {
1692     // Function-to-pointer conversion (C++ 4.3).
1693     SCS.First = ICK_Function_To_Pointer;
1694 
1695     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1696       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1697         if (!S.checkAddressOfFunctionIsAvailable(FD))
1698           return false;
1699 
1700     // An lvalue of function type T can be converted to an rvalue of
1701     // type "pointer to T." The result is a pointer to the
1702     // function. (C++ 4.3p1).
1703     FromType = S.Context.getPointerType(FromType);
1704   } else {
1705     // We don't require any conversions for the first step.
1706     SCS.First = ICK_Identity;
1707   }
1708   SCS.setToType(0, FromType);
1709 
1710   // The second conversion can be an integral promotion, floating
1711   // point promotion, integral conversion, floating point conversion,
1712   // floating-integral conversion, pointer conversion,
1713   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1714   // For overloading in C, this can also be a "compatible-type"
1715   // conversion.
1716   bool IncompatibleObjC = false;
1717   ImplicitConversionKind SecondICK = ICK_Identity;
1718   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1719     // The unqualified versions of the types are the same: there's no
1720     // conversion to do.
1721     SCS.Second = ICK_Identity;
1722   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1723     // Integral promotion (C++ 4.5).
1724     SCS.Second = ICK_Integral_Promotion;
1725     FromType = ToType.getUnqualifiedType();
1726   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1727     // Floating point promotion (C++ 4.6).
1728     SCS.Second = ICK_Floating_Promotion;
1729     FromType = ToType.getUnqualifiedType();
1730   } else if (S.IsComplexPromotion(FromType, ToType)) {
1731     // Complex promotion (Clang extension)
1732     SCS.Second = ICK_Complex_Promotion;
1733     FromType = ToType.getUnqualifiedType();
1734   } else if (ToType->isBooleanType() &&
1735              (FromType->isArithmeticType() ||
1736               FromType->isAnyPointerType() ||
1737               FromType->isBlockPointerType() ||
1738               FromType->isMemberPointerType() ||
1739               FromType->isNullPtrType())) {
1740     // Boolean conversions (C++ 4.12).
1741     SCS.Second = ICK_Boolean_Conversion;
1742     FromType = S.Context.BoolTy;
1743   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1744              ToType->isIntegralType(S.Context)) {
1745     // Integral conversions (C++ 4.7).
1746     SCS.Second = ICK_Integral_Conversion;
1747     FromType = ToType.getUnqualifiedType();
1748   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1749     // Complex conversions (C99 6.3.1.6)
1750     SCS.Second = ICK_Complex_Conversion;
1751     FromType = ToType.getUnqualifiedType();
1752   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1753              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1754     // Complex-real conversions (C99 6.3.1.7)
1755     SCS.Second = ICK_Complex_Real;
1756     FromType = ToType.getUnqualifiedType();
1757   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1758     // FIXME: disable conversions between long double and __float128 if
1759     // their representation is different until there is back end support
1760     // We of course allow this conversion if long double is really double.
1761     if (&S.Context.getFloatTypeSemantics(FromType) !=
1762         &S.Context.getFloatTypeSemantics(ToType)) {
1763       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1764                                     ToType == S.Context.LongDoubleTy) ||
1765                                    (FromType == S.Context.LongDoubleTy &&
1766                                     ToType == S.Context.Float128Ty));
1767       if (Float128AndLongDouble &&
1768           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1769            &llvm::APFloat::PPCDoubleDouble()))
1770         return false;
1771     }
1772     // Floating point conversions (C++ 4.8).
1773     SCS.Second = ICK_Floating_Conversion;
1774     FromType = ToType.getUnqualifiedType();
1775   } else if ((FromType->isRealFloatingType() &&
1776               ToType->isIntegralType(S.Context)) ||
1777              (FromType->isIntegralOrUnscopedEnumerationType() &&
1778               ToType->isRealFloatingType())) {
1779     // Floating-integral conversions (C++ 4.9).
1780     SCS.Second = ICK_Floating_Integral;
1781     FromType = ToType.getUnqualifiedType();
1782   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1783     SCS.Second = ICK_Block_Pointer_Conversion;
1784   } else if (AllowObjCWritebackConversion &&
1785              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1786     SCS.Second = ICK_Writeback_Conversion;
1787   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1788                                    FromType, IncompatibleObjC)) {
1789     // Pointer conversions (C++ 4.10).
1790     SCS.Second = ICK_Pointer_Conversion;
1791     SCS.IncompatibleObjC = IncompatibleObjC;
1792     FromType = FromType.getUnqualifiedType();
1793   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1794                                          InOverloadResolution, FromType)) {
1795     // Pointer to member conversions (4.11).
1796     SCS.Second = ICK_Pointer_Member;
1797   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1798     SCS.Second = SecondICK;
1799     FromType = ToType.getUnqualifiedType();
1800   } else if (!S.getLangOpts().CPlusPlus &&
1801              S.Context.typesAreCompatible(ToType, FromType)) {
1802     // Compatible conversions (Clang extension for C function overloading)
1803     SCS.Second = ICK_Compatible_Conversion;
1804     FromType = ToType.getUnqualifiedType();
1805   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1806                                              InOverloadResolution,
1807                                              SCS, CStyle)) {
1808     SCS.Second = ICK_TransparentUnionConversion;
1809     FromType = ToType;
1810   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1811                                  CStyle)) {
1812     // tryAtomicConversion has updated the standard conversion sequence
1813     // appropriately.
1814     return true;
1815   } else if (ToType->isEventT() &&
1816              From->isIntegerConstantExpr(S.getASTContext()) &&
1817              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1818     SCS.Second = ICK_Zero_Event_Conversion;
1819     FromType = ToType;
1820   } else if (ToType->isQueueT() &&
1821              From->isIntegerConstantExpr(S.getASTContext()) &&
1822              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1823     SCS.Second = ICK_Zero_Queue_Conversion;
1824     FromType = ToType;
1825   } else {
1826     // No second conversion required.
1827     SCS.Second = ICK_Identity;
1828   }
1829   SCS.setToType(1, FromType);
1830 
1831   // The third conversion can be a function pointer conversion or a
1832   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1833   bool ObjCLifetimeConversion;
1834   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1835     // Function pointer conversions (removing 'noexcept') including removal of
1836     // 'noreturn' (Clang extension).
1837     SCS.Third = ICK_Function_Conversion;
1838   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1839                                          ObjCLifetimeConversion)) {
1840     SCS.Third = ICK_Qualification;
1841     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1842     FromType = ToType;
1843   } else {
1844     // No conversion required
1845     SCS.Third = ICK_Identity;
1846   }
1847 
1848   // C++ [over.best.ics]p6:
1849   //   [...] Any difference in top-level cv-qualification is
1850   //   subsumed by the initialization itself and does not constitute
1851   //   a conversion. [...]
1852   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1853   QualType CanonTo = S.Context.getCanonicalType(ToType);
1854   if (CanonFrom.getLocalUnqualifiedType()
1855                                      == CanonTo.getLocalUnqualifiedType() &&
1856       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1857     FromType = ToType;
1858     CanonFrom = CanonTo;
1859   }
1860 
1861   SCS.setToType(2, FromType);
1862 
1863   if (CanonFrom == CanonTo)
1864     return true;
1865 
1866   // If we have not converted the argument type to the parameter type,
1867   // this is a bad conversion sequence, unless we're resolving an overload in C.
1868   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1869     return false;
1870 
1871   ExprResult ER = ExprResult{From};
1872   Sema::AssignConvertType Conv =
1873       S.CheckSingleAssignmentConstraints(ToType, ER,
1874                                          /*Diagnose=*/false,
1875                                          /*DiagnoseCFAudited=*/false,
1876                                          /*ConvertRHS=*/false);
1877   ImplicitConversionKind SecondConv;
1878   switch (Conv) {
1879   case Sema::Compatible:
1880     SecondConv = ICK_C_Only_Conversion;
1881     break;
1882   // For our purposes, discarding qualifiers is just as bad as using an
1883   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1884   // qualifiers, as well.
1885   case Sema::CompatiblePointerDiscardsQualifiers:
1886   case Sema::IncompatiblePointer:
1887   case Sema::IncompatiblePointerSign:
1888     SecondConv = ICK_Incompatible_Pointer_Conversion;
1889     break;
1890   default:
1891     return false;
1892   }
1893 
1894   // First can only be an lvalue conversion, so we pretend that this was the
1895   // second conversion. First should already be valid from earlier in the
1896   // function.
1897   SCS.Second = SecondConv;
1898   SCS.setToType(1, ToType);
1899 
1900   // Third is Identity, because Second should rank us worse than any other
1901   // conversion. This could also be ICK_Qualification, but it's simpler to just
1902   // lump everything in with the second conversion, and we don't gain anything
1903   // from making this ICK_Qualification.
1904   SCS.Third = ICK_Identity;
1905   SCS.setToType(2, ToType);
1906   return true;
1907 }
1908 
1909 static bool
1910 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1911                                      QualType &ToType,
1912                                      bool InOverloadResolution,
1913                                      StandardConversionSequence &SCS,
1914                                      bool CStyle) {
1915 
1916   const RecordType *UT = ToType->getAsUnionType();
1917   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1918     return false;
1919   // The field to initialize within the transparent union.
1920   RecordDecl *UD = UT->getDecl();
1921   // It's compatible if the expression matches any of the fields.
1922   for (const auto *it : UD->fields()) {
1923     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1924                              CStyle, /*ObjCWritebackConversion=*/false)) {
1925       ToType = it->getType();
1926       return true;
1927     }
1928   }
1929   return false;
1930 }
1931 
1932 /// IsIntegralPromotion - Determines whether the conversion from the
1933 /// expression From (whose potentially-adjusted type is FromType) to
1934 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1935 /// sets PromotedType to the promoted type.
1936 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1937   const BuiltinType *To = ToType->getAs<BuiltinType>();
1938   // All integers are built-in.
1939   if (!To) {
1940     return false;
1941   }
1942 
1943   // An rvalue of type char, signed char, unsigned char, short int, or
1944   // unsigned short int can be converted to an rvalue of type int if
1945   // int can represent all the values of the source type; otherwise,
1946   // the source rvalue can be converted to an rvalue of type unsigned
1947   // int (C++ 4.5p1).
1948   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1949       !FromType->isEnumeralType()) {
1950     if (// We can promote any signed, promotable integer type to an int
1951         (FromType->isSignedIntegerType() ||
1952          // We can promote any unsigned integer type whose size is
1953          // less than int to an int.
1954          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1955       return To->getKind() == BuiltinType::Int;
1956     }
1957 
1958     return To->getKind() == BuiltinType::UInt;
1959   }
1960 
1961   // C++11 [conv.prom]p3:
1962   //   A prvalue of an unscoped enumeration type whose underlying type is not
1963   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1964   //   following types that can represent all the values of the enumeration
1965   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1966   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1967   //   long long int. If none of the types in that list can represent all the
1968   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1969   //   type can be converted to an rvalue a prvalue of the extended integer type
1970   //   with lowest integer conversion rank (4.13) greater than the rank of long
1971   //   long in which all the values of the enumeration can be represented. If
1972   //   there are two such extended types, the signed one is chosen.
1973   // C++11 [conv.prom]p4:
1974   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1975   //   can be converted to a prvalue of its underlying type. Moreover, if
1976   //   integral promotion can be applied to its underlying type, a prvalue of an
1977   //   unscoped enumeration type whose underlying type is fixed can also be
1978   //   converted to a prvalue of the promoted underlying type.
1979   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1980     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1981     // provided for a scoped enumeration.
1982     if (FromEnumType->getDecl()->isScoped())
1983       return false;
1984 
1985     // We can perform an integral promotion to the underlying type of the enum,
1986     // even if that's not the promoted type. Note that the check for promoting
1987     // the underlying type is based on the type alone, and does not consider
1988     // the bitfield-ness of the actual source expression.
1989     if (FromEnumType->getDecl()->isFixed()) {
1990       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1991       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1992              IsIntegralPromotion(nullptr, Underlying, ToType);
1993     }
1994 
1995     // We have already pre-calculated the promotion type, so this is trivial.
1996     if (ToType->isIntegerType() &&
1997         isCompleteType(From->getLocStart(), FromType))
1998       return Context.hasSameUnqualifiedType(
1999           ToType, FromEnumType->getDecl()->getPromotionType());
2000   }
2001 
2002   // C++0x [conv.prom]p2:
2003   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2004   //   to an rvalue a prvalue of the first of the following types that can
2005   //   represent all the values of its underlying type: int, unsigned int,
2006   //   long int, unsigned long int, long long int, or unsigned long long int.
2007   //   If none of the types in that list can represent all the values of its
2008   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2009   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2010   //   type.
2011   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2012       ToType->isIntegerType()) {
2013     // Determine whether the type we're converting from is signed or
2014     // unsigned.
2015     bool FromIsSigned = FromType->isSignedIntegerType();
2016     uint64_t FromSize = Context.getTypeSize(FromType);
2017 
2018     // The types we'll try to promote to, in the appropriate
2019     // order. Try each of these types.
2020     QualType PromoteTypes[6] = {
2021       Context.IntTy, Context.UnsignedIntTy,
2022       Context.LongTy, Context.UnsignedLongTy ,
2023       Context.LongLongTy, Context.UnsignedLongLongTy
2024     };
2025     for (int Idx = 0; Idx < 6; ++Idx) {
2026       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2027       if (FromSize < ToSize ||
2028           (FromSize == ToSize &&
2029            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2030         // We found the type that we can promote to. If this is the
2031         // type we wanted, we have a promotion. Otherwise, no
2032         // promotion.
2033         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2034       }
2035     }
2036   }
2037 
2038   // An rvalue for an integral bit-field (9.6) can be converted to an
2039   // rvalue of type int if int can represent all the values of the
2040   // bit-field; otherwise, it can be converted to unsigned int if
2041   // unsigned int can represent all the values of the bit-field. If
2042   // the bit-field is larger yet, no integral promotion applies to
2043   // it. If the bit-field has an enumerated type, it is treated as any
2044   // other value of that type for promotion purposes (C++ 4.5p3).
2045   // FIXME: We should delay checking of bit-fields until we actually perform the
2046   // conversion.
2047   if (From) {
2048     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2049       llvm::APSInt BitWidth;
2050       if (FromType->isIntegralType(Context) &&
2051           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2052         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2053         ToSize = Context.getTypeSize(ToType);
2054 
2055         // Are we promoting to an int from a bitfield that fits in an int?
2056         if (BitWidth < ToSize ||
2057             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2058           return To->getKind() == BuiltinType::Int;
2059         }
2060 
2061         // Are we promoting to an unsigned int from an unsigned bitfield
2062         // that fits into an unsigned int?
2063         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2064           return To->getKind() == BuiltinType::UInt;
2065         }
2066 
2067         return false;
2068       }
2069     }
2070   }
2071 
2072   // An rvalue of type bool can be converted to an rvalue of type int,
2073   // with false becoming zero and true becoming one (C++ 4.5p4).
2074   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2075     return true;
2076   }
2077 
2078   return false;
2079 }
2080 
2081 /// IsFloatingPointPromotion - Determines whether the conversion from
2082 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2083 /// returns true and sets PromotedType to the promoted type.
2084 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2085   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2086     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2087       /// An rvalue of type float can be converted to an rvalue of type
2088       /// double. (C++ 4.6p1).
2089       if (FromBuiltin->getKind() == BuiltinType::Float &&
2090           ToBuiltin->getKind() == BuiltinType::Double)
2091         return true;
2092 
2093       // C99 6.3.1.5p1:
2094       //   When a float is promoted to double or long double, or a
2095       //   double is promoted to long double [...].
2096       if (!getLangOpts().CPlusPlus &&
2097           (FromBuiltin->getKind() == BuiltinType::Float ||
2098            FromBuiltin->getKind() == BuiltinType::Double) &&
2099           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2100            ToBuiltin->getKind() == BuiltinType::Float128))
2101         return true;
2102 
2103       // Half can be promoted to float.
2104       if (!getLangOpts().NativeHalfType &&
2105            FromBuiltin->getKind() == BuiltinType::Half &&
2106           ToBuiltin->getKind() == BuiltinType::Float)
2107         return true;
2108     }
2109 
2110   return false;
2111 }
2112 
2113 /// \brief Determine if a conversion is a complex promotion.
2114 ///
2115 /// A complex promotion is defined as a complex -> complex conversion
2116 /// where the conversion between the underlying real types is a
2117 /// floating-point or integral promotion.
2118 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2119   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2120   if (!FromComplex)
2121     return false;
2122 
2123   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2124   if (!ToComplex)
2125     return false;
2126 
2127   return IsFloatingPointPromotion(FromComplex->getElementType(),
2128                                   ToComplex->getElementType()) ||
2129     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2130                         ToComplex->getElementType());
2131 }
2132 
2133 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2134 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2135 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2136 /// if non-empty, will be a pointer to ToType that may or may not have
2137 /// the right set of qualifiers on its pointee.
2138 ///
2139 static QualType
2140 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2141                                    QualType ToPointee, QualType ToType,
2142                                    ASTContext &Context,
2143                                    bool StripObjCLifetime = false) {
2144   assert((FromPtr->getTypeClass() == Type::Pointer ||
2145           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2146          "Invalid similarly-qualified pointer type");
2147 
2148   /// Conversions to 'id' subsume cv-qualifier conversions.
2149   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2150     return ToType.getUnqualifiedType();
2151 
2152   QualType CanonFromPointee
2153     = Context.getCanonicalType(FromPtr->getPointeeType());
2154   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2155   Qualifiers Quals = CanonFromPointee.getQualifiers();
2156 
2157   if (StripObjCLifetime)
2158     Quals.removeObjCLifetime();
2159 
2160   // Exact qualifier match -> return the pointer type we're converting to.
2161   if (CanonToPointee.getLocalQualifiers() == Quals) {
2162     // ToType is exactly what we need. Return it.
2163     if (!ToType.isNull())
2164       return ToType.getUnqualifiedType();
2165 
2166     // Build a pointer to ToPointee. It has the right qualifiers
2167     // already.
2168     if (isa<ObjCObjectPointerType>(ToType))
2169       return Context.getObjCObjectPointerType(ToPointee);
2170     return Context.getPointerType(ToPointee);
2171   }
2172 
2173   // Just build a canonical type that has the right qualifiers.
2174   QualType QualifiedCanonToPointee
2175     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2176 
2177   if (isa<ObjCObjectPointerType>(ToType))
2178     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2179   return Context.getPointerType(QualifiedCanonToPointee);
2180 }
2181 
2182 static bool isNullPointerConstantForConversion(Expr *Expr,
2183                                                bool InOverloadResolution,
2184                                                ASTContext &Context) {
2185   // Handle value-dependent integral null pointer constants correctly.
2186   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2187   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2188       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2189     return !InOverloadResolution;
2190 
2191   return Expr->isNullPointerConstant(Context,
2192                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2193                                         : Expr::NPC_ValueDependentIsNull);
2194 }
2195 
2196 /// IsPointerConversion - Determines whether the conversion of the
2197 /// expression From, which has the (possibly adjusted) type FromType,
2198 /// can be converted to the type ToType via a pointer conversion (C++
2199 /// 4.10). If so, returns true and places the converted type (that
2200 /// might differ from ToType in its cv-qualifiers at some level) into
2201 /// ConvertedType.
2202 ///
2203 /// This routine also supports conversions to and from block pointers
2204 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2205 /// pointers to interfaces. FIXME: Once we've determined the
2206 /// appropriate overloading rules for Objective-C, we may want to
2207 /// split the Objective-C checks into a different routine; however,
2208 /// GCC seems to consider all of these conversions to be pointer
2209 /// conversions, so for now they live here. IncompatibleObjC will be
2210 /// set if the conversion is an allowed Objective-C conversion that
2211 /// should result in a warning.
2212 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2213                                bool InOverloadResolution,
2214                                QualType& ConvertedType,
2215                                bool &IncompatibleObjC) {
2216   IncompatibleObjC = false;
2217   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2218                               IncompatibleObjC))
2219     return true;
2220 
2221   // Conversion from a null pointer constant to any Objective-C pointer type.
2222   if (ToType->isObjCObjectPointerType() &&
2223       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2224     ConvertedType = ToType;
2225     return true;
2226   }
2227 
2228   // Blocks: Block pointers can be converted to void*.
2229   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2230       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2231     ConvertedType = ToType;
2232     return true;
2233   }
2234   // Blocks: A null pointer constant can be converted to a block
2235   // pointer type.
2236   if (ToType->isBlockPointerType() &&
2237       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2238     ConvertedType = ToType;
2239     return true;
2240   }
2241 
2242   // If the left-hand-side is nullptr_t, the right side can be a null
2243   // pointer constant.
2244   if (ToType->isNullPtrType() &&
2245       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2246     ConvertedType = ToType;
2247     return true;
2248   }
2249 
2250   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2251   if (!ToTypePtr)
2252     return false;
2253 
2254   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2255   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2256     ConvertedType = ToType;
2257     return true;
2258   }
2259 
2260   // Beyond this point, both types need to be pointers
2261   // , including objective-c pointers.
2262   QualType ToPointeeType = ToTypePtr->getPointeeType();
2263   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2264       !getLangOpts().ObjCAutoRefCount) {
2265     ConvertedType = BuildSimilarlyQualifiedPointerType(
2266                                       FromType->getAs<ObjCObjectPointerType>(),
2267                                                        ToPointeeType,
2268                                                        ToType, Context);
2269     return true;
2270   }
2271   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2272   if (!FromTypePtr)
2273     return false;
2274 
2275   QualType FromPointeeType = FromTypePtr->getPointeeType();
2276 
2277   // If the unqualified pointee types are the same, this can't be a
2278   // pointer conversion, so don't do all of the work below.
2279   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2280     return false;
2281 
2282   // An rvalue of type "pointer to cv T," where T is an object type,
2283   // can be converted to an rvalue of type "pointer to cv void" (C++
2284   // 4.10p2).
2285   if (FromPointeeType->isIncompleteOrObjectType() &&
2286       ToPointeeType->isVoidType()) {
2287     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2288                                                        ToPointeeType,
2289                                                        ToType, Context,
2290                                                    /*StripObjCLifetime=*/true);
2291     return true;
2292   }
2293 
2294   // MSVC allows implicit function to void* type conversion.
2295   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2296       ToPointeeType->isVoidType()) {
2297     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2298                                                        ToPointeeType,
2299                                                        ToType, Context);
2300     return true;
2301   }
2302 
2303   // When we're overloading in C, we allow a special kind of pointer
2304   // conversion for compatible-but-not-identical pointee types.
2305   if (!getLangOpts().CPlusPlus &&
2306       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2307     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2308                                                        ToPointeeType,
2309                                                        ToType, Context);
2310     return true;
2311   }
2312 
2313   // C++ [conv.ptr]p3:
2314   //
2315   //   An rvalue of type "pointer to cv D," where D is a class type,
2316   //   can be converted to an rvalue of type "pointer to cv B," where
2317   //   B is a base class (clause 10) of D. If B is an inaccessible
2318   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2319   //   necessitates this conversion is ill-formed. The result of the
2320   //   conversion is a pointer to the base class sub-object of the
2321   //   derived class object. The null pointer value is converted to
2322   //   the null pointer value of the destination type.
2323   //
2324   // Note that we do not check for ambiguity or inaccessibility
2325   // here. That is handled by CheckPointerConversion.
2326   if (getLangOpts().CPlusPlus &&
2327       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2328       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2329       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2330     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331                                                        ToPointeeType,
2332                                                        ToType, Context);
2333     return true;
2334   }
2335 
2336   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2337       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343 
2344   return false;
2345 }
2346 
2347 /// \brief Adopt the given qualifiers for the given type.
2348 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2349   Qualifiers TQs = T.getQualifiers();
2350 
2351   // Check whether qualifiers already match.
2352   if (TQs == Qs)
2353     return T;
2354 
2355   if (Qs.compatiblyIncludes(TQs))
2356     return Context.getQualifiedType(T, Qs);
2357 
2358   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2359 }
2360 
2361 /// isObjCPointerConversion - Determines whether this is an
2362 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2363 /// with the same arguments and return values.
2364 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2365                                    QualType& ConvertedType,
2366                                    bool &IncompatibleObjC) {
2367   if (!getLangOpts().ObjC1)
2368     return false;
2369 
2370   // The set of qualifiers on the type we're converting from.
2371   Qualifiers FromQualifiers = FromType.getQualifiers();
2372 
2373   // First, we handle all conversions on ObjC object pointer types.
2374   const ObjCObjectPointerType* ToObjCPtr =
2375     ToType->getAs<ObjCObjectPointerType>();
2376   const ObjCObjectPointerType *FromObjCPtr =
2377     FromType->getAs<ObjCObjectPointerType>();
2378 
2379   if (ToObjCPtr && FromObjCPtr) {
2380     // If the pointee types are the same (ignoring qualifications),
2381     // then this is not a pointer conversion.
2382     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2383                                        FromObjCPtr->getPointeeType()))
2384       return false;
2385 
2386     // Conversion between Objective-C pointers.
2387     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2388       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2389       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2390       if (getLangOpts().CPlusPlus && LHS && RHS &&
2391           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2392                                                 FromObjCPtr->getPointeeType()))
2393         return false;
2394       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2395                                                    ToObjCPtr->getPointeeType(),
2396                                                          ToType, Context);
2397       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2398       return true;
2399     }
2400 
2401     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2402       // Okay: this is some kind of implicit downcast of Objective-C
2403       // interfaces, which is permitted. However, we're going to
2404       // complain about it.
2405       IncompatibleObjC = true;
2406       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2407                                                    ToObjCPtr->getPointeeType(),
2408                                                          ToType, Context);
2409       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2410       return true;
2411     }
2412   }
2413   // Beyond this point, both types need to be C pointers or block pointers.
2414   QualType ToPointeeType;
2415   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2416     ToPointeeType = ToCPtr->getPointeeType();
2417   else if (const BlockPointerType *ToBlockPtr =
2418             ToType->getAs<BlockPointerType>()) {
2419     // Objective C++: We're able to convert from a pointer to any object
2420     // to a block pointer type.
2421     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2422       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2423       return true;
2424     }
2425     ToPointeeType = ToBlockPtr->getPointeeType();
2426   }
2427   else if (FromType->getAs<BlockPointerType>() &&
2428            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2429     // Objective C++: We're able to convert from a block pointer type to a
2430     // pointer to any object.
2431     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2432     return true;
2433   }
2434   else
2435     return false;
2436 
2437   QualType FromPointeeType;
2438   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2439     FromPointeeType = FromCPtr->getPointeeType();
2440   else if (const BlockPointerType *FromBlockPtr =
2441            FromType->getAs<BlockPointerType>())
2442     FromPointeeType = FromBlockPtr->getPointeeType();
2443   else
2444     return false;
2445 
2446   // If we have pointers to pointers, recursively check whether this
2447   // is an Objective-C conversion.
2448   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2449       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2450                               IncompatibleObjC)) {
2451     // We always complain about this conversion.
2452     IncompatibleObjC = true;
2453     ConvertedType = Context.getPointerType(ConvertedType);
2454     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2455     return true;
2456   }
2457   // Allow conversion of pointee being objective-c pointer to another one;
2458   // as in I* to id.
2459   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2460       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2461       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2462                               IncompatibleObjC)) {
2463 
2464     ConvertedType = Context.getPointerType(ConvertedType);
2465     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2466     return true;
2467   }
2468 
2469   // If we have pointers to functions or blocks, check whether the only
2470   // differences in the argument and result types are in Objective-C
2471   // pointer conversions. If so, we permit the conversion (but
2472   // complain about it).
2473   const FunctionProtoType *FromFunctionType
2474     = FromPointeeType->getAs<FunctionProtoType>();
2475   const FunctionProtoType *ToFunctionType
2476     = ToPointeeType->getAs<FunctionProtoType>();
2477   if (FromFunctionType && ToFunctionType) {
2478     // If the function types are exactly the same, this isn't an
2479     // Objective-C pointer conversion.
2480     if (Context.getCanonicalType(FromPointeeType)
2481           == Context.getCanonicalType(ToPointeeType))
2482       return false;
2483 
2484     // Perform the quick checks that will tell us whether these
2485     // function types are obviously different.
2486     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2487         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2488         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2489       return false;
2490 
2491     bool HasObjCConversion = false;
2492     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2493         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2494       // Okay, the types match exactly. Nothing to do.
2495     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2496                                        ToFunctionType->getReturnType(),
2497                                        ConvertedType, IncompatibleObjC)) {
2498       // Okay, we have an Objective-C pointer conversion.
2499       HasObjCConversion = true;
2500     } else {
2501       // Function types are too different. Abort.
2502       return false;
2503     }
2504 
2505     // Check argument types.
2506     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2507          ArgIdx != NumArgs; ++ArgIdx) {
2508       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2509       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2510       if (Context.getCanonicalType(FromArgType)
2511             == Context.getCanonicalType(ToArgType)) {
2512         // Okay, the types match exactly. Nothing to do.
2513       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2514                                          ConvertedType, IncompatibleObjC)) {
2515         // Okay, we have an Objective-C pointer conversion.
2516         HasObjCConversion = true;
2517       } else {
2518         // Argument types are too different. Abort.
2519         return false;
2520       }
2521     }
2522 
2523     if (HasObjCConversion) {
2524       // We had an Objective-C conversion. Allow this pointer
2525       // conversion, but complain about it.
2526       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2527       IncompatibleObjC = true;
2528       return true;
2529     }
2530   }
2531 
2532   return false;
2533 }
2534 
2535 /// \brief Determine whether this is an Objective-C writeback conversion,
2536 /// used for parameter passing when performing automatic reference counting.
2537 ///
2538 /// \param FromType The type we're converting form.
2539 ///
2540 /// \param ToType The type we're converting to.
2541 ///
2542 /// \param ConvertedType The type that will be produced after applying
2543 /// this conversion.
2544 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2545                                      QualType &ConvertedType) {
2546   if (!getLangOpts().ObjCAutoRefCount ||
2547       Context.hasSameUnqualifiedType(FromType, ToType))
2548     return false;
2549 
2550   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2551   QualType ToPointee;
2552   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2553     ToPointee = ToPointer->getPointeeType();
2554   else
2555     return false;
2556 
2557   Qualifiers ToQuals = ToPointee.getQualifiers();
2558   if (!ToPointee->isObjCLifetimeType() ||
2559       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2560       !ToQuals.withoutObjCLifetime().empty())
2561     return false;
2562 
2563   // Argument must be a pointer to __strong to __weak.
2564   QualType FromPointee;
2565   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2566     FromPointee = FromPointer->getPointeeType();
2567   else
2568     return false;
2569 
2570   Qualifiers FromQuals = FromPointee.getQualifiers();
2571   if (!FromPointee->isObjCLifetimeType() ||
2572       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2573        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2574     return false;
2575 
2576   // Make sure that we have compatible qualifiers.
2577   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2578   if (!ToQuals.compatiblyIncludes(FromQuals))
2579     return false;
2580 
2581   // Remove qualifiers from the pointee type we're converting from; they
2582   // aren't used in the compatibility check belong, and we'll be adding back
2583   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2584   FromPointee = FromPointee.getUnqualifiedType();
2585 
2586   // The unqualified form of the pointee types must be compatible.
2587   ToPointee = ToPointee.getUnqualifiedType();
2588   bool IncompatibleObjC;
2589   if (Context.typesAreCompatible(FromPointee, ToPointee))
2590     FromPointee = ToPointee;
2591   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2592                                     IncompatibleObjC))
2593     return false;
2594 
2595   /// \brief Construct the type we're converting to, which is a pointer to
2596   /// __autoreleasing pointee.
2597   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2598   ConvertedType = Context.getPointerType(FromPointee);
2599   return true;
2600 }
2601 
2602 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2603                                     QualType& ConvertedType) {
2604   QualType ToPointeeType;
2605   if (const BlockPointerType *ToBlockPtr =
2606         ToType->getAs<BlockPointerType>())
2607     ToPointeeType = ToBlockPtr->getPointeeType();
2608   else
2609     return false;
2610 
2611   QualType FromPointeeType;
2612   if (const BlockPointerType *FromBlockPtr =
2613       FromType->getAs<BlockPointerType>())
2614     FromPointeeType = FromBlockPtr->getPointeeType();
2615   else
2616     return false;
2617   // We have pointer to blocks, check whether the only
2618   // differences in the argument and result types are in Objective-C
2619   // pointer conversions. If so, we permit the conversion.
2620 
2621   const FunctionProtoType *FromFunctionType
2622     = FromPointeeType->getAs<FunctionProtoType>();
2623   const FunctionProtoType *ToFunctionType
2624     = ToPointeeType->getAs<FunctionProtoType>();
2625 
2626   if (!FromFunctionType || !ToFunctionType)
2627     return false;
2628 
2629   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2630     return true;
2631 
2632   // Perform the quick checks that will tell us whether these
2633   // function types are obviously different.
2634   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2635       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2636     return false;
2637 
2638   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2639   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2640   if (FromEInfo != ToEInfo)
2641     return false;
2642 
2643   bool IncompatibleObjC = false;
2644   if (Context.hasSameType(FromFunctionType->getReturnType(),
2645                           ToFunctionType->getReturnType())) {
2646     // Okay, the types match exactly. Nothing to do.
2647   } else {
2648     QualType RHS = FromFunctionType->getReturnType();
2649     QualType LHS = ToFunctionType->getReturnType();
2650     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2651         !RHS.hasQualifiers() && LHS.hasQualifiers())
2652        LHS = LHS.getUnqualifiedType();
2653 
2654      if (Context.hasSameType(RHS,LHS)) {
2655        // OK exact match.
2656      } else if (isObjCPointerConversion(RHS, LHS,
2657                                         ConvertedType, IncompatibleObjC)) {
2658      if (IncompatibleObjC)
2659        return false;
2660      // Okay, we have an Objective-C pointer conversion.
2661      }
2662      else
2663        return false;
2664    }
2665 
2666    // Check argument types.
2667    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2668         ArgIdx != NumArgs; ++ArgIdx) {
2669      IncompatibleObjC = false;
2670      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2671      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2672      if (Context.hasSameType(FromArgType, ToArgType)) {
2673        // Okay, the types match exactly. Nothing to do.
2674      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2675                                         ConvertedType, IncompatibleObjC)) {
2676        if (IncompatibleObjC)
2677          return false;
2678        // Okay, we have an Objective-C pointer conversion.
2679      } else
2680        // Argument types are too different. Abort.
2681        return false;
2682    }
2683 
2684    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2685    bool CanUseToFPT, CanUseFromFPT;
2686    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2687                                       CanUseToFPT, CanUseFromFPT,
2688                                       NewParamInfos))
2689      return false;
2690 
2691    ConvertedType = ToType;
2692    return true;
2693 }
2694 
2695 enum {
2696   ft_default,
2697   ft_different_class,
2698   ft_parameter_arity,
2699   ft_parameter_mismatch,
2700   ft_return_type,
2701   ft_qualifer_mismatch,
2702   ft_noexcept
2703 };
2704 
2705 /// Attempts to get the FunctionProtoType from a Type. Handles
2706 /// MemberFunctionPointers properly.
2707 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2708   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2709     return FPT;
2710 
2711   if (auto *MPT = FromType->getAs<MemberPointerType>())
2712     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2713 
2714   return nullptr;
2715 }
2716 
2717 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2718 /// function types.  Catches different number of parameter, mismatch in
2719 /// parameter types, and different return types.
2720 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2721                                       QualType FromType, QualType ToType) {
2722   // If either type is not valid, include no extra info.
2723   if (FromType.isNull() || ToType.isNull()) {
2724     PDiag << ft_default;
2725     return;
2726   }
2727 
2728   // Get the function type from the pointers.
2729   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2730     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2731                             *ToMember = ToType->getAs<MemberPointerType>();
2732     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2733       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2734             << QualType(FromMember->getClass(), 0);
2735       return;
2736     }
2737     FromType = FromMember->getPointeeType();
2738     ToType = ToMember->getPointeeType();
2739   }
2740 
2741   if (FromType->isPointerType())
2742     FromType = FromType->getPointeeType();
2743   if (ToType->isPointerType())
2744     ToType = ToType->getPointeeType();
2745 
2746   // Remove references.
2747   FromType = FromType.getNonReferenceType();
2748   ToType = ToType.getNonReferenceType();
2749 
2750   // Don't print extra info for non-specialized template functions.
2751   if (FromType->isInstantiationDependentType() &&
2752       !FromType->getAs<TemplateSpecializationType>()) {
2753     PDiag << ft_default;
2754     return;
2755   }
2756 
2757   // No extra info for same types.
2758   if (Context.hasSameType(FromType, ToType)) {
2759     PDiag << ft_default;
2760     return;
2761   }
2762 
2763   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2764                           *ToFunction = tryGetFunctionProtoType(ToType);
2765 
2766   // Both types need to be function types.
2767   if (!FromFunction || !ToFunction) {
2768     PDiag << ft_default;
2769     return;
2770   }
2771 
2772   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2773     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2774           << FromFunction->getNumParams();
2775     return;
2776   }
2777 
2778   // Handle different parameter types.
2779   unsigned ArgPos;
2780   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2781     PDiag << ft_parameter_mismatch << ArgPos + 1
2782           << ToFunction->getParamType(ArgPos)
2783           << FromFunction->getParamType(ArgPos);
2784     return;
2785   }
2786 
2787   // Handle different return type.
2788   if (!Context.hasSameType(FromFunction->getReturnType(),
2789                            ToFunction->getReturnType())) {
2790     PDiag << ft_return_type << ToFunction->getReturnType()
2791           << FromFunction->getReturnType();
2792     return;
2793   }
2794 
2795   unsigned FromQuals = FromFunction->getTypeQuals(),
2796            ToQuals = ToFunction->getTypeQuals();
2797   if (FromQuals != ToQuals) {
2798     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2799     return;
2800   }
2801 
2802   // Handle exception specification differences on canonical type (in C++17
2803   // onwards).
2804   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2805           ->isNothrow(Context) !=
2806       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2807           ->isNothrow(Context)) {
2808     PDiag << ft_noexcept;
2809     return;
2810   }
2811 
2812   // Unable to find a difference, so add no extra info.
2813   PDiag << ft_default;
2814 }
2815 
2816 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2817 /// for equality of their argument types. Caller has already checked that
2818 /// they have same number of arguments.  If the parameters are different,
2819 /// ArgPos will have the parameter index of the first different parameter.
2820 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2821                                       const FunctionProtoType *NewType,
2822                                       unsigned *ArgPos) {
2823   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2824                                               N = NewType->param_type_begin(),
2825                                               E = OldType->param_type_end();
2826        O && (O != E); ++O, ++N) {
2827     if (!Context.hasSameType(O->getUnqualifiedType(),
2828                              N->getUnqualifiedType())) {
2829       if (ArgPos)
2830         *ArgPos = O - OldType->param_type_begin();
2831       return false;
2832     }
2833   }
2834   return true;
2835 }
2836 
2837 /// CheckPointerConversion - Check the pointer conversion from the
2838 /// expression From to the type ToType. This routine checks for
2839 /// ambiguous or inaccessible derived-to-base pointer
2840 /// conversions for which IsPointerConversion has already returned
2841 /// true. It returns true and produces a diagnostic if there was an
2842 /// error, or returns false otherwise.
2843 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2844                                   CastKind &Kind,
2845                                   CXXCastPath& BasePath,
2846                                   bool IgnoreBaseAccess,
2847                                   bool Diagnose) {
2848   QualType FromType = From->getType();
2849   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2850 
2851   Kind = CK_BitCast;
2852 
2853   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2854       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2855           Expr::NPCK_ZeroExpression) {
2856     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2857       DiagRuntimeBehavior(From->getExprLoc(), From,
2858                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2859                             << ToType << From->getSourceRange());
2860     else if (!isUnevaluatedContext())
2861       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2862         << ToType << From->getSourceRange();
2863   }
2864   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2865     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2866       QualType FromPointeeType = FromPtrType->getPointeeType(),
2867                ToPointeeType   = ToPtrType->getPointeeType();
2868 
2869       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2870           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2871         // We must have a derived-to-base conversion. Check an
2872         // ambiguous or inaccessible conversion.
2873         unsigned InaccessibleID = 0;
2874         unsigned AmbigiousID = 0;
2875         if (Diagnose) {
2876           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2877           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2878         }
2879         if (CheckDerivedToBaseConversion(
2880                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2881                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2882                 &BasePath, IgnoreBaseAccess))
2883           return true;
2884 
2885         // The conversion was successful.
2886         Kind = CK_DerivedToBase;
2887       }
2888 
2889       if (Diagnose && !IsCStyleOrFunctionalCast &&
2890           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2891         assert(getLangOpts().MSVCCompat &&
2892                "this should only be possible with MSVCCompat!");
2893         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2894             << From->getSourceRange();
2895       }
2896     }
2897   } else if (const ObjCObjectPointerType *ToPtrType =
2898                ToType->getAs<ObjCObjectPointerType>()) {
2899     if (const ObjCObjectPointerType *FromPtrType =
2900           FromType->getAs<ObjCObjectPointerType>()) {
2901       // Objective-C++ conversions are always okay.
2902       // FIXME: We should have a different class of conversions for the
2903       // Objective-C++ implicit conversions.
2904       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2905         return false;
2906     } else if (FromType->isBlockPointerType()) {
2907       Kind = CK_BlockPointerToObjCPointerCast;
2908     } else {
2909       Kind = CK_CPointerToObjCPointerCast;
2910     }
2911   } else if (ToType->isBlockPointerType()) {
2912     if (!FromType->isBlockPointerType())
2913       Kind = CK_AnyPointerToBlockPointerCast;
2914   }
2915 
2916   // We shouldn't fall into this case unless it's valid for other
2917   // reasons.
2918   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2919     Kind = CK_NullToPointer;
2920 
2921   return false;
2922 }
2923 
2924 /// IsMemberPointerConversion - Determines whether the conversion of the
2925 /// expression From, which has the (possibly adjusted) type FromType, can be
2926 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2927 /// If so, returns true and places the converted type (that might differ from
2928 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2929 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2930                                      QualType ToType,
2931                                      bool InOverloadResolution,
2932                                      QualType &ConvertedType) {
2933   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2934   if (!ToTypePtr)
2935     return false;
2936 
2937   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2938   if (From->isNullPointerConstant(Context,
2939                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2940                                         : Expr::NPC_ValueDependentIsNull)) {
2941     ConvertedType = ToType;
2942     return true;
2943   }
2944 
2945   // Otherwise, both types have to be member pointers.
2946   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2947   if (!FromTypePtr)
2948     return false;
2949 
2950   // A pointer to member of B can be converted to a pointer to member of D,
2951   // where D is derived from B (C++ 4.11p2).
2952   QualType FromClass(FromTypePtr->getClass(), 0);
2953   QualType ToClass(ToTypePtr->getClass(), 0);
2954 
2955   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2956       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2957     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2958                                                  ToClass.getTypePtr());
2959     return true;
2960   }
2961 
2962   return false;
2963 }
2964 
2965 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2966 /// expression From to the type ToType. This routine checks for ambiguous or
2967 /// virtual or inaccessible base-to-derived member pointer conversions
2968 /// for which IsMemberPointerConversion has already returned true. It returns
2969 /// true and produces a diagnostic if there was an error, or returns false
2970 /// otherwise.
2971 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2972                                         CastKind &Kind,
2973                                         CXXCastPath &BasePath,
2974                                         bool IgnoreBaseAccess) {
2975   QualType FromType = From->getType();
2976   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2977   if (!FromPtrType) {
2978     // This must be a null pointer to member pointer conversion
2979     assert(From->isNullPointerConstant(Context,
2980                                        Expr::NPC_ValueDependentIsNull) &&
2981            "Expr must be null pointer constant!");
2982     Kind = CK_NullToMemberPointer;
2983     return false;
2984   }
2985 
2986   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2987   assert(ToPtrType && "No member pointer cast has a target type "
2988                       "that is not a member pointer.");
2989 
2990   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2991   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2992 
2993   // FIXME: What about dependent types?
2994   assert(FromClass->isRecordType() && "Pointer into non-class.");
2995   assert(ToClass->isRecordType() && "Pointer into non-class.");
2996 
2997   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2998                      /*DetectVirtual=*/true);
2999   bool DerivationOkay =
3000       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3001   assert(DerivationOkay &&
3002          "Should not have been called if derivation isn't OK.");
3003   (void)DerivationOkay;
3004 
3005   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3006                                   getUnqualifiedType())) {
3007     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3008     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3009       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3010     return true;
3011   }
3012 
3013   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3014     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3015       << FromClass << ToClass << QualType(VBase, 0)
3016       << From->getSourceRange();
3017     return true;
3018   }
3019 
3020   if (!IgnoreBaseAccess)
3021     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3022                          Paths.front(),
3023                          diag::err_downcast_from_inaccessible_base);
3024 
3025   // Must be a base to derived member conversion.
3026   BuildBasePathArray(Paths, BasePath);
3027   Kind = CK_BaseToDerivedMemberPointer;
3028   return false;
3029 }
3030 
3031 /// Determine whether the lifetime conversion between the two given
3032 /// qualifiers sets is nontrivial.
3033 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3034                                                Qualifiers ToQuals) {
3035   // Converting anything to const __unsafe_unretained is trivial.
3036   if (ToQuals.hasConst() &&
3037       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3038     return false;
3039 
3040   return true;
3041 }
3042 
3043 /// IsQualificationConversion - Determines whether the conversion from
3044 /// an rvalue of type FromType to ToType is a qualification conversion
3045 /// (C++ 4.4).
3046 ///
3047 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3048 /// when the qualification conversion involves a change in the Objective-C
3049 /// object lifetime.
3050 bool
3051 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3052                                 bool CStyle, bool &ObjCLifetimeConversion) {
3053   FromType = Context.getCanonicalType(FromType);
3054   ToType = Context.getCanonicalType(ToType);
3055   ObjCLifetimeConversion = false;
3056 
3057   // If FromType and ToType are the same type, this is not a
3058   // qualification conversion.
3059   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3060     return false;
3061 
3062   // (C++ 4.4p4):
3063   //   A conversion can add cv-qualifiers at levels other than the first
3064   //   in multi-level pointers, subject to the following rules: [...]
3065   bool PreviousToQualsIncludeConst = true;
3066   bool UnwrappedAnyPointer = false;
3067   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3068     // Within each iteration of the loop, we check the qualifiers to
3069     // determine if this still looks like a qualification
3070     // conversion. Then, if all is well, we unwrap one more level of
3071     // pointers or pointers-to-members and do it all again
3072     // until there are no more pointers or pointers-to-members left to
3073     // unwrap.
3074     UnwrappedAnyPointer = true;
3075 
3076     Qualifiers FromQuals = FromType.getQualifiers();
3077     Qualifiers ToQuals = ToType.getQualifiers();
3078 
3079     // Ignore __unaligned qualifier if this type is void.
3080     if (ToType.getUnqualifiedType()->isVoidType())
3081       FromQuals.removeUnaligned();
3082 
3083     // Objective-C ARC:
3084     //   Check Objective-C lifetime conversions.
3085     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3086         UnwrappedAnyPointer) {
3087       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3088         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3089           ObjCLifetimeConversion = true;
3090         FromQuals.removeObjCLifetime();
3091         ToQuals.removeObjCLifetime();
3092       } else {
3093         // Qualification conversions cannot cast between different
3094         // Objective-C lifetime qualifiers.
3095         return false;
3096       }
3097     }
3098 
3099     // Allow addition/removal of GC attributes but not changing GC attributes.
3100     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3101         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3102       FromQuals.removeObjCGCAttr();
3103       ToQuals.removeObjCGCAttr();
3104     }
3105 
3106     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3107     //      2,j, and similarly for volatile.
3108     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3109       return false;
3110 
3111     //   -- if the cv 1,j and cv 2,j are different, then const is in
3112     //      every cv for 0 < k < j.
3113     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3114         && !PreviousToQualsIncludeConst)
3115       return false;
3116 
3117     // Keep track of whether all prior cv-qualifiers in the "to" type
3118     // include const.
3119     PreviousToQualsIncludeConst
3120       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3121   }
3122 
3123   // We are left with FromType and ToType being the pointee types
3124   // after unwrapping the original FromType and ToType the same number
3125   // of types. If we unwrapped any pointers, and if FromType and
3126   // ToType have the same unqualified type (since we checked
3127   // qualifiers above), then this is a qualification conversion.
3128   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3129 }
3130 
3131 /// \brief - Determine whether this is a conversion from a scalar type to an
3132 /// atomic type.
3133 ///
3134 /// If successful, updates \c SCS's second and third steps in the conversion
3135 /// sequence to finish the conversion.
3136 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3137                                 bool InOverloadResolution,
3138                                 StandardConversionSequence &SCS,
3139                                 bool CStyle) {
3140   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3141   if (!ToAtomic)
3142     return false;
3143 
3144   StandardConversionSequence InnerSCS;
3145   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3146                             InOverloadResolution, InnerSCS,
3147                             CStyle, /*AllowObjCWritebackConversion=*/false))
3148     return false;
3149 
3150   SCS.Second = InnerSCS.Second;
3151   SCS.setToType(1, InnerSCS.getToType(1));
3152   SCS.Third = InnerSCS.Third;
3153   SCS.QualificationIncludesObjCLifetime
3154     = InnerSCS.QualificationIncludesObjCLifetime;
3155   SCS.setToType(2, InnerSCS.getToType(2));
3156   return true;
3157 }
3158 
3159 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3160                                               CXXConstructorDecl *Constructor,
3161                                               QualType Type) {
3162   const FunctionProtoType *CtorType =
3163       Constructor->getType()->getAs<FunctionProtoType>();
3164   if (CtorType->getNumParams() > 0) {
3165     QualType FirstArg = CtorType->getParamType(0);
3166     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3167       return true;
3168   }
3169   return false;
3170 }
3171 
3172 static OverloadingResult
3173 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3174                                        CXXRecordDecl *To,
3175                                        UserDefinedConversionSequence &User,
3176                                        OverloadCandidateSet &CandidateSet,
3177                                        bool AllowExplicit) {
3178   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3179   for (auto *D : S.LookupConstructors(To)) {
3180     auto Info = getConstructorInfo(D);
3181     if (!Info)
3182       continue;
3183 
3184     bool Usable = !Info.Constructor->isInvalidDecl() &&
3185                   S.isInitListConstructor(Info.Constructor) &&
3186                   (AllowExplicit || !Info.Constructor->isExplicit());
3187     if (Usable) {
3188       // If the first argument is (a reference to) the target type,
3189       // suppress conversions.
3190       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3191           S.Context, Info.Constructor, ToType);
3192       if (Info.ConstructorTmpl)
3193         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3194                                        /*ExplicitArgs*/ nullptr, From,
3195                                        CandidateSet, SuppressUserConversions);
3196       else
3197         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3198                                CandidateSet, SuppressUserConversions);
3199     }
3200   }
3201 
3202   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3203 
3204   OverloadCandidateSet::iterator Best;
3205   switch (auto Result =
3206             CandidateSet.BestViableFunction(S, From->getLocStart(),
3207                                             Best)) {
3208   case OR_Deleted:
3209   case OR_Success: {
3210     // Record the standard conversion we used and the conversion function.
3211     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3212     QualType ThisType = Constructor->getThisType(S.Context);
3213     // Initializer lists don't have conversions as such.
3214     User.Before.setAsIdentityConversion();
3215     User.HadMultipleCandidates = HadMultipleCandidates;
3216     User.ConversionFunction = Constructor;
3217     User.FoundConversionFunction = Best->FoundDecl;
3218     User.After.setAsIdentityConversion();
3219     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3220     User.After.setAllToTypes(ToType);
3221     return Result;
3222   }
3223 
3224   case OR_No_Viable_Function:
3225     return OR_No_Viable_Function;
3226   case OR_Ambiguous:
3227     return OR_Ambiguous;
3228   }
3229 
3230   llvm_unreachable("Invalid OverloadResult!");
3231 }
3232 
3233 /// Determines whether there is a user-defined conversion sequence
3234 /// (C++ [over.ics.user]) that converts expression From to the type
3235 /// ToType. If such a conversion exists, User will contain the
3236 /// user-defined conversion sequence that performs such a conversion
3237 /// and this routine will return true. Otherwise, this routine returns
3238 /// false and User is unspecified.
3239 ///
3240 /// \param AllowExplicit  true if the conversion should consider C++0x
3241 /// "explicit" conversion functions as well as non-explicit conversion
3242 /// functions (C++0x [class.conv.fct]p2).
3243 ///
3244 /// \param AllowObjCConversionOnExplicit true if the conversion should
3245 /// allow an extra Objective-C pointer conversion on uses of explicit
3246 /// constructors. Requires \c AllowExplicit to also be set.
3247 static OverloadingResult
3248 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3249                         UserDefinedConversionSequence &User,
3250                         OverloadCandidateSet &CandidateSet,
3251                         bool AllowExplicit,
3252                         bool AllowObjCConversionOnExplicit) {
3253   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3254   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3255 
3256   // Whether we will only visit constructors.
3257   bool ConstructorsOnly = false;
3258 
3259   // If the type we are conversion to is a class type, enumerate its
3260   // constructors.
3261   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3262     // C++ [over.match.ctor]p1:
3263     //   When objects of class type are direct-initialized (8.5), or
3264     //   copy-initialized from an expression of the same or a
3265     //   derived class type (8.5), overload resolution selects the
3266     //   constructor. [...] For copy-initialization, the candidate
3267     //   functions are all the converting constructors (12.3.1) of
3268     //   that class. The argument list is the expression-list within
3269     //   the parentheses of the initializer.
3270     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3271         (From->getType()->getAs<RecordType>() &&
3272          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3273       ConstructorsOnly = true;
3274 
3275     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3276       // We're not going to find any constructors.
3277     } else if (CXXRecordDecl *ToRecordDecl
3278                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3279 
3280       Expr **Args = &From;
3281       unsigned NumArgs = 1;
3282       bool ListInitializing = false;
3283       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3284         // But first, see if there is an init-list-constructor that will work.
3285         OverloadingResult Result = IsInitializerListConstructorConversion(
3286             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3287         if (Result != OR_No_Viable_Function)
3288           return Result;
3289         // Never mind.
3290         CandidateSet.clear(
3291             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3292 
3293         // If we're list-initializing, we pass the individual elements as
3294         // arguments, not the entire list.
3295         Args = InitList->getInits();
3296         NumArgs = InitList->getNumInits();
3297         ListInitializing = true;
3298       }
3299 
3300       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3301         auto Info = getConstructorInfo(D);
3302         if (!Info)
3303           continue;
3304 
3305         bool Usable = !Info.Constructor->isInvalidDecl();
3306         if (ListInitializing)
3307           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3308         else
3309           Usable = Usable &&
3310                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3311         if (Usable) {
3312           bool SuppressUserConversions = !ConstructorsOnly;
3313           if (SuppressUserConversions && ListInitializing) {
3314             SuppressUserConversions = false;
3315             if (NumArgs == 1) {
3316               // If the first argument is (a reference to) the target type,
3317               // suppress conversions.
3318               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3319                   S.Context, Info.Constructor, ToType);
3320             }
3321           }
3322           if (Info.ConstructorTmpl)
3323             S.AddTemplateOverloadCandidate(
3324                 Info.ConstructorTmpl, Info.FoundDecl,
3325                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3326                 CandidateSet, SuppressUserConversions);
3327           else
3328             // Allow one user-defined conversion when user specifies a
3329             // From->ToType conversion via an static cast (c-style, etc).
3330             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3331                                    llvm::makeArrayRef(Args, NumArgs),
3332                                    CandidateSet, SuppressUserConversions);
3333         }
3334       }
3335     }
3336   }
3337 
3338   // Enumerate conversion functions, if we're allowed to.
3339   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3340   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3341     // No conversion functions from incomplete types.
3342   } else if (const RecordType *FromRecordType
3343                                    = From->getType()->getAs<RecordType>()) {
3344     if (CXXRecordDecl *FromRecordDecl
3345          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3346       // Add all of the conversion functions as candidates.
3347       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3348       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3349         DeclAccessPair FoundDecl = I.getPair();
3350         NamedDecl *D = FoundDecl.getDecl();
3351         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3352         if (isa<UsingShadowDecl>(D))
3353           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3354 
3355         CXXConversionDecl *Conv;
3356         FunctionTemplateDecl *ConvTemplate;
3357         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3358           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3359         else
3360           Conv = cast<CXXConversionDecl>(D);
3361 
3362         if (AllowExplicit || !Conv->isExplicit()) {
3363           if (ConvTemplate)
3364             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3365                                              ActingContext, From, ToType,
3366                                              CandidateSet,
3367                                              AllowObjCConversionOnExplicit);
3368           else
3369             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3370                                      From, ToType, CandidateSet,
3371                                      AllowObjCConversionOnExplicit);
3372         }
3373       }
3374     }
3375   }
3376 
3377   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3378 
3379   OverloadCandidateSet::iterator Best;
3380   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3381                                                         Best)) {
3382   case OR_Success:
3383   case OR_Deleted:
3384     // Record the standard conversion we used and the conversion function.
3385     if (CXXConstructorDecl *Constructor
3386           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3387       // C++ [over.ics.user]p1:
3388       //   If the user-defined conversion is specified by a
3389       //   constructor (12.3.1), the initial standard conversion
3390       //   sequence converts the source type to the type required by
3391       //   the argument of the constructor.
3392       //
3393       QualType ThisType = Constructor->getThisType(S.Context);
3394       if (isa<InitListExpr>(From)) {
3395         // Initializer lists don't have conversions as such.
3396         User.Before.setAsIdentityConversion();
3397       } else {
3398         if (Best->Conversions[0].isEllipsis())
3399           User.EllipsisConversion = true;
3400         else {
3401           User.Before = Best->Conversions[0].Standard;
3402           User.EllipsisConversion = false;
3403         }
3404       }
3405       User.HadMultipleCandidates = HadMultipleCandidates;
3406       User.ConversionFunction = Constructor;
3407       User.FoundConversionFunction = Best->FoundDecl;
3408       User.After.setAsIdentityConversion();
3409       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3410       User.After.setAllToTypes(ToType);
3411       return Result;
3412     }
3413     if (CXXConversionDecl *Conversion
3414                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3415       // C++ [over.ics.user]p1:
3416       //
3417       //   [...] If the user-defined conversion is specified by a
3418       //   conversion function (12.3.2), the initial standard
3419       //   conversion sequence converts the source type to the
3420       //   implicit object parameter of the conversion function.
3421       User.Before = Best->Conversions[0].Standard;
3422       User.HadMultipleCandidates = HadMultipleCandidates;
3423       User.ConversionFunction = Conversion;
3424       User.FoundConversionFunction = Best->FoundDecl;
3425       User.EllipsisConversion = false;
3426 
3427       // C++ [over.ics.user]p2:
3428       //   The second standard conversion sequence converts the
3429       //   result of the user-defined conversion to the target type
3430       //   for the sequence. Since an implicit conversion sequence
3431       //   is an initialization, the special rules for
3432       //   initialization by user-defined conversion apply when
3433       //   selecting the best user-defined conversion for a
3434       //   user-defined conversion sequence (see 13.3.3 and
3435       //   13.3.3.1).
3436       User.After = Best->FinalConversion;
3437       return Result;
3438     }
3439     llvm_unreachable("Not a constructor or conversion function?");
3440 
3441   case OR_No_Viable_Function:
3442     return OR_No_Viable_Function;
3443 
3444   case OR_Ambiguous:
3445     return OR_Ambiguous;
3446   }
3447 
3448   llvm_unreachable("Invalid OverloadResult!");
3449 }
3450 
3451 bool
3452 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3453   ImplicitConversionSequence ICS;
3454   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3455                                     OverloadCandidateSet::CSK_Normal);
3456   OverloadingResult OvResult =
3457     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3458                             CandidateSet, false, false);
3459   if (OvResult == OR_Ambiguous)
3460     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3461         << From->getType() << ToType << From->getSourceRange();
3462   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3463     if (!RequireCompleteType(From->getLocStart(), ToType,
3464                              diag::err_typecheck_nonviable_condition_incomplete,
3465                              From->getType(), From->getSourceRange()))
3466       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3467           << false << From->getType() << From->getSourceRange() << ToType;
3468   } else
3469     return false;
3470   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3471   return true;
3472 }
3473 
3474 /// \brief Compare the user-defined conversion functions or constructors
3475 /// of two user-defined conversion sequences to determine whether any ordering
3476 /// is possible.
3477 static ImplicitConversionSequence::CompareKind
3478 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3479                            FunctionDecl *Function2) {
3480   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3481     return ImplicitConversionSequence::Indistinguishable;
3482 
3483   // Objective-C++:
3484   //   If both conversion functions are implicitly-declared conversions from
3485   //   a lambda closure type to a function pointer and a block pointer,
3486   //   respectively, always prefer the conversion to a function pointer,
3487   //   because the function pointer is more lightweight and is more likely
3488   //   to keep code working.
3489   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3490   if (!Conv1)
3491     return ImplicitConversionSequence::Indistinguishable;
3492 
3493   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3494   if (!Conv2)
3495     return ImplicitConversionSequence::Indistinguishable;
3496 
3497   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3498     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3499     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3500     if (Block1 != Block2)
3501       return Block1 ? ImplicitConversionSequence::Worse
3502                     : ImplicitConversionSequence::Better;
3503   }
3504 
3505   return ImplicitConversionSequence::Indistinguishable;
3506 }
3507 
3508 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3509     const ImplicitConversionSequence &ICS) {
3510   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3511          (ICS.isUserDefined() &&
3512           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3513 }
3514 
3515 /// CompareImplicitConversionSequences - Compare two implicit
3516 /// conversion sequences to determine whether one is better than the
3517 /// other or if they are indistinguishable (C++ 13.3.3.2).
3518 static ImplicitConversionSequence::CompareKind
3519 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3520                                    const ImplicitConversionSequence& ICS1,
3521                                    const ImplicitConversionSequence& ICS2)
3522 {
3523   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3524   // conversion sequences (as defined in 13.3.3.1)
3525   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3526   //      conversion sequence than a user-defined conversion sequence or
3527   //      an ellipsis conversion sequence, and
3528   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3529   //      conversion sequence than an ellipsis conversion sequence
3530   //      (13.3.3.1.3).
3531   //
3532   // C++0x [over.best.ics]p10:
3533   //   For the purpose of ranking implicit conversion sequences as
3534   //   described in 13.3.3.2, the ambiguous conversion sequence is
3535   //   treated as a user-defined sequence that is indistinguishable
3536   //   from any other user-defined conversion sequence.
3537 
3538   // String literal to 'char *' conversion has been deprecated in C++03. It has
3539   // been removed from C++11. We still accept this conversion, if it happens at
3540   // the best viable function. Otherwise, this conversion is considered worse
3541   // than ellipsis conversion. Consider this as an extension; this is not in the
3542   // standard. For example:
3543   //
3544   // int &f(...);    // #1
3545   // void f(char*);  // #2
3546   // void g() { int &r = f("foo"); }
3547   //
3548   // In C++03, we pick #2 as the best viable function.
3549   // In C++11, we pick #1 as the best viable function, because ellipsis
3550   // conversion is better than string-literal to char* conversion (since there
3551   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3552   // convert arguments, #2 would be the best viable function in C++11.
3553   // If the best viable function has this conversion, a warning will be issued
3554   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3555 
3556   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3557       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3558       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3559     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3560                ? ImplicitConversionSequence::Worse
3561                : ImplicitConversionSequence::Better;
3562 
3563   if (ICS1.getKindRank() < ICS2.getKindRank())
3564     return ImplicitConversionSequence::Better;
3565   if (ICS2.getKindRank() < ICS1.getKindRank())
3566     return ImplicitConversionSequence::Worse;
3567 
3568   // The following checks require both conversion sequences to be of
3569   // the same kind.
3570   if (ICS1.getKind() != ICS2.getKind())
3571     return ImplicitConversionSequence::Indistinguishable;
3572 
3573   ImplicitConversionSequence::CompareKind Result =
3574       ImplicitConversionSequence::Indistinguishable;
3575 
3576   // Two implicit conversion sequences of the same form are
3577   // indistinguishable conversion sequences unless one of the
3578   // following rules apply: (C++ 13.3.3.2p3):
3579 
3580   // List-initialization sequence L1 is a better conversion sequence than
3581   // list-initialization sequence L2 if:
3582   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3583   //   if not that,
3584   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3585   //   and N1 is smaller than N2.,
3586   // even if one of the other rules in this paragraph would otherwise apply.
3587   if (!ICS1.isBad()) {
3588     if (ICS1.isStdInitializerListElement() &&
3589         !ICS2.isStdInitializerListElement())
3590       return ImplicitConversionSequence::Better;
3591     if (!ICS1.isStdInitializerListElement() &&
3592         ICS2.isStdInitializerListElement())
3593       return ImplicitConversionSequence::Worse;
3594   }
3595 
3596   if (ICS1.isStandard())
3597     // Standard conversion sequence S1 is a better conversion sequence than
3598     // standard conversion sequence S2 if [...]
3599     Result = CompareStandardConversionSequences(S, Loc,
3600                                                 ICS1.Standard, ICS2.Standard);
3601   else if (ICS1.isUserDefined()) {
3602     // User-defined conversion sequence U1 is a better conversion
3603     // sequence than another user-defined conversion sequence U2 if
3604     // they contain the same user-defined conversion function or
3605     // constructor and if the second standard conversion sequence of
3606     // U1 is better than the second standard conversion sequence of
3607     // U2 (C++ 13.3.3.2p3).
3608     if (ICS1.UserDefined.ConversionFunction ==
3609           ICS2.UserDefined.ConversionFunction)
3610       Result = CompareStandardConversionSequences(S, Loc,
3611                                                   ICS1.UserDefined.After,
3612                                                   ICS2.UserDefined.After);
3613     else
3614       Result = compareConversionFunctions(S,
3615                                           ICS1.UserDefined.ConversionFunction,
3616                                           ICS2.UserDefined.ConversionFunction);
3617   }
3618 
3619   return Result;
3620 }
3621 
3622 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3623   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3624     Qualifiers Quals;
3625     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3626     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3627   }
3628 
3629   return Context.hasSameUnqualifiedType(T1, T2);
3630 }
3631 
3632 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3633 // determine if one is a proper subset of the other.
3634 static ImplicitConversionSequence::CompareKind
3635 compareStandardConversionSubsets(ASTContext &Context,
3636                                  const StandardConversionSequence& SCS1,
3637                                  const StandardConversionSequence& SCS2) {
3638   ImplicitConversionSequence::CompareKind Result
3639     = ImplicitConversionSequence::Indistinguishable;
3640 
3641   // the identity conversion sequence is considered to be a subsequence of
3642   // any non-identity conversion sequence
3643   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3644     return ImplicitConversionSequence::Better;
3645   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3646     return ImplicitConversionSequence::Worse;
3647 
3648   if (SCS1.Second != SCS2.Second) {
3649     if (SCS1.Second == ICK_Identity)
3650       Result = ImplicitConversionSequence::Better;
3651     else if (SCS2.Second == ICK_Identity)
3652       Result = ImplicitConversionSequence::Worse;
3653     else
3654       return ImplicitConversionSequence::Indistinguishable;
3655   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3656     return ImplicitConversionSequence::Indistinguishable;
3657 
3658   if (SCS1.Third == SCS2.Third) {
3659     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3660                              : ImplicitConversionSequence::Indistinguishable;
3661   }
3662 
3663   if (SCS1.Third == ICK_Identity)
3664     return Result == ImplicitConversionSequence::Worse
3665              ? ImplicitConversionSequence::Indistinguishable
3666              : ImplicitConversionSequence::Better;
3667 
3668   if (SCS2.Third == ICK_Identity)
3669     return Result == ImplicitConversionSequence::Better
3670              ? ImplicitConversionSequence::Indistinguishable
3671              : ImplicitConversionSequence::Worse;
3672 
3673   return ImplicitConversionSequence::Indistinguishable;
3674 }
3675 
3676 /// \brief Determine whether one of the given reference bindings is better
3677 /// than the other based on what kind of bindings they are.
3678 static bool
3679 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3680                              const StandardConversionSequence &SCS2) {
3681   // C++0x [over.ics.rank]p3b4:
3682   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3683   //      implicit object parameter of a non-static member function declared
3684   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3685   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3686   //      lvalue reference to a function lvalue and S2 binds an rvalue
3687   //      reference*.
3688   //
3689   // FIXME: Rvalue references. We're going rogue with the above edits,
3690   // because the semantics in the current C++0x working paper (N3225 at the
3691   // time of this writing) break the standard definition of std::forward
3692   // and std::reference_wrapper when dealing with references to functions.
3693   // Proposed wording changes submitted to CWG for consideration.
3694   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3695       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3696     return false;
3697 
3698   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3699           SCS2.IsLvalueReference) ||
3700          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3701           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3702 }
3703 
3704 /// CompareStandardConversionSequences - Compare two standard
3705 /// conversion sequences to determine whether one is better than the
3706 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3707 static ImplicitConversionSequence::CompareKind
3708 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3709                                    const StandardConversionSequence& SCS1,
3710                                    const StandardConversionSequence& SCS2)
3711 {
3712   // Standard conversion sequence S1 is a better conversion sequence
3713   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3714 
3715   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3716   //     sequences in the canonical form defined by 13.3.3.1.1,
3717   //     excluding any Lvalue Transformation; the identity conversion
3718   //     sequence is considered to be a subsequence of any
3719   //     non-identity conversion sequence) or, if not that,
3720   if (ImplicitConversionSequence::CompareKind CK
3721         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3722     return CK;
3723 
3724   //  -- the rank of S1 is better than the rank of S2 (by the rules
3725   //     defined below), or, if not that,
3726   ImplicitConversionRank Rank1 = SCS1.getRank();
3727   ImplicitConversionRank Rank2 = SCS2.getRank();
3728   if (Rank1 < Rank2)
3729     return ImplicitConversionSequence::Better;
3730   else if (Rank2 < Rank1)
3731     return ImplicitConversionSequence::Worse;
3732 
3733   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3734   // are indistinguishable unless one of the following rules
3735   // applies:
3736 
3737   //   A conversion that is not a conversion of a pointer, or
3738   //   pointer to member, to bool is better than another conversion
3739   //   that is such a conversion.
3740   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3741     return SCS2.isPointerConversionToBool()
3742              ? ImplicitConversionSequence::Better
3743              : ImplicitConversionSequence::Worse;
3744 
3745   // C++ [over.ics.rank]p4b2:
3746   //
3747   //   If class B is derived directly or indirectly from class A,
3748   //   conversion of B* to A* is better than conversion of B* to
3749   //   void*, and conversion of A* to void* is better than conversion
3750   //   of B* to void*.
3751   bool SCS1ConvertsToVoid
3752     = SCS1.isPointerConversionToVoidPointer(S.Context);
3753   bool SCS2ConvertsToVoid
3754     = SCS2.isPointerConversionToVoidPointer(S.Context);
3755   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3756     // Exactly one of the conversion sequences is a conversion to
3757     // a void pointer; it's the worse conversion.
3758     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3759                               : ImplicitConversionSequence::Worse;
3760   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3761     // Neither conversion sequence converts to a void pointer; compare
3762     // their derived-to-base conversions.
3763     if (ImplicitConversionSequence::CompareKind DerivedCK
3764           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3765       return DerivedCK;
3766   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3767              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3768     // Both conversion sequences are conversions to void
3769     // pointers. Compare the source types to determine if there's an
3770     // inheritance relationship in their sources.
3771     QualType FromType1 = SCS1.getFromType();
3772     QualType FromType2 = SCS2.getFromType();
3773 
3774     // Adjust the types we're converting from via the array-to-pointer
3775     // conversion, if we need to.
3776     if (SCS1.First == ICK_Array_To_Pointer)
3777       FromType1 = S.Context.getArrayDecayedType(FromType1);
3778     if (SCS2.First == ICK_Array_To_Pointer)
3779       FromType2 = S.Context.getArrayDecayedType(FromType2);
3780 
3781     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3782     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3783 
3784     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3785       return ImplicitConversionSequence::Better;
3786     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3787       return ImplicitConversionSequence::Worse;
3788 
3789     // Objective-C++: If one interface is more specific than the
3790     // other, it is the better one.
3791     const ObjCObjectPointerType* FromObjCPtr1
3792       = FromType1->getAs<ObjCObjectPointerType>();
3793     const ObjCObjectPointerType* FromObjCPtr2
3794       = FromType2->getAs<ObjCObjectPointerType>();
3795     if (FromObjCPtr1 && FromObjCPtr2) {
3796       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3797                                                           FromObjCPtr2);
3798       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3799                                                            FromObjCPtr1);
3800       if (AssignLeft != AssignRight) {
3801         return AssignLeft? ImplicitConversionSequence::Better
3802                          : ImplicitConversionSequence::Worse;
3803       }
3804     }
3805   }
3806 
3807   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3808   // bullet 3).
3809   if (ImplicitConversionSequence::CompareKind QualCK
3810         = CompareQualificationConversions(S, SCS1, SCS2))
3811     return QualCK;
3812 
3813   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3814     // Check for a better reference binding based on the kind of bindings.
3815     if (isBetterReferenceBindingKind(SCS1, SCS2))
3816       return ImplicitConversionSequence::Better;
3817     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3818       return ImplicitConversionSequence::Worse;
3819 
3820     // C++ [over.ics.rank]p3b4:
3821     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3822     //      which the references refer are the same type except for
3823     //      top-level cv-qualifiers, and the type to which the reference
3824     //      initialized by S2 refers is more cv-qualified than the type
3825     //      to which the reference initialized by S1 refers.
3826     QualType T1 = SCS1.getToType(2);
3827     QualType T2 = SCS2.getToType(2);
3828     T1 = S.Context.getCanonicalType(T1);
3829     T2 = S.Context.getCanonicalType(T2);
3830     Qualifiers T1Quals, T2Quals;
3831     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3832     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3833     if (UnqualT1 == UnqualT2) {
3834       // Objective-C++ ARC: If the references refer to objects with different
3835       // lifetimes, prefer bindings that don't change lifetime.
3836       if (SCS1.ObjCLifetimeConversionBinding !=
3837                                           SCS2.ObjCLifetimeConversionBinding) {
3838         return SCS1.ObjCLifetimeConversionBinding
3839                                            ? ImplicitConversionSequence::Worse
3840                                            : ImplicitConversionSequence::Better;
3841       }
3842 
3843       // If the type is an array type, promote the element qualifiers to the
3844       // type for comparison.
3845       if (isa<ArrayType>(T1) && T1Quals)
3846         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3847       if (isa<ArrayType>(T2) && T2Quals)
3848         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3849       if (T2.isMoreQualifiedThan(T1))
3850         return ImplicitConversionSequence::Better;
3851       else if (T1.isMoreQualifiedThan(T2))
3852         return ImplicitConversionSequence::Worse;
3853     }
3854   }
3855 
3856   // In Microsoft mode, prefer an integral conversion to a
3857   // floating-to-integral conversion if the integral conversion
3858   // is between types of the same size.
3859   // For example:
3860   // void f(float);
3861   // void f(int);
3862   // int main {
3863   //    long a;
3864   //    f(a);
3865   // }
3866   // Here, MSVC will call f(int) instead of generating a compile error
3867   // as clang will do in standard mode.
3868   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3869       SCS2.Second == ICK_Floating_Integral &&
3870       S.Context.getTypeSize(SCS1.getFromType()) ==
3871           S.Context.getTypeSize(SCS1.getToType(2)))
3872     return ImplicitConversionSequence::Better;
3873 
3874   return ImplicitConversionSequence::Indistinguishable;
3875 }
3876 
3877 /// CompareQualificationConversions - Compares two standard conversion
3878 /// sequences to determine whether they can be ranked based on their
3879 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3880 static ImplicitConversionSequence::CompareKind
3881 CompareQualificationConversions(Sema &S,
3882                                 const StandardConversionSequence& SCS1,
3883                                 const StandardConversionSequence& SCS2) {
3884   // C++ 13.3.3.2p3:
3885   //  -- S1 and S2 differ only in their qualification conversion and
3886   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3887   //     cv-qualification signature of type T1 is a proper subset of
3888   //     the cv-qualification signature of type T2, and S1 is not the
3889   //     deprecated string literal array-to-pointer conversion (4.2).
3890   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3891       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3892     return ImplicitConversionSequence::Indistinguishable;
3893 
3894   // FIXME: the example in the standard doesn't use a qualification
3895   // conversion (!)
3896   QualType T1 = SCS1.getToType(2);
3897   QualType T2 = SCS2.getToType(2);
3898   T1 = S.Context.getCanonicalType(T1);
3899   T2 = S.Context.getCanonicalType(T2);
3900   Qualifiers T1Quals, T2Quals;
3901   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3902   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3903 
3904   // If the types are the same, we won't learn anything by unwrapped
3905   // them.
3906   if (UnqualT1 == UnqualT2)
3907     return ImplicitConversionSequence::Indistinguishable;
3908 
3909   // If the type is an array type, promote the element qualifiers to the type
3910   // for comparison.
3911   if (isa<ArrayType>(T1) && T1Quals)
3912     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3913   if (isa<ArrayType>(T2) && T2Quals)
3914     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3915 
3916   ImplicitConversionSequence::CompareKind Result
3917     = ImplicitConversionSequence::Indistinguishable;
3918 
3919   // Objective-C++ ARC:
3920   //   Prefer qualification conversions not involving a change in lifetime
3921   //   to qualification conversions that do not change lifetime.
3922   if (SCS1.QualificationIncludesObjCLifetime !=
3923                                       SCS2.QualificationIncludesObjCLifetime) {
3924     Result = SCS1.QualificationIncludesObjCLifetime
3925                ? ImplicitConversionSequence::Worse
3926                : ImplicitConversionSequence::Better;
3927   }
3928 
3929   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3930     // Within each iteration of the loop, we check the qualifiers to
3931     // determine if this still looks like a qualification
3932     // conversion. Then, if all is well, we unwrap one more level of
3933     // pointers or pointers-to-members and do it all again
3934     // until there are no more pointers or pointers-to-members left
3935     // to unwrap. This essentially mimics what
3936     // IsQualificationConversion does, but here we're checking for a
3937     // strict subset of qualifiers.
3938     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3939       // The qualifiers are the same, so this doesn't tell us anything
3940       // about how the sequences rank.
3941       ;
3942     else if (T2.isMoreQualifiedThan(T1)) {
3943       // T1 has fewer qualifiers, so it could be the better sequence.
3944       if (Result == ImplicitConversionSequence::Worse)
3945         // Neither has qualifiers that are a subset of the other's
3946         // qualifiers.
3947         return ImplicitConversionSequence::Indistinguishable;
3948 
3949       Result = ImplicitConversionSequence::Better;
3950     } else if (T1.isMoreQualifiedThan(T2)) {
3951       // T2 has fewer qualifiers, so it could be the better sequence.
3952       if (Result == ImplicitConversionSequence::Better)
3953         // Neither has qualifiers that are a subset of the other's
3954         // qualifiers.
3955         return ImplicitConversionSequence::Indistinguishable;
3956 
3957       Result = ImplicitConversionSequence::Worse;
3958     } else {
3959       // Qualifiers are disjoint.
3960       return ImplicitConversionSequence::Indistinguishable;
3961     }
3962 
3963     // If the types after this point are equivalent, we're done.
3964     if (S.Context.hasSameUnqualifiedType(T1, T2))
3965       break;
3966   }
3967 
3968   // Check that the winning standard conversion sequence isn't using
3969   // the deprecated string literal array to pointer conversion.
3970   switch (Result) {
3971   case ImplicitConversionSequence::Better:
3972     if (SCS1.DeprecatedStringLiteralToCharPtr)
3973       Result = ImplicitConversionSequence::Indistinguishable;
3974     break;
3975 
3976   case ImplicitConversionSequence::Indistinguishable:
3977     break;
3978 
3979   case ImplicitConversionSequence::Worse:
3980     if (SCS2.DeprecatedStringLiteralToCharPtr)
3981       Result = ImplicitConversionSequence::Indistinguishable;
3982     break;
3983   }
3984 
3985   return Result;
3986 }
3987 
3988 /// CompareDerivedToBaseConversions - Compares two standard conversion
3989 /// sequences to determine whether they can be ranked based on their
3990 /// various kinds of derived-to-base conversions (C++
3991 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3992 /// conversions between Objective-C interface types.
3993 static ImplicitConversionSequence::CompareKind
3994 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3995                                 const StandardConversionSequence& SCS1,
3996                                 const StandardConversionSequence& SCS2) {
3997   QualType FromType1 = SCS1.getFromType();
3998   QualType ToType1 = SCS1.getToType(1);
3999   QualType FromType2 = SCS2.getFromType();
4000   QualType ToType2 = SCS2.getToType(1);
4001 
4002   // Adjust the types we're converting from via the array-to-pointer
4003   // conversion, if we need to.
4004   if (SCS1.First == ICK_Array_To_Pointer)
4005     FromType1 = S.Context.getArrayDecayedType(FromType1);
4006   if (SCS2.First == ICK_Array_To_Pointer)
4007     FromType2 = S.Context.getArrayDecayedType(FromType2);
4008 
4009   // Canonicalize all of the types.
4010   FromType1 = S.Context.getCanonicalType(FromType1);
4011   ToType1 = S.Context.getCanonicalType(ToType1);
4012   FromType2 = S.Context.getCanonicalType(FromType2);
4013   ToType2 = S.Context.getCanonicalType(ToType2);
4014 
4015   // C++ [over.ics.rank]p4b3:
4016   //
4017   //   If class B is derived directly or indirectly from class A and
4018   //   class C is derived directly or indirectly from B,
4019   //
4020   // Compare based on pointer conversions.
4021   if (SCS1.Second == ICK_Pointer_Conversion &&
4022       SCS2.Second == ICK_Pointer_Conversion &&
4023       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4024       FromType1->isPointerType() && FromType2->isPointerType() &&
4025       ToType1->isPointerType() && ToType2->isPointerType()) {
4026     QualType FromPointee1
4027       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4028     QualType ToPointee1
4029       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4030     QualType FromPointee2
4031       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4032     QualType ToPointee2
4033       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4034 
4035     //   -- conversion of C* to B* is better than conversion of C* to A*,
4036     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4037       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4038         return ImplicitConversionSequence::Better;
4039       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4040         return ImplicitConversionSequence::Worse;
4041     }
4042 
4043     //   -- conversion of B* to A* is better than conversion of C* to A*,
4044     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4045       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4046         return ImplicitConversionSequence::Better;
4047       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4048         return ImplicitConversionSequence::Worse;
4049     }
4050   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4051              SCS2.Second == ICK_Pointer_Conversion) {
4052     const ObjCObjectPointerType *FromPtr1
4053       = FromType1->getAs<ObjCObjectPointerType>();
4054     const ObjCObjectPointerType *FromPtr2
4055       = FromType2->getAs<ObjCObjectPointerType>();
4056     const ObjCObjectPointerType *ToPtr1
4057       = ToType1->getAs<ObjCObjectPointerType>();
4058     const ObjCObjectPointerType *ToPtr2
4059       = ToType2->getAs<ObjCObjectPointerType>();
4060 
4061     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4062       // Apply the same conversion ranking rules for Objective-C pointer types
4063       // that we do for C++ pointers to class types. However, we employ the
4064       // Objective-C pseudo-subtyping relationship used for assignment of
4065       // Objective-C pointer types.
4066       bool FromAssignLeft
4067         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4068       bool FromAssignRight
4069         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4070       bool ToAssignLeft
4071         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4072       bool ToAssignRight
4073         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4074 
4075       // A conversion to an a non-id object pointer type or qualified 'id'
4076       // type is better than a conversion to 'id'.
4077       if (ToPtr1->isObjCIdType() &&
4078           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4079         return ImplicitConversionSequence::Worse;
4080       if (ToPtr2->isObjCIdType() &&
4081           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4082         return ImplicitConversionSequence::Better;
4083 
4084       // A conversion to a non-id object pointer type is better than a
4085       // conversion to a qualified 'id' type
4086       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4087         return ImplicitConversionSequence::Worse;
4088       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4089         return ImplicitConversionSequence::Better;
4090 
4091       // A conversion to an a non-Class object pointer type or qualified 'Class'
4092       // type is better than a conversion to 'Class'.
4093       if (ToPtr1->isObjCClassType() &&
4094           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4095         return ImplicitConversionSequence::Worse;
4096       if (ToPtr2->isObjCClassType() &&
4097           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4098         return ImplicitConversionSequence::Better;
4099 
4100       // A conversion to a non-Class object pointer type is better than a
4101       // conversion to a qualified 'Class' type.
4102       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4103         return ImplicitConversionSequence::Worse;
4104       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4105         return ImplicitConversionSequence::Better;
4106 
4107       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4108       if (S.Context.hasSameType(FromType1, FromType2) &&
4109           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4110           (ToAssignLeft != ToAssignRight)) {
4111         if (FromPtr1->isSpecialized()) {
4112           // "conversion of B<A> * to B * is better than conversion of B * to
4113           // C *.
4114           bool IsFirstSame =
4115               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4116           bool IsSecondSame =
4117               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4118           if (IsFirstSame) {
4119             if (!IsSecondSame)
4120               return ImplicitConversionSequence::Better;
4121           } else if (IsSecondSame)
4122             return ImplicitConversionSequence::Worse;
4123         }
4124         return ToAssignLeft? ImplicitConversionSequence::Worse
4125                            : ImplicitConversionSequence::Better;
4126       }
4127 
4128       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4129       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4130           (FromAssignLeft != FromAssignRight))
4131         return FromAssignLeft? ImplicitConversionSequence::Better
4132         : ImplicitConversionSequence::Worse;
4133     }
4134   }
4135 
4136   // Ranking of member-pointer types.
4137   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4138       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4139       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4140     const MemberPointerType * FromMemPointer1 =
4141                                         FromType1->getAs<MemberPointerType>();
4142     const MemberPointerType * ToMemPointer1 =
4143                                           ToType1->getAs<MemberPointerType>();
4144     const MemberPointerType * FromMemPointer2 =
4145                                           FromType2->getAs<MemberPointerType>();
4146     const MemberPointerType * ToMemPointer2 =
4147                                           ToType2->getAs<MemberPointerType>();
4148     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4149     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4150     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4151     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4152     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4153     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4154     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4155     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4156     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4157     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4158       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4159         return ImplicitConversionSequence::Worse;
4160       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4161         return ImplicitConversionSequence::Better;
4162     }
4163     // conversion of B::* to C::* is better than conversion of A::* to C::*
4164     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4165       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4166         return ImplicitConversionSequence::Better;
4167       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4168         return ImplicitConversionSequence::Worse;
4169     }
4170   }
4171 
4172   if (SCS1.Second == ICK_Derived_To_Base) {
4173     //   -- conversion of C to B is better than conversion of C to A,
4174     //   -- binding of an expression of type C to a reference of type
4175     //      B& is better than binding an expression of type C to a
4176     //      reference of type A&,
4177     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4178         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4179       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4180         return ImplicitConversionSequence::Better;
4181       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4182         return ImplicitConversionSequence::Worse;
4183     }
4184 
4185     //   -- conversion of B to A is better than conversion of C to A.
4186     //   -- binding of an expression of type B to a reference of type
4187     //      A& is better than binding an expression of type C to a
4188     //      reference of type A&,
4189     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4190         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4191       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4192         return ImplicitConversionSequence::Better;
4193       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4194         return ImplicitConversionSequence::Worse;
4195     }
4196   }
4197 
4198   return ImplicitConversionSequence::Indistinguishable;
4199 }
4200 
4201 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4202 /// C++ class.
4203 static bool isTypeValid(QualType T) {
4204   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4205     return !Record->isInvalidDecl();
4206 
4207   return true;
4208 }
4209 
4210 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4211 /// determine whether they are reference-related,
4212 /// reference-compatible, reference-compatible with added
4213 /// qualification, or incompatible, for use in C++ initialization by
4214 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4215 /// type, and the first type (T1) is the pointee type of the reference
4216 /// type being initialized.
4217 Sema::ReferenceCompareResult
4218 Sema::CompareReferenceRelationship(SourceLocation Loc,
4219                                    QualType OrigT1, QualType OrigT2,
4220                                    bool &DerivedToBase,
4221                                    bool &ObjCConversion,
4222                                    bool &ObjCLifetimeConversion) {
4223   assert(!OrigT1->isReferenceType() &&
4224     "T1 must be the pointee type of the reference type");
4225   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4226 
4227   QualType T1 = Context.getCanonicalType(OrigT1);
4228   QualType T2 = Context.getCanonicalType(OrigT2);
4229   Qualifiers T1Quals, T2Quals;
4230   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4231   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4232 
4233   // C++ [dcl.init.ref]p4:
4234   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4235   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4236   //   T1 is a base class of T2.
4237   DerivedToBase = false;
4238   ObjCConversion = false;
4239   ObjCLifetimeConversion = false;
4240   QualType ConvertedT2;
4241   if (UnqualT1 == UnqualT2) {
4242     // Nothing to do.
4243   } else if (isCompleteType(Loc, OrigT2) &&
4244              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4245              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4246     DerivedToBase = true;
4247   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4248            UnqualT2->isObjCObjectOrInterfaceType() &&
4249            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4250     ObjCConversion = true;
4251   else if (UnqualT2->isFunctionType() &&
4252            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4253     // C++1z [dcl.init.ref]p4:
4254     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4255     //   function" and T1 is "function"
4256     //
4257     // We extend this to also apply to 'noreturn', so allow any function
4258     // conversion between function types.
4259     return Ref_Compatible;
4260   else
4261     return Ref_Incompatible;
4262 
4263   // At this point, we know that T1 and T2 are reference-related (at
4264   // least).
4265 
4266   // If the type is an array type, promote the element qualifiers to the type
4267   // for comparison.
4268   if (isa<ArrayType>(T1) && T1Quals)
4269     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4270   if (isa<ArrayType>(T2) && T2Quals)
4271     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4272 
4273   // C++ [dcl.init.ref]p4:
4274   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4275   //   reference-related to T2 and cv1 is the same cv-qualification
4276   //   as, or greater cv-qualification than, cv2. For purposes of
4277   //   overload resolution, cases for which cv1 is greater
4278   //   cv-qualification than cv2 are identified as
4279   //   reference-compatible with added qualification (see 13.3.3.2).
4280   //
4281   // Note that we also require equivalence of Objective-C GC and address-space
4282   // qualifiers when performing these computations, so that e.g., an int in
4283   // address space 1 is not reference-compatible with an int in address
4284   // space 2.
4285   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4286       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4287     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4288       ObjCLifetimeConversion = true;
4289 
4290     T1Quals.removeObjCLifetime();
4291     T2Quals.removeObjCLifetime();
4292   }
4293 
4294   // MS compiler ignores __unaligned qualifier for references; do the same.
4295   T1Quals.removeUnaligned();
4296   T2Quals.removeUnaligned();
4297 
4298   if (T1Quals.compatiblyIncludes(T2Quals))
4299     return Ref_Compatible;
4300   else
4301     return Ref_Related;
4302 }
4303 
4304 /// \brief Look for a user-defined conversion to a value reference-compatible
4305 ///        with DeclType. Return true if something definite is found.
4306 static bool
4307 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4308                          QualType DeclType, SourceLocation DeclLoc,
4309                          Expr *Init, QualType T2, bool AllowRvalues,
4310                          bool AllowExplicit) {
4311   assert(T2->isRecordType() && "Can only find conversions of record types.");
4312   CXXRecordDecl *T2RecordDecl
4313     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4314 
4315   OverloadCandidateSet CandidateSet(
4316       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4317   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4318   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4319     NamedDecl *D = *I;
4320     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4321     if (isa<UsingShadowDecl>(D))
4322       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4323 
4324     FunctionTemplateDecl *ConvTemplate
4325       = dyn_cast<FunctionTemplateDecl>(D);
4326     CXXConversionDecl *Conv;
4327     if (ConvTemplate)
4328       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4329     else
4330       Conv = cast<CXXConversionDecl>(D);
4331 
4332     // If this is an explicit conversion, and we're not allowed to consider
4333     // explicit conversions, skip it.
4334     if (!AllowExplicit && Conv->isExplicit())
4335       continue;
4336 
4337     if (AllowRvalues) {
4338       bool DerivedToBase = false;
4339       bool ObjCConversion = false;
4340       bool ObjCLifetimeConversion = false;
4341 
4342       // If we are initializing an rvalue reference, don't permit conversion
4343       // functions that return lvalues.
4344       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4345         const ReferenceType *RefType
4346           = Conv->getConversionType()->getAs<LValueReferenceType>();
4347         if (RefType && !RefType->getPointeeType()->isFunctionType())
4348           continue;
4349       }
4350 
4351       if (!ConvTemplate &&
4352           S.CompareReferenceRelationship(
4353             DeclLoc,
4354             Conv->getConversionType().getNonReferenceType()
4355               .getUnqualifiedType(),
4356             DeclType.getNonReferenceType().getUnqualifiedType(),
4357             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4358           Sema::Ref_Incompatible)
4359         continue;
4360     } else {
4361       // If the conversion function doesn't return a reference type,
4362       // it can't be considered for this conversion. An rvalue reference
4363       // is only acceptable if its referencee is a function type.
4364 
4365       const ReferenceType *RefType =
4366         Conv->getConversionType()->getAs<ReferenceType>();
4367       if (!RefType ||
4368           (!RefType->isLValueReferenceType() &&
4369            !RefType->getPointeeType()->isFunctionType()))
4370         continue;
4371     }
4372 
4373     if (ConvTemplate)
4374       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4375                                        Init, DeclType, CandidateSet,
4376                                        /*AllowObjCConversionOnExplicit=*/false);
4377     else
4378       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4379                                DeclType, CandidateSet,
4380                                /*AllowObjCConversionOnExplicit=*/false);
4381   }
4382 
4383   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4384 
4385   OverloadCandidateSet::iterator Best;
4386   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4387   case OR_Success:
4388     // C++ [over.ics.ref]p1:
4389     //
4390     //   [...] If the parameter binds directly to the result of
4391     //   applying a conversion function to the argument
4392     //   expression, the implicit conversion sequence is a
4393     //   user-defined conversion sequence (13.3.3.1.2), with the
4394     //   second standard conversion sequence either an identity
4395     //   conversion or, if the conversion function returns an
4396     //   entity of a type that is a derived class of the parameter
4397     //   type, a derived-to-base Conversion.
4398     if (!Best->FinalConversion.DirectBinding)
4399       return false;
4400 
4401     ICS.setUserDefined();
4402     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4403     ICS.UserDefined.After = Best->FinalConversion;
4404     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4405     ICS.UserDefined.ConversionFunction = Best->Function;
4406     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4407     ICS.UserDefined.EllipsisConversion = false;
4408     assert(ICS.UserDefined.After.ReferenceBinding &&
4409            ICS.UserDefined.After.DirectBinding &&
4410            "Expected a direct reference binding!");
4411     return true;
4412 
4413   case OR_Ambiguous:
4414     ICS.setAmbiguous();
4415     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4416          Cand != CandidateSet.end(); ++Cand)
4417       if (Cand->Viable)
4418         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4419     return true;
4420 
4421   case OR_No_Viable_Function:
4422   case OR_Deleted:
4423     // There was no suitable conversion, or we found a deleted
4424     // conversion; continue with other checks.
4425     return false;
4426   }
4427 
4428   llvm_unreachable("Invalid OverloadResult!");
4429 }
4430 
4431 /// \brief Compute an implicit conversion sequence for reference
4432 /// initialization.
4433 static ImplicitConversionSequence
4434 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4435                  SourceLocation DeclLoc,
4436                  bool SuppressUserConversions,
4437                  bool AllowExplicit) {
4438   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4439 
4440   // Most paths end in a failed conversion.
4441   ImplicitConversionSequence ICS;
4442   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4443 
4444   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4445   QualType T2 = Init->getType();
4446 
4447   // If the initializer is the address of an overloaded function, try
4448   // to resolve the overloaded function. If all goes well, T2 is the
4449   // type of the resulting function.
4450   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4451     DeclAccessPair Found;
4452     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4453                                                                 false, Found))
4454       T2 = Fn->getType();
4455   }
4456 
4457   // Compute some basic properties of the types and the initializer.
4458   bool isRValRef = DeclType->isRValueReferenceType();
4459   bool DerivedToBase = false;
4460   bool ObjCConversion = false;
4461   bool ObjCLifetimeConversion = false;
4462   Expr::Classification InitCategory = Init->Classify(S.Context);
4463   Sema::ReferenceCompareResult RefRelationship
4464     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4465                                      ObjCConversion, ObjCLifetimeConversion);
4466 
4467 
4468   // C++0x [dcl.init.ref]p5:
4469   //   A reference to type "cv1 T1" is initialized by an expression
4470   //   of type "cv2 T2" as follows:
4471 
4472   //     -- If reference is an lvalue reference and the initializer expression
4473   if (!isRValRef) {
4474     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4475     //        reference-compatible with "cv2 T2," or
4476     //
4477     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4478     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4479       // C++ [over.ics.ref]p1:
4480       //   When a parameter of reference type binds directly (8.5.3)
4481       //   to an argument expression, the implicit conversion sequence
4482       //   is the identity conversion, unless the argument expression
4483       //   has a type that is a derived class of the parameter type,
4484       //   in which case the implicit conversion sequence is a
4485       //   derived-to-base Conversion (13.3.3.1).
4486       ICS.setStandard();
4487       ICS.Standard.First = ICK_Identity;
4488       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4489                          : ObjCConversion? ICK_Compatible_Conversion
4490                          : ICK_Identity;
4491       ICS.Standard.Third = ICK_Identity;
4492       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4493       ICS.Standard.setToType(0, T2);
4494       ICS.Standard.setToType(1, T1);
4495       ICS.Standard.setToType(2, T1);
4496       ICS.Standard.ReferenceBinding = true;
4497       ICS.Standard.DirectBinding = true;
4498       ICS.Standard.IsLvalueReference = !isRValRef;
4499       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4500       ICS.Standard.BindsToRvalue = false;
4501       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4502       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4503       ICS.Standard.CopyConstructor = nullptr;
4504       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4505 
4506       // Nothing more to do: the inaccessibility/ambiguity check for
4507       // derived-to-base conversions is suppressed when we're
4508       // computing the implicit conversion sequence (C++
4509       // [over.best.ics]p2).
4510       return ICS;
4511     }
4512 
4513     //       -- has a class type (i.e., T2 is a class type), where T1 is
4514     //          not reference-related to T2, and can be implicitly
4515     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4516     //          is reference-compatible with "cv3 T3" 92) (this
4517     //          conversion is selected by enumerating the applicable
4518     //          conversion functions (13.3.1.6) and choosing the best
4519     //          one through overload resolution (13.3)),
4520     if (!SuppressUserConversions && T2->isRecordType() &&
4521         S.isCompleteType(DeclLoc, T2) &&
4522         RefRelationship == Sema::Ref_Incompatible) {
4523       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4524                                    Init, T2, /*AllowRvalues=*/false,
4525                                    AllowExplicit))
4526         return ICS;
4527     }
4528   }
4529 
4530   //     -- Otherwise, the reference shall be an lvalue reference to a
4531   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4532   //        shall be an rvalue reference.
4533   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4534     return ICS;
4535 
4536   //       -- If the initializer expression
4537   //
4538   //            -- is an xvalue, class prvalue, array prvalue or function
4539   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4540   if (RefRelationship == Sema::Ref_Compatible &&
4541       (InitCategory.isXValue() ||
4542        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4543        (InitCategory.isLValue() && T2->isFunctionType()))) {
4544     ICS.setStandard();
4545     ICS.Standard.First = ICK_Identity;
4546     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4547                       : ObjCConversion? ICK_Compatible_Conversion
4548                       : ICK_Identity;
4549     ICS.Standard.Third = ICK_Identity;
4550     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4551     ICS.Standard.setToType(0, T2);
4552     ICS.Standard.setToType(1, T1);
4553     ICS.Standard.setToType(2, T1);
4554     ICS.Standard.ReferenceBinding = true;
4555     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4556     // binding unless we're binding to a class prvalue.
4557     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4558     // allow the use of rvalue references in C++98/03 for the benefit of
4559     // standard library implementors; therefore, we need the xvalue check here.
4560     ICS.Standard.DirectBinding =
4561       S.getLangOpts().CPlusPlus11 ||
4562       !(InitCategory.isPRValue() || T2->isRecordType());
4563     ICS.Standard.IsLvalueReference = !isRValRef;
4564     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4565     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4566     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4567     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4568     ICS.Standard.CopyConstructor = nullptr;
4569     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4570     return ICS;
4571   }
4572 
4573   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4574   //               reference-related to T2, and can be implicitly converted to
4575   //               an xvalue, class prvalue, or function lvalue of type
4576   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4577   //               "cv3 T3",
4578   //
4579   //          then the reference is bound to the value of the initializer
4580   //          expression in the first case and to the result of the conversion
4581   //          in the second case (or, in either case, to an appropriate base
4582   //          class subobject).
4583   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4584       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4585       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4586                                Init, T2, /*AllowRvalues=*/true,
4587                                AllowExplicit)) {
4588     // In the second case, if the reference is an rvalue reference
4589     // and the second standard conversion sequence of the
4590     // user-defined conversion sequence includes an lvalue-to-rvalue
4591     // conversion, the program is ill-formed.
4592     if (ICS.isUserDefined() && isRValRef &&
4593         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4594       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4595 
4596     return ICS;
4597   }
4598 
4599   // A temporary of function type cannot be created; don't even try.
4600   if (T1->isFunctionType())
4601     return ICS;
4602 
4603   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4604   //          initialized from the initializer expression using the
4605   //          rules for a non-reference copy initialization (8.5). The
4606   //          reference is then bound to the temporary. If T1 is
4607   //          reference-related to T2, cv1 must be the same
4608   //          cv-qualification as, or greater cv-qualification than,
4609   //          cv2; otherwise, the program is ill-formed.
4610   if (RefRelationship == Sema::Ref_Related) {
4611     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4612     // we would be reference-compatible or reference-compatible with
4613     // added qualification. But that wasn't the case, so the reference
4614     // initialization fails.
4615     //
4616     // Note that we only want to check address spaces and cvr-qualifiers here.
4617     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4618     Qualifiers T1Quals = T1.getQualifiers();
4619     Qualifiers T2Quals = T2.getQualifiers();
4620     T1Quals.removeObjCGCAttr();
4621     T1Quals.removeObjCLifetime();
4622     T2Quals.removeObjCGCAttr();
4623     T2Quals.removeObjCLifetime();
4624     // MS compiler ignores __unaligned qualifier for references; do the same.
4625     T1Quals.removeUnaligned();
4626     T2Quals.removeUnaligned();
4627     if (!T1Quals.compatiblyIncludes(T2Quals))
4628       return ICS;
4629   }
4630 
4631   // If at least one of the types is a class type, the types are not
4632   // related, and we aren't allowed any user conversions, the
4633   // reference binding fails. This case is important for breaking
4634   // recursion, since TryImplicitConversion below will attempt to
4635   // create a temporary through the use of a copy constructor.
4636   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4637       (T1->isRecordType() || T2->isRecordType()))
4638     return ICS;
4639 
4640   // If T1 is reference-related to T2 and the reference is an rvalue
4641   // reference, the initializer expression shall not be an lvalue.
4642   if (RefRelationship >= Sema::Ref_Related &&
4643       isRValRef && Init->Classify(S.Context).isLValue())
4644     return ICS;
4645 
4646   // C++ [over.ics.ref]p2:
4647   //   When a parameter of reference type is not bound directly to
4648   //   an argument expression, the conversion sequence is the one
4649   //   required to convert the argument expression to the
4650   //   underlying type of the reference according to
4651   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4652   //   to copy-initializing a temporary of the underlying type with
4653   //   the argument expression. Any difference in top-level
4654   //   cv-qualification is subsumed by the initialization itself
4655   //   and does not constitute a conversion.
4656   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4657                               /*AllowExplicit=*/false,
4658                               /*InOverloadResolution=*/false,
4659                               /*CStyle=*/false,
4660                               /*AllowObjCWritebackConversion=*/false,
4661                               /*AllowObjCConversionOnExplicit=*/false);
4662 
4663   // Of course, that's still a reference binding.
4664   if (ICS.isStandard()) {
4665     ICS.Standard.ReferenceBinding = true;
4666     ICS.Standard.IsLvalueReference = !isRValRef;
4667     ICS.Standard.BindsToFunctionLvalue = false;
4668     ICS.Standard.BindsToRvalue = true;
4669     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4670     ICS.Standard.ObjCLifetimeConversionBinding = false;
4671   } else if (ICS.isUserDefined()) {
4672     const ReferenceType *LValRefType =
4673         ICS.UserDefined.ConversionFunction->getReturnType()
4674             ->getAs<LValueReferenceType>();
4675 
4676     // C++ [over.ics.ref]p3:
4677     //   Except for an implicit object parameter, for which see 13.3.1, a
4678     //   standard conversion sequence cannot be formed if it requires [...]
4679     //   binding an rvalue reference to an lvalue other than a function
4680     //   lvalue.
4681     // Note that the function case is not possible here.
4682     if (DeclType->isRValueReferenceType() && LValRefType) {
4683       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4684       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4685       // reference to an rvalue!
4686       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4687       return ICS;
4688     }
4689 
4690     ICS.UserDefined.After.ReferenceBinding = true;
4691     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4692     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4693     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4694     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4695     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4696   }
4697 
4698   return ICS;
4699 }
4700 
4701 static ImplicitConversionSequence
4702 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4703                       bool SuppressUserConversions,
4704                       bool InOverloadResolution,
4705                       bool AllowObjCWritebackConversion,
4706                       bool AllowExplicit = false);
4707 
4708 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4709 /// initializer list From.
4710 static ImplicitConversionSequence
4711 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4712                   bool SuppressUserConversions,
4713                   bool InOverloadResolution,
4714                   bool AllowObjCWritebackConversion) {
4715   // C++11 [over.ics.list]p1:
4716   //   When an argument is an initializer list, it is not an expression and
4717   //   special rules apply for converting it to a parameter type.
4718 
4719   ImplicitConversionSequence Result;
4720   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4721 
4722   // We need a complete type for what follows. Incomplete types can never be
4723   // initialized from init lists.
4724   if (!S.isCompleteType(From->getLocStart(), ToType))
4725     return Result;
4726 
4727   // Per DR1467:
4728   //   If the parameter type is a class X and the initializer list has a single
4729   //   element of type cv U, where U is X or a class derived from X, the
4730   //   implicit conversion sequence is the one required to convert the element
4731   //   to the parameter type.
4732   //
4733   //   Otherwise, if the parameter type is a character array [... ]
4734   //   and the initializer list has a single element that is an
4735   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4736   //   implicit conversion sequence is the identity conversion.
4737   if (From->getNumInits() == 1) {
4738     if (ToType->isRecordType()) {
4739       QualType InitType = From->getInit(0)->getType();
4740       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4741           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4742         return TryCopyInitialization(S, From->getInit(0), ToType,
4743                                      SuppressUserConversions,
4744                                      InOverloadResolution,
4745                                      AllowObjCWritebackConversion);
4746     }
4747     // FIXME: Check the other conditions here: array of character type,
4748     // initializer is a string literal.
4749     if (ToType->isArrayType()) {
4750       InitializedEntity Entity =
4751         InitializedEntity::InitializeParameter(S.Context, ToType,
4752                                                /*Consumed=*/false);
4753       if (S.CanPerformCopyInitialization(Entity, From)) {
4754         Result.setStandard();
4755         Result.Standard.setAsIdentityConversion();
4756         Result.Standard.setFromType(ToType);
4757         Result.Standard.setAllToTypes(ToType);
4758         return Result;
4759       }
4760     }
4761   }
4762 
4763   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4764   // C++11 [over.ics.list]p2:
4765   //   If the parameter type is std::initializer_list<X> or "array of X" and
4766   //   all the elements can be implicitly converted to X, the implicit
4767   //   conversion sequence is the worst conversion necessary to convert an
4768   //   element of the list to X.
4769   //
4770   // C++14 [over.ics.list]p3:
4771   //   Otherwise, if the parameter type is "array of N X", if the initializer
4772   //   list has exactly N elements or if it has fewer than N elements and X is
4773   //   default-constructible, and if all the elements of the initializer list
4774   //   can be implicitly converted to X, the implicit conversion sequence is
4775   //   the worst conversion necessary to convert an element of the list to X.
4776   //
4777   // FIXME: We're missing a lot of these checks.
4778   bool toStdInitializerList = false;
4779   QualType X;
4780   if (ToType->isArrayType())
4781     X = S.Context.getAsArrayType(ToType)->getElementType();
4782   else
4783     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4784   if (!X.isNull()) {
4785     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4786       Expr *Init = From->getInit(i);
4787       ImplicitConversionSequence ICS =
4788           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4789                                 InOverloadResolution,
4790                                 AllowObjCWritebackConversion);
4791       // If a single element isn't convertible, fail.
4792       if (ICS.isBad()) {
4793         Result = ICS;
4794         break;
4795       }
4796       // Otherwise, look for the worst conversion.
4797       if (Result.isBad() ||
4798           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4799                                              Result) ==
4800               ImplicitConversionSequence::Worse)
4801         Result = ICS;
4802     }
4803 
4804     // For an empty list, we won't have computed any conversion sequence.
4805     // Introduce the identity conversion sequence.
4806     if (From->getNumInits() == 0) {
4807       Result.setStandard();
4808       Result.Standard.setAsIdentityConversion();
4809       Result.Standard.setFromType(ToType);
4810       Result.Standard.setAllToTypes(ToType);
4811     }
4812 
4813     Result.setStdInitializerListElement(toStdInitializerList);
4814     return Result;
4815   }
4816 
4817   // C++14 [over.ics.list]p4:
4818   // C++11 [over.ics.list]p3:
4819   //   Otherwise, if the parameter is a non-aggregate class X and overload
4820   //   resolution chooses a single best constructor [...] the implicit
4821   //   conversion sequence is a user-defined conversion sequence. If multiple
4822   //   constructors are viable but none is better than the others, the
4823   //   implicit conversion sequence is a user-defined conversion sequence.
4824   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4825     // This function can deal with initializer lists.
4826     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4827                                     /*AllowExplicit=*/false,
4828                                     InOverloadResolution, /*CStyle=*/false,
4829                                     AllowObjCWritebackConversion,
4830                                     /*AllowObjCConversionOnExplicit=*/false);
4831   }
4832 
4833   // C++14 [over.ics.list]p5:
4834   // C++11 [over.ics.list]p4:
4835   //   Otherwise, if the parameter has an aggregate type which can be
4836   //   initialized from the initializer list [...] the implicit conversion
4837   //   sequence is a user-defined conversion sequence.
4838   if (ToType->isAggregateType()) {
4839     // Type is an aggregate, argument is an init list. At this point it comes
4840     // down to checking whether the initialization works.
4841     // FIXME: Find out whether this parameter is consumed or not.
4842     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4843     // need to call into the initialization code here; overload resolution
4844     // should not be doing that.
4845     InitializedEntity Entity =
4846         InitializedEntity::InitializeParameter(S.Context, ToType,
4847                                                /*Consumed=*/false);
4848     if (S.CanPerformCopyInitialization(Entity, From)) {
4849       Result.setUserDefined();
4850       Result.UserDefined.Before.setAsIdentityConversion();
4851       // Initializer lists don't have a type.
4852       Result.UserDefined.Before.setFromType(QualType());
4853       Result.UserDefined.Before.setAllToTypes(QualType());
4854 
4855       Result.UserDefined.After.setAsIdentityConversion();
4856       Result.UserDefined.After.setFromType(ToType);
4857       Result.UserDefined.After.setAllToTypes(ToType);
4858       Result.UserDefined.ConversionFunction = nullptr;
4859     }
4860     return Result;
4861   }
4862 
4863   // C++14 [over.ics.list]p6:
4864   // C++11 [over.ics.list]p5:
4865   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4866   if (ToType->isReferenceType()) {
4867     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4868     // mention initializer lists in any way. So we go by what list-
4869     // initialization would do and try to extrapolate from that.
4870 
4871     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4872 
4873     // If the initializer list has a single element that is reference-related
4874     // to the parameter type, we initialize the reference from that.
4875     if (From->getNumInits() == 1) {
4876       Expr *Init = From->getInit(0);
4877 
4878       QualType T2 = Init->getType();
4879 
4880       // If the initializer is the address of an overloaded function, try
4881       // to resolve the overloaded function. If all goes well, T2 is the
4882       // type of the resulting function.
4883       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4884         DeclAccessPair Found;
4885         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4886                                    Init, ToType, false, Found))
4887           T2 = Fn->getType();
4888       }
4889 
4890       // Compute some basic properties of the types and the initializer.
4891       bool dummy1 = false;
4892       bool dummy2 = false;
4893       bool dummy3 = false;
4894       Sema::ReferenceCompareResult RefRelationship
4895         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4896                                          dummy2, dummy3);
4897 
4898       if (RefRelationship >= Sema::Ref_Related) {
4899         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4900                                 SuppressUserConversions,
4901                                 /*AllowExplicit=*/false);
4902       }
4903     }
4904 
4905     // Otherwise, we bind the reference to a temporary created from the
4906     // initializer list.
4907     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4908                                InOverloadResolution,
4909                                AllowObjCWritebackConversion);
4910     if (Result.isFailure())
4911       return Result;
4912     assert(!Result.isEllipsis() &&
4913            "Sub-initialization cannot result in ellipsis conversion.");
4914 
4915     // Can we even bind to a temporary?
4916     if (ToType->isRValueReferenceType() ||
4917         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4918       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4919                                             Result.UserDefined.After;
4920       SCS.ReferenceBinding = true;
4921       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4922       SCS.BindsToRvalue = true;
4923       SCS.BindsToFunctionLvalue = false;
4924       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4925       SCS.ObjCLifetimeConversionBinding = false;
4926     } else
4927       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4928                     From, ToType);
4929     return Result;
4930   }
4931 
4932   // C++14 [over.ics.list]p7:
4933   // C++11 [over.ics.list]p6:
4934   //   Otherwise, if the parameter type is not a class:
4935   if (!ToType->isRecordType()) {
4936     //    - if the initializer list has one element that is not itself an
4937     //      initializer list, the implicit conversion sequence is the one
4938     //      required to convert the element to the parameter type.
4939     unsigned NumInits = From->getNumInits();
4940     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4941       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4942                                      SuppressUserConversions,
4943                                      InOverloadResolution,
4944                                      AllowObjCWritebackConversion);
4945     //    - if the initializer list has no elements, the implicit conversion
4946     //      sequence is the identity conversion.
4947     else if (NumInits == 0) {
4948       Result.setStandard();
4949       Result.Standard.setAsIdentityConversion();
4950       Result.Standard.setFromType(ToType);
4951       Result.Standard.setAllToTypes(ToType);
4952     }
4953     return Result;
4954   }
4955 
4956   // C++14 [over.ics.list]p8:
4957   // C++11 [over.ics.list]p7:
4958   //   In all cases other than those enumerated above, no conversion is possible
4959   return Result;
4960 }
4961 
4962 /// TryCopyInitialization - Try to copy-initialize a value of type
4963 /// ToType from the expression From. Return the implicit conversion
4964 /// sequence required to pass this argument, which may be a bad
4965 /// conversion sequence (meaning that the argument cannot be passed to
4966 /// a parameter of this type). If @p SuppressUserConversions, then we
4967 /// do not permit any user-defined conversion sequences.
4968 static ImplicitConversionSequence
4969 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4970                       bool SuppressUserConversions,
4971                       bool InOverloadResolution,
4972                       bool AllowObjCWritebackConversion,
4973                       bool AllowExplicit) {
4974   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4975     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4976                              InOverloadResolution,AllowObjCWritebackConversion);
4977 
4978   if (ToType->isReferenceType())
4979     return TryReferenceInit(S, From, ToType,
4980                             /*FIXME:*/From->getLocStart(),
4981                             SuppressUserConversions,
4982                             AllowExplicit);
4983 
4984   return TryImplicitConversion(S, From, ToType,
4985                                SuppressUserConversions,
4986                                /*AllowExplicit=*/false,
4987                                InOverloadResolution,
4988                                /*CStyle=*/false,
4989                                AllowObjCWritebackConversion,
4990                                /*AllowObjCConversionOnExplicit=*/false);
4991 }
4992 
4993 static bool TryCopyInitialization(const CanQualType FromQTy,
4994                                   const CanQualType ToQTy,
4995                                   Sema &S,
4996                                   SourceLocation Loc,
4997                                   ExprValueKind FromVK) {
4998   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4999   ImplicitConversionSequence ICS =
5000     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5001 
5002   return !ICS.isBad();
5003 }
5004 
5005 /// TryObjectArgumentInitialization - Try to initialize the object
5006 /// parameter of the given member function (@c Method) from the
5007 /// expression @p From.
5008 static ImplicitConversionSequence
5009 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5010                                 Expr::Classification FromClassification,
5011                                 CXXMethodDecl *Method,
5012                                 CXXRecordDecl *ActingContext) {
5013   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5014   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5015   //                 const volatile object.
5016   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5017     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5018   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5019 
5020   // Set up the conversion sequence as a "bad" conversion, to allow us
5021   // to exit early.
5022   ImplicitConversionSequence ICS;
5023 
5024   // We need to have an object of class type.
5025   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5026     FromType = PT->getPointeeType();
5027 
5028     // When we had a pointer, it's implicitly dereferenced, so we
5029     // better have an lvalue.
5030     assert(FromClassification.isLValue());
5031   }
5032 
5033   assert(FromType->isRecordType());
5034 
5035   // C++0x [over.match.funcs]p4:
5036   //   For non-static member functions, the type of the implicit object
5037   //   parameter is
5038   //
5039   //     - "lvalue reference to cv X" for functions declared without a
5040   //        ref-qualifier or with the & ref-qualifier
5041   //     - "rvalue reference to cv X" for functions declared with the &&
5042   //        ref-qualifier
5043   //
5044   // where X is the class of which the function is a member and cv is the
5045   // cv-qualification on the member function declaration.
5046   //
5047   // However, when finding an implicit conversion sequence for the argument, we
5048   // are not allowed to perform user-defined conversions
5049   // (C++ [over.match.funcs]p5). We perform a simplified version of
5050   // reference binding here, that allows class rvalues to bind to
5051   // non-constant references.
5052 
5053   // First check the qualifiers.
5054   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5055   if (ImplicitParamType.getCVRQualifiers()
5056                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5057       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5058     ICS.setBad(BadConversionSequence::bad_qualifiers,
5059                FromType, ImplicitParamType);
5060     return ICS;
5061   }
5062 
5063   // Check that we have either the same type or a derived type. It
5064   // affects the conversion rank.
5065   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5066   ImplicitConversionKind SecondKind;
5067   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5068     SecondKind = ICK_Identity;
5069   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5070     SecondKind = ICK_Derived_To_Base;
5071   else {
5072     ICS.setBad(BadConversionSequence::unrelated_class,
5073                FromType, ImplicitParamType);
5074     return ICS;
5075   }
5076 
5077   // Check the ref-qualifier.
5078   switch (Method->getRefQualifier()) {
5079   case RQ_None:
5080     // Do nothing; we don't care about lvalueness or rvalueness.
5081     break;
5082 
5083   case RQ_LValue:
5084     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5085       // non-const lvalue reference cannot bind to an rvalue
5086       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5087                  ImplicitParamType);
5088       return ICS;
5089     }
5090     break;
5091 
5092   case RQ_RValue:
5093     if (!FromClassification.isRValue()) {
5094       // rvalue reference cannot bind to an lvalue
5095       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5096                  ImplicitParamType);
5097       return ICS;
5098     }
5099     break;
5100   }
5101 
5102   // Success. Mark this as a reference binding.
5103   ICS.setStandard();
5104   ICS.Standard.setAsIdentityConversion();
5105   ICS.Standard.Second = SecondKind;
5106   ICS.Standard.setFromType(FromType);
5107   ICS.Standard.setAllToTypes(ImplicitParamType);
5108   ICS.Standard.ReferenceBinding = true;
5109   ICS.Standard.DirectBinding = true;
5110   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5111   ICS.Standard.BindsToFunctionLvalue = false;
5112   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5113   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5114     = (Method->getRefQualifier() == RQ_None);
5115   return ICS;
5116 }
5117 
5118 /// PerformObjectArgumentInitialization - Perform initialization of
5119 /// the implicit object parameter for the given Method with the given
5120 /// expression.
5121 ExprResult
5122 Sema::PerformObjectArgumentInitialization(Expr *From,
5123                                           NestedNameSpecifier *Qualifier,
5124                                           NamedDecl *FoundDecl,
5125                                           CXXMethodDecl *Method) {
5126   QualType FromRecordType, DestType;
5127   QualType ImplicitParamRecordType  =
5128     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5129 
5130   Expr::Classification FromClassification;
5131   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5132     FromRecordType = PT->getPointeeType();
5133     DestType = Method->getThisType(Context);
5134     FromClassification = Expr::Classification::makeSimpleLValue();
5135   } else {
5136     FromRecordType = From->getType();
5137     DestType = ImplicitParamRecordType;
5138     FromClassification = From->Classify(Context);
5139   }
5140 
5141   // Note that we always use the true parent context when performing
5142   // the actual argument initialization.
5143   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5144       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5145       Method->getParent());
5146   if (ICS.isBad()) {
5147     switch (ICS.Bad.Kind) {
5148     case BadConversionSequence::bad_qualifiers: {
5149       Qualifiers FromQs = FromRecordType.getQualifiers();
5150       Qualifiers ToQs = DestType.getQualifiers();
5151       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5152       if (CVR) {
5153         Diag(From->getLocStart(),
5154              diag::err_member_function_call_bad_cvr)
5155           << Method->getDeclName() << FromRecordType << (CVR - 1)
5156           << From->getSourceRange();
5157         Diag(Method->getLocation(), diag::note_previous_decl)
5158           << Method->getDeclName();
5159         return ExprError();
5160       }
5161       break;
5162     }
5163 
5164     case BadConversionSequence::lvalue_ref_to_rvalue:
5165     case BadConversionSequence::rvalue_ref_to_lvalue: {
5166       bool IsRValueQualified =
5167         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5168       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5169         << Method->getDeclName() << FromClassification.isRValue()
5170         << IsRValueQualified;
5171       Diag(Method->getLocation(), diag::note_previous_decl)
5172         << Method->getDeclName();
5173       return ExprError();
5174     }
5175 
5176     case BadConversionSequence::no_conversion:
5177     case BadConversionSequence::unrelated_class:
5178       break;
5179     }
5180 
5181     return Diag(From->getLocStart(),
5182                 diag::err_member_function_call_bad_type)
5183        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5184   }
5185 
5186   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5187     ExprResult FromRes =
5188       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5189     if (FromRes.isInvalid())
5190       return ExprError();
5191     From = FromRes.get();
5192   }
5193 
5194   if (!Context.hasSameType(From->getType(), DestType))
5195     From = ImpCastExprToType(From, DestType, CK_NoOp,
5196                              From->getValueKind()).get();
5197   return From;
5198 }
5199 
5200 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5201 /// expression From to bool (C++0x [conv]p3).
5202 static ImplicitConversionSequence
5203 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5204   return TryImplicitConversion(S, From, S.Context.BoolTy,
5205                                /*SuppressUserConversions=*/false,
5206                                /*AllowExplicit=*/true,
5207                                /*InOverloadResolution=*/false,
5208                                /*CStyle=*/false,
5209                                /*AllowObjCWritebackConversion=*/false,
5210                                /*AllowObjCConversionOnExplicit=*/false);
5211 }
5212 
5213 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5214 /// of the expression From to bool (C++0x [conv]p3).
5215 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5216   if (checkPlaceholderForOverload(*this, From))
5217     return ExprError();
5218 
5219   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5220   if (!ICS.isBad())
5221     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5222 
5223   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5224     return Diag(From->getLocStart(),
5225                 diag::err_typecheck_bool_condition)
5226                   << From->getType() << From->getSourceRange();
5227   return ExprError();
5228 }
5229 
5230 /// Check that the specified conversion is permitted in a converted constant
5231 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5232 /// is acceptable.
5233 static bool CheckConvertedConstantConversions(Sema &S,
5234                                               StandardConversionSequence &SCS) {
5235   // Since we know that the target type is an integral or unscoped enumeration
5236   // type, most conversion kinds are impossible. All possible First and Third
5237   // conversions are fine.
5238   switch (SCS.Second) {
5239   case ICK_Identity:
5240   case ICK_Function_Conversion:
5241   case ICK_Integral_Promotion:
5242   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5243   case ICK_Zero_Queue_Conversion:
5244     return true;
5245 
5246   case ICK_Boolean_Conversion:
5247     // Conversion from an integral or unscoped enumeration type to bool is
5248     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5249     // conversion, so we allow it in a converted constant expression.
5250     //
5251     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5252     // a lot of popular code. We should at least add a warning for this
5253     // (non-conforming) extension.
5254     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5255            SCS.getToType(2)->isBooleanType();
5256 
5257   case ICK_Pointer_Conversion:
5258   case ICK_Pointer_Member:
5259     // C++1z: null pointer conversions and null member pointer conversions are
5260     // only permitted if the source type is std::nullptr_t.
5261     return SCS.getFromType()->isNullPtrType();
5262 
5263   case ICK_Floating_Promotion:
5264   case ICK_Complex_Promotion:
5265   case ICK_Floating_Conversion:
5266   case ICK_Complex_Conversion:
5267   case ICK_Floating_Integral:
5268   case ICK_Compatible_Conversion:
5269   case ICK_Derived_To_Base:
5270   case ICK_Vector_Conversion:
5271   case ICK_Vector_Splat:
5272   case ICK_Complex_Real:
5273   case ICK_Block_Pointer_Conversion:
5274   case ICK_TransparentUnionConversion:
5275   case ICK_Writeback_Conversion:
5276   case ICK_Zero_Event_Conversion:
5277   case ICK_C_Only_Conversion:
5278   case ICK_Incompatible_Pointer_Conversion:
5279     return false;
5280 
5281   case ICK_Lvalue_To_Rvalue:
5282   case ICK_Array_To_Pointer:
5283   case ICK_Function_To_Pointer:
5284     llvm_unreachable("found a first conversion kind in Second");
5285 
5286   case ICK_Qualification:
5287     llvm_unreachable("found a third conversion kind in Second");
5288 
5289   case ICK_Num_Conversion_Kinds:
5290     break;
5291   }
5292 
5293   llvm_unreachable("unknown conversion kind");
5294 }
5295 
5296 /// CheckConvertedConstantExpression - Check that the expression From is a
5297 /// converted constant expression of type T, perform the conversion and produce
5298 /// the converted expression, per C++11 [expr.const]p3.
5299 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5300                                                    QualType T, APValue &Value,
5301                                                    Sema::CCEKind CCE,
5302                                                    bool RequireInt) {
5303   assert(S.getLangOpts().CPlusPlus11 &&
5304          "converted constant expression outside C++11");
5305 
5306   if (checkPlaceholderForOverload(S, From))
5307     return ExprError();
5308 
5309   // C++1z [expr.const]p3:
5310   //  A converted constant expression of type T is an expression,
5311   //  implicitly converted to type T, where the converted
5312   //  expression is a constant expression and the implicit conversion
5313   //  sequence contains only [... list of conversions ...].
5314   // C++1z [stmt.if]p2:
5315   //  If the if statement is of the form if constexpr, the value of the
5316   //  condition shall be a contextually converted constant expression of type
5317   //  bool.
5318   ImplicitConversionSequence ICS =
5319       CCE == Sema::CCEK_ConstexprIf
5320           ? TryContextuallyConvertToBool(S, From)
5321           : TryCopyInitialization(S, From, T,
5322                                   /*SuppressUserConversions=*/false,
5323                                   /*InOverloadResolution=*/false,
5324                                   /*AllowObjcWritebackConversion=*/false,
5325                                   /*AllowExplicit=*/false);
5326   StandardConversionSequence *SCS = nullptr;
5327   switch (ICS.getKind()) {
5328   case ImplicitConversionSequence::StandardConversion:
5329     SCS = &ICS.Standard;
5330     break;
5331   case ImplicitConversionSequence::UserDefinedConversion:
5332     // We are converting to a non-class type, so the Before sequence
5333     // must be trivial.
5334     SCS = &ICS.UserDefined.After;
5335     break;
5336   case ImplicitConversionSequence::AmbiguousConversion:
5337   case ImplicitConversionSequence::BadConversion:
5338     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5339       return S.Diag(From->getLocStart(),
5340                     diag::err_typecheck_converted_constant_expression)
5341                 << From->getType() << From->getSourceRange() << T;
5342     return ExprError();
5343 
5344   case ImplicitConversionSequence::EllipsisConversion:
5345     llvm_unreachable("ellipsis conversion in converted constant expression");
5346   }
5347 
5348   // Check that we would only use permitted conversions.
5349   if (!CheckConvertedConstantConversions(S, *SCS)) {
5350     return S.Diag(From->getLocStart(),
5351                   diag::err_typecheck_converted_constant_expression_disallowed)
5352              << From->getType() << From->getSourceRange() << T;
5353   }
5354   // [...] and where the reference binding (if any) binds directly.
5355   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5356     return S.Diag(From->getLocStart(),
5357                   diag::err_typecheck_converted_constant_expression_indirect)
5358              << From->getType() << From->getSourceRange() << T;
5359   }
5360 
5361   ExprResult Result =
5362       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5363   if (Result.isInvalid())
5364     return Result;
5365 
5366   // Check for a narrowing implicit conversion.
5367   APValue PreNarrowingValue;
5368   QualType PreNarrowingType;
5369   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5370                                 PreNarrowingType)) {
5371   case NK_Dependent_Narrowing:
5372     // Implicit conversion to a narrower type, but the expression is
5373     // value-dependent so we can't tell whether it's actually narrowing.
5374   case NK_Variable_Narrowing:
5375     // Implicit conversion to a narrower type, and the value is not a constant
5376     // expression. We'll diagnose this in a moment.
5377   case NK_Not_Narrowing:
5378     break;
5379 
5380   case NK_Constant_Narrowing:
5381     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5382       << CCE << /*Constant*/1
5383       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5384     break;
5385 
5386   case NK_Type_Narrowing:
5387     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5388       << CCE << /*Constant*/0 << From->getType() << T;
5389     break;
5390   }
5391 
5392   if (Result.get()->isValueDependent()) {
5393     Value = APValue();
5394     return Result;
5395   }
5396 
5397   // Check the expression is a constant expression.
5398   SmallVector<PartialDiagnosticAt, 8> Notes;
5399   Expr::EvalResult Eval;
5400   Eval.Diag = &Notes;
5401 
5402   if ((T->isReferenceType()
5403            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5404            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5405       (RequireInt && !Eval.Val.isInt())) {
5406     // The expression can't be folded, so we can't keep it at this position in
5407     // the AST.
5408     Result = ExprError();
5409   } else {
5410     Value = Eval.Val;
5411 
5412     if (Notes.empty()) {
5413       // It's a constant expression.
5414       return Result;
5415     }
5416   }
5417 
5418   // It's not a constant expression. Produce an appropriate diagnostic.
5419   if (Notes.size() == 1 &&
5420       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5421     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5422   else {
5423     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5424       << CCE << From->getSourceRange();
5425     for (unsigned I = 0; I < Notes.size(); ++I)
5426       S.Diag(Notes[I].first, Notes[I].second);
5427   }
5428   return ExprError();
5429 }
5430 
5431 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5432                                                   APValue &Value, CCEKind CCE) {
5433   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5434 }
5435 
5436 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5437                                                   llvm::APSInt &Value,
5438                                                   CCEKind CCE) {
5439   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5440 
5441   APValue V;
5442   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5443   if (!R.isInvalid() && !R.get()->isValueDependent())
5444     Value = V.getInt();
5445   return R;
5446 }
5447 
5448 
5449 /// dropPointerConversions - If the given standard conversion sequence
5450 /// involves any pointer conversions, remove them.  This may change
5451 /// the result type of the conversion sequence.
5452 static void dropPointerConversion(StandardConversionSequence &SCS) {
5453   if (SCS.Second == ICK_Pointer_Conversion) {
5454     SCS.Second = ICK_Identity;
5455     SCS.Third = ICK_Identity;
5456     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5457   }
5458 }
5459 
5460 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5461 /// convert the expression From to an Objective-C pointer type.
5462 static ImplicitConversionSequence
5463 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5464   // Do an implicit conversion to 'id'.
5465   QualType Ty = S.Context.getObjCIdType();
5466   ImplicitConversionSequence ICS
5467     = TryImplicitConversion(S, From, Ty,
5468                             // FIXME: Are these flags correct?
5469                             /*SuppressUserConversions=*/false,
5470                             /*AllowExplicit=*/true,
5471                             /*InOverloadResolution=*/false,
5472                             /*CStyle=*/false,
5473                             /*AllowObjCWritebackConversion=*/false,
5474                             /*AllowObjCConversionOnExplicit=*/true);
5475 
5476   // Strip off any final conversions to 'id'.
5477   switch (ICS.getKind()) {
5478   case ImplicitConversionSequence::BadConversion:
5479   case ImplicitConversionSequence::AmbiguousConversion:
5480   case ImplicitConversionSequence::EllipsisConversion:
5481     break;
5482 
5483   case ImplicitConversionSequence::UserDefinedConversion:
5484     dropPointerConversion(ICS.UserDefined.After);
5485     break;
5486 
5487   case ImplicitConversionSequence::StandardConversion:
5488     dropPointerConversion(ICS.Standard);
5489     break;
5490   }
5491 
5492   return ICS;
5493 }
5494 
5495 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5496 /// conversion of the expression From to an Objective-C pointer type.
5497 /// Returns a valid but null ExprResult if no conversion sequence exists.
5498 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5499   if (checkPlaceholderForOverload(*this, From))
5500     return ExprError();
5501 
5502   QualType Ty = Context.getObjCIdType();
5503   ImplicitConversionSequence ICS =
5504     TryContextuallyConvertToObjCPointer(*this, From);
5505   if (!ICS.isBad())
5506     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5507   return ExprResult();
5508 }
5509 
5510 /// Determine whether the provided type is an integral type, or an enumeration
5511 /// type of a permitted flavor.
5512 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5513   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5514                                  : T->isIntegralOrUnscopedEnumerationType();
5515 }
5516 
5517 static ExprResult
5518 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5519                             Sema::ContextualImplicitConverter &Converter,
5520                             QualType T, UnresolvedSetImpl &ViableConversions) {
5521 
5522   if (Converter.Suppress)
5523     return ExprError();
5524 
5525   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5526   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5527     CXXConversionDecl *Conv =
5528         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5529     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5530     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5531   }
5532   return From;
5533 }
5534 
5535 static bool
5536 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5537                            Sema::ContextualImplicitConverter &Converter,
5538                            QualType T, bool HadMultipleCandidates,
5539                            UnresolvedSetImpl &ExplicitConversions) {
5540   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5541     DeclAccessPair Found = ExplicitConversions[0];
5542     CXXConversionDecl *Conversion =
5543         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5544 
5545     // The user probably meant to invoke the given explicit
5546     // conversion; use it.
5547     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5548     std::string TypeStr;
5549     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5550 
5551     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5552         << FixItHint::CreateInsertion(From->getLocStart(),
5553                                       "static_cast<" + TypeStr + ">(")
5554         << FixItHint::CreateInsertion(
5555                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5556     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5557 
5558     // If we aren't in a SFINAE context, build a call to the
5559     // explicit conversion function.
5560     if (SemaRef.isSFINAEContext())
5561       return true;
5562 
5563     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5564     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5565                                                        HadMultipleCandidates);
5566     if (Result.isInvalid())
5567       return true;
5568     // Record usage of conversion in an implicit cast.
5569     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5570                                     CK_UserDefinedConversion, Result.get(),
5571                                     nullptr, Result.get()->getValueKind());
5572   }
5573   return false;
5574 }
5575 
5576 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5577                              Sema::ContextualImplicitConverter &Converter,
5578                              QualType T, bool HadMultipleCandidates,
5579                              DeclAccessPair &Found) {
5580   CXXConversionDecl *Conversion =
5581       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5582   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5583 
5584   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5585   if (!Converter.SuppressConversion) {
5586     if (SemaRef.isSFINAEContext())
5587       return true;
5588 
5589     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5590         << From->getSourceRange();
5591   }
5592 
5593   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5594                                                      HadMultipleCandidates);
5595   if (Result.isInvalid())
5596     return true;
5597   // Record usage of conversion in an implicit cast.
5598   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5599                                   CK_UserDefinedConversion, Result.get(),
5600                                   nullptr, Result.get()->getValueKind());
5601   return false;
5602 }
5603 
5604 static ExprResult finishContextualImplicitConversion(
5605     Sema &SemaRef, SourceLocation Loc, Expr *From,
5606     Sema::ContextualImplicitConverter &Converter) {
5607   if (!Converter.match(From->getType()) && !Converter.Suppress)
5608     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5609         << From->getSourceRange();
5610 
5611   return SemaRef.DefaultLvalueConversion(From);
5612 }
5613 
5614 static void
5615 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5616                                   UnresolvedSetImpl &ViableConversions,
5617                                   OverloadCandidateSet &CandidateSet) {
5618   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5619     DeclAccessPair FoundDecl = ViableConversions[I];
5620     NamedDecl *D = FoundDecl.getDecl();
5621     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5622     if (isa<UsingShadowDecl>(D))
5623       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5624 
5625     CXXConversionDecl *Conv;
5626     FunctionTemplateDecl *ConvTemplate;
5627     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5628       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5629     else
5630       Conv = cast<CXXConversionDecl>(D);
5631 
5632     if (ConvTemplate)
5633       SemaRef.AddTemplateConversionCandidate(
5634         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5635         /*AllowObjCConversionOnExplicit=*/false);
5636     else
5637       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5638                                      ToType, CandidateSet,
5639                                      /*AllowObjCConversionOnExplicit=*/false);
5640   }
5641 }
5642 
5643 /// \brief Attempt to convert the given expression to a type which is accepted
5644 /// by the given converter.
5645 ///
5646 /// This routine will attempt to convert an expression of class type to a
5647 /// type accepted by the specified converter. In C++11 and before, the class
5648 /// must have a single non-explicit conversion function converting to a matching
5649 /// type. In C++1y, there can be multiple such conversion functions, but only
5650 /// one target type.
5651 ///
5652 /// \param Loc The source location of the construct that requires the
5653 /// conversion.
5654 ///
5655 /// \param From The expression we're converting from.
5656 ///
5657 /// \param Converter Used to control and diagnose the conversion process.
5658 ///
5659 /// \returns The expression, converted to an integral or enumeration type if
5660 /// successful.
5661 ExprResult Sema::PerformContextualImplicitConversion(
5662     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5663   // We can't perform any more checking for type-dependent expressions.
5664   if (From->isTypeDependent())
5665     return From;
5666 
5667   // Process placeholders immediately.
5668   if (From->hasPlaceholderType()) {
5669     ExprResult result = CheckPlaceholderExpr(From);
5670     if (result.isInvalid())
5671       return result;
5672     From = result.get();
5673   }
5674 
5675   // If the expression already has a matching type, we're golden.
5676   QualType T = From->getType();
5677   if (Converter.match(T))
5678     return DefaultLvalueConversion(From);
5679 
5680   // FIXME: Check for missing '()' if T is a function type?
5681 
5682   // We can only perform contextual implicit conversions on objects of class
5683   // type.
5684   const RecordType *RecordTy = T->getAs<RecordType>();
5685   if (!RecordTy || !getLangOpts().CPlusPlus) {
5686     if (!Converter.Suppress)
5687       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5688     return From;
5689   }
5690 
5691   // We must have a complete class type.
5692   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5693     ContextualImplicitConverter &Converter;
5694     Expr *From;
5695 
5696     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5697         : Converter(Converter), From(From) {}
5698 
5699     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5700       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5701     }
5702   } IncompleteDiagnoser(Converter, From);
5703 
5704   if (Converter.Suppress ? !isCompleteType(Loc, T)
5705                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5706     return From;
5707 
5708   // Look for a conversion to an integral or enumeration type.
5709   UnresolvedSet<4>
5710       ViableConversions; // These are *potentially* viable in C++1y.
5711   UnresolvedSet<4> ExplicitConversions;
5712   const auto &Conversions =
5713       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5714 
5715   bool HadMultipleCandidates =
5716       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5717 
5718   // To check that there is only one target type, in C++1y:
5719   QualType ToType;
5720   bool HasUniqueTargetType = true;
5721 
5722   // Collect explicit or viable (potentially in C++1y) conversions.
5723   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5724     NamedDecl *D = (*I)->getUnderlyingDecl();
5725     CXXConversionDecl *Conversion;
5726     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5727     if (ConvTemplate) {
5728       if (getLangOpts().CPlusPlus14)
5729         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5730       else
5731         continue; // C++11 does not consider conversion operator templates(?).
5732     } else
5733       Conversion = cast<CXXConversionDecl>(D);
5734 
5735     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5736            "Conversion operator templates are considered potentially "
5737            "viable in C++1y");
5738 
5739     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5740     if (Converter.match(CurToType) || ConvTemplate) {
5741 
5742       if (Conversion->isExplicit()) {
5743         // FIXME: For C++1y, do we need this restriction?
5744         // cf. diagnoseNoViableConversion()
5745         if (!ConvTemplate)
5746           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5747       } else {
5748         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5749           if (ToType.isNull())
5750             ToType = CurToType.getUnqualifiedType();
5751           else if (HasUniqueTargetType &&
5752                    (CurToType.getUnqualifiedType() != ToType))
5753             HasUniqueTargetType = false;
5754         }
5755         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5756       }
5757     }
5758   }
5759 
5760   if (getLangOpts().CPlusPlus14) {
5761     // C++1y [conv]p6:
5762     // ... An expression e of class type E appearing in such a context
5763     // is said to be contextually implicitly converted to a specified
5764     // type T and is well-formed if and only if e can be implicitly
5765     // converted to a type T that is determined as follows: E is searched
5766     // for conversion functions whose return type is cv T or reference to
5767     // cv T such that T is allowed by the context. There shall be
5768     // exactly one such T.
5769 
5770     // If no unique T is found:
5771     if (ToType.isNull()) {
5772       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5773                                      HadMultipleCandidates,
5774                                      ExplicitConversions))
5775         return ExprError();
5776       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5777     }
5778 
5779     // If more than one unique Ts are found:
5780     if (!HasUniqueTargetType)
5781       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5782                                          ViableConversions);
5783 
5784     // If one unique T is found:
5785     // First, build a candidate set from the previously recorded
5786     // potentially viable conversions.
5787     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5788     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5789                                       CandidateSet);
5790 
5791     // Then, perform overload resolution over the candidate set.
5792     OverloadCandidateSet::iterator Best;
5793     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5794     case OR_Success: {
5795       // Apply this conversion.
5796       DeclAccessPair Found =
5797           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5798       if (recordConversion(*this, Loc, From, Converter, T,
5799                            HadMultipleCandidates, Found))
5800         return ExprError();
5801       break;
5802     }
5803     case OR_Ambiguous:
5804       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5805                                          ViableConversions);
5806     case OR_No_Viable_Function:
5807       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5808                                      HadMultipleCandidates,
5809                                      ExplicitConversions))
5810         return ExprError();
5811       LLVM_FALLTHROUGH;
5812     case OR_Deleted:
5813       // We'll complain below about a non-integral condition type.
5814       break;
5815     }
5816   } else {
5817     switch (ViableConversions.size()) {
5818     case 0: {
5819       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5820                                      HadMultipleCandidates,
5821                                      ExplicitConversions))
5822         return ExprError();
5823 
5824       // We'll complain below about a non-integral condition type.
5825       break;
5826     }
5827     case 1: {
5828       // Apply this conversion.
5829       DeclAccessPair Found = ViableConversions[0];
5830       if (recordConversion(*this, Loc, From, Converter, T,
5831                            HadMultipleCandidates, Found))
5832         return ExprError();
5833       break;
5834     }
5835     default:
5836       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5837                                          ViableConversions);
5838     }
5839   }
5840 
5841   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5842 }
5843 
5844 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5845 /// an acceptable non-member overloaded operator for a call whose
5846 /// arguments have types T1 (and, if non-empty, T2). This routine
5847 /// implements the check in C++ [over.match.oper]p3b2 concerning
5848 /// enumeration types.
5849 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5850                                                    FunctionDecl *Fn,
5851                                                    ArrayRef<Expr *> Args) {
5852   QualType T1 = Args[0]->getType();
5853   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5854 
5855   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5856     return true;
5857 
5858   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5859     return true;
5860 
5861   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5862   if (Proto->getNumParams() < 1)
5863     return false;
5864 
5865   if (T1->isEnumeralType()) {
5866     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5867     if (Context.hasSameUnqualifiedType(T1, ArgType))
5868       return true;
5869   }
5870 
5871   if (Proto->getNumParams() < 2)
5872     return false;
5873 
5874   if (!T2.isNull() && T2->isEnumeralType()) {
5875     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5876     if (Context.hasSameUnqualifiedType(T2, ArgType))
5877       return true;
5878   }
5879 
5880   return false;
5881 }
5882 
5883 /// AddOverloadCandidate - Adds the given function to the set of
5884 /// candidate functions, using the given function call arguments.  If
5885 /// @p SuppressUserConversions, then don't allow user-defined
5886 /// conversions via constructors or conversion operators.
5887 ///
5888 /// \param PartialOverloading true if we are performing "partial" overloading
5889 /// based on an incomplete set of function arguments. This feature is used by
5890 /// code completion.
5891 void
5892 Sema::AddOverloadCandidate(FunctionDecl *Function,
5893                            DeclAccessPair FoundDecl,
5894                            ArrayRef<Expr *> Args,
5895                            OverloadCandidateSet &CandidateSet,
5896                            bool SuppressUserConversions,
5897                            bool PartialOverloading,
5898                            bool AllowExplicit,
5899                            ConversionSequenceList EarlyConversions) {
5900   const FunctionProtoType *Proto
5901     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5902   assert(Proto && "Functions without a prototype cannot be overloaded");
5903   assert(!Function->getDescribedFunctionTemplate() &&
5904          "Use AddTemplateOverloadCandidate for function templates");
5905 
5906   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5907     if (!isa<CXXConstructorDecl>(Method)) {
5908       // If we get here, it's because we're calling a member function
5909       // that is named without a member access expression (e.g.,
5910       // "this->f") that was either written explicitly or created
5911       // implicitly. This can happen with a qualified call to a member
5912       // function, e.g., X::f(). We use an empty type for the implied
5913       // object argument (C++ [over.call.func]p3), and the acting context
5914       // is irrelevant.
5915       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5916                          Expr::Classification::makeSimpleLValue(), Args,
5917                          CandidateSet, SuppressUserConversions,
5918                          PartialOverloading, EarlyConversions);
5919       return;
5920     }
5921     // We treat a constructor like a non-member function, since its object
5922     // argument doesn't participate in overload resolution.
5923   }
5924 
5925   if (!CandidateSet.isNewCandidate(Function))
5926     return;
5927 
5928   // C++ [over.match.oper]p3:
5929   //   if no operand has a class type, only those non-member functions in the
5930   //   lookup set that have a first parameter of type T1 or "reference to
5931   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5932   //   is a right operand) a second parameter of type T2 or "reference to
5933   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5934   //   candidate functions.
5935   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5936       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5937     return;
5938 
5939   // C++11 [class.copy]p11: [DR1402]
5940   //   A defaulted move constructor that is defined as deleted is ignored by
5941   //   overload resolution.
5942   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5943   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5944       Constructor->isMoveConstructor())
5945     return;
5946 
5947   // Overload resolution is always an unevaluated context.
5948   EnterExpressionEvaluationContext Unevaluated(
5949       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5950 
5951   // Add this candidate
5952   OverloadCandidate &Candidate =
5953       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5954   Candidate.FoundDecl = FoundDecl;
5955   Candidate.Function = Function;
5956   Candidate.Viable = true;
5957   Candidate.IsSurrogate = false;
5958   Candidate.IgnoreObjectArgument = false;
5959   Candidate.ExplicitCallArguments = Args.size();
5960 
5961   if (Function->isMultiVersion() &&
5962       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5963     Candidate.Viable = false;
5964     Candidate.FailureKind = ovl_non_default_multiversion_function;
5965     return;
5966   }
5967 
5968   if (Constructor) {
5969     // C++ [class.copy]p3:
5970     //   A member function template is never instantiated to perform the copy
5971     //   of a class object to an object of its class type.
5972     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5973     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5974         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5975          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5976                        ClassType))) {
5977       Candidate.Viable = false;
5978       Candidate.FailureKind = ovl_fail_illegal_constructor;
5979       return;
5980     }
5981 
5982     // C++ [over.match.funcs]p8: (proposed DR resolution)
5983     //   A constructor inherited from class type C that has a first parameter
5984     //   of type "reference to P" (including such a constructor instantiated
5985     //   from a template) is excluded from the set of candidate functions when
5986     //   constructing an object of type cv D if the argument list has exactly
5987     //   one argument and D is reference-related to P and P is reference-related
5988     //   to C.
5989     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5990     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5991         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5992       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5993       QualType C = Context.getRecordType(Constructor->getParent());
5994       QualType D = Context.getRecordType(Shadow->getParent());
5995       SourceLocation Loc = Args.front()->getExprLoc();
5996       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5997           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5998         Candidate.Viable = false;
5999         Candidate.FailureKind = ovl_fail_inhctor_slice;
6000         return;
6001       }
6002     }
6003   }
6004 
6005   unsigned NumParams = Proto->getNumParams();
6006 
6007   // (C++ 13.3.2p2): A candidate function having fewer than m
6008   // parameters is viable only if it has an ellipsis in its parameter
6009   // list (8.3.5).
6010   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6011       !Proto->isVariadic()) {
6012     Candidate.Viable = false;
6013     Candidate.FailureKind = ovl_fail_too_many_arguments;
6014     return;
6015   }
6016 
6017   // (C++ 13.3.2p2): A candidate function having more than m parameters
6018   // is viable only if the (m+1)st parameter has a default argument
6019   // (8.3.6). For the purposes of overload resolution, the
6020   // parameter list is truncated on the right, so that there are
6021   // exactly m parameters.
6022   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6023   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6024     // Not enough arguments.
6025     Candidate.Viable = false;
6026     Candidate.FailureKind = ovl_fail_too_few_arguments;
6027     return;
6028   }
6029 
6030   // (CUDA B.1): Check for invalid calls between targets.
6031   if (getLangOpts().CUDA)
6032     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6033       // Skip the check for callers that are implicit members, because in this
6034       // case we may not yet know what the member's target is; the target is
6035       // inferred for the member automatically, based on the bases and fields of
6036       // the class.
6037       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6038         Candidate.Viable = false;
6039         Candidate.FailureKind = ovl_fail_bad_target;
6040         return;
6041       }
6042 
6043   // Determine the implicit conversion sequences for each of the
6044   // arguments.
6045   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6046     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6047       // We already formed a conversion sequence for this parameter during
6048       // template argument deduction.
6049     } else if (ArgIdx < NumParams) {
6050       // (C++ 13.3.2p3): for F to be a viable function, there shall
6051       // exist for each argument an implicit conversion sequence
6052       // (13.3.3.1) that converts that argument to the corresponding
6053       // parameter of F.
6054       QualType ParamType = Proto->getParamType(ArgIdx);
6055       Candidate.Conversions[ArgIdx]
6056         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6057                                 SuppressUserConversions,
6058                                 /*InOverloadResolution=*/true,
6059                                 /*AllowObjCWritebackConversion=*/
6060                                   getLangOpts().ObjCAutoRefCount,
6061                                 AllowExplicit);
6062       if (Candidate.Conversions[ArgIdx].isBad()) {
6063         Candidate.Viable = false;
6064         Candidate.FailureKind = ovl_fail_bad_conversion;
6065         return;
6066       }
6067     } else {
6068       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6069       // argument for which there is no corresponding parameter is
6070       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6071       Candidate.Conversions[ArgIdx].setEllipsis();
6072     }
6073   }
6074 
6075   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6076     Candidate.Viable = false;
6077     Candidate.FailureKind = ovl_fail_enable_if;
6078     Candidate.DeductionFailure.Data = FailedAttr;
6079     return;
6080   }
6081 
6082   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6083     Candidate.Viable = false;
6084     Candidate.FailureKind = ovl_fail_ext_disabled;
6085     return;
6086   }
6087 }
6088 
6089 ObjCMethodDecl *
6090 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6091                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6092   if (Methods.size() <= 1)
6093     return nullptr;
6094 
6095   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6096     bool Match = true;
6097     ObjCMethodDecl *Method = Methods[b];
6098     unsigned NumNamedArgs = Sel.getNumArgs();
6099     // Method might have more arguments than selector indicates. This is due
6100     // to addition of c-style arguments in method.
6101     if (Method->param_size() > NumNamedArgs)
6102       NumNamedArgs = Method->param_size();
6103     if (Args.size() < NumNamedArgs)
6104       continue;
6105 
6106     for (unsigned i = 0; i < NumNamedArgs; i++) {
6107       // We can't do any type-checking on a type-dependent argument.
6108       if (Args[i]->isTypeDependent()) {
6109         Match = false;
6110         break;
6111       }
6112 
6113       ParmVarDecl *param = Method->parameters()[i];
6114       Expr *argExpr = Args[i];
6115       assert(argExpr && "SelectBestMethod(): missing expression");
6116 
6117       // Strip the unbridged-cast placeholder expression off unless it's
6118       // a consumed argument.
6119       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6120           !param->hasAttr<CFConsumedAttr>())
6121         argExpr = stripARCUnbridgedCast(argExpr);
6122 
6123       // If the parameter is __unknown_anytype, move on to the next method.
6124       if (param->getType() == Context.UnknownAnyTy) {
6125         Match = false;
6126         break;
6127       }
6128 
6129       ImplicitConversionSequence ConversionState
6130         = TryCopyInitialization(*this, argExpr, param->getType(),
6131                                 /*SuppressUserConversions*/false,
6132                                 /*InOverloadResolution=*/true,
6133                                 /*AllowObjCWritebackConversion=*/
6134                                 getLangOpts().ObjCAutoRefCount,
6135                                 /*AllowExplicit*/false);
6136       // This function looks for a reasonably-exact match, so we consider
6137       // incompatible pointer conversions to be a failure here.
6138       if (ConversionState.isBad() ||
6139           (ConversionState.isStandard() &&
6140            ConversionState.Standard.Second ==
6141                ICK_Incompatible_Pointer_Conversion)) {
6142         Match = false;
6143         break;
6144       }
6145     }
6146     // Promote additional arguments to variadic methods.
6147     if (Match && Method->isVariadic()) {
6148       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6149         if (Args[i]->isTypeDependent()) {
6150           Match = false;
6151           break;
6152         }
6153         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6154                                                           nullptr);
6155         if (Arg.isInvalid()) {
6156           Match = false;
6157           break;
6158         }
6159       }
6160     } else {
6161       // Check for extra arguments to non-variadic methods.
6162       if (Args.size() != NumNamedArgs)
6163         Match = false;
6164       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6165         // Special case when selectors have no argument. In this case, select
6166         // one with the most general result type of 'id'.
6167         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6168           QualType ReturnT = Methods[b]->getReturnType();
6169           if (ReturnT->isObjCIdType())
6170             return Methods[b];
6171         }
6172       }
6173     }
6174 
6175     if (Match)
6176       return Method;
6177   }
6178   return nullptr;
6179 }
6180 
6181 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6182 // enable_if is order-sensitive. As a result, we need to reverse things
6183 // sometimes. Size of 4 elements is arbitrary.
6184 static SmallVector<EnableIfAttr *, 4>
6185 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6186   SmallVector<EnableIfAttr *, 4> Result;
6187   if (!Function->hasAttrs())
6188     return Result;
6189 
6190   const auto &FuncAttrs = Function->getAttrs();
6191   for (Attr *Attr : FuncAttrs)
6192     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6193       Result.push_back(EnableIf);
6194 
6195   std::reverse(Result.begin(), Result.end());
6196   return Result;
6197 }
6198 
6199 static bool
6200 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6201                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6202                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6203                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6204   if (ThisArg) {
6205     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6206     assert(!isa<CXXConstructorDecl>(Method) &&
6207            "Shouldn't have `this` for ctors!");
6208     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6209     ExprResult R = S.PerformObjectArgumentInitialization(
6210         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6211     if (R.isInvalid())
6212       return false;
6213     ConvertedThis = R.get();
6214   } else {
6215     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6216       (void)MD;
6217       assert((MissingImplicitThis || MD->isStatic() ||
6218               isa<CXXConstructorDecl>(MD)) &&
6219              "Expected `this` for non-ctor instance methods");
6220     }
6221     ConvertedThis = nullptr;
6222   }
6223 
6224   // Ignore any variadic arguments. Converting them is pointless, since the
6225   // user can't refer to them in the function condition.
6226   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6227 
6228   // Convert the arguments.
6229   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6230     ExprResult R;
6231     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6232                                         S.Context, Function->getParamDecl(I)),
6233                                     SourceLocation(), Args[I]);
6234 
6235     if (R.isInvalid())
6236       return false;
6237 
6238     ConvertedArgs.push_back(R.get());
6239   }
6240 
6241   if (Trap.hasErrorOccurred())
6242     return false;
6243 
6244   // Push default arguments if needed.
6245   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6246     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6247       ParmVarDecl *P = Function->getParamDecl(i);
6248       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6249                          ? P->getUninstantiatedDefaultArg()
6250                          : P->getDefaultArg();
6251       // This can only happen in code completion, i.e. when PartialOverloading
6252       // is true.
6253       if (!DefArg)
6254         return false;
6255       ExprResult R =
6256           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6257                                           S.Context, Function->getParamDecl(i)),
6258                                       SourceLocation(), DefArg);
6259       if (R.isInvalid())
6260         return false;
6261       ConvertedArgs.push_back(R.get());
6262     }
6263 
6264     if (Trap.hasErrorOccurred())
6265       return false;
6266   }
6267   return true;
6268 }
6269 
6270 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6271                                   bool MissingImplicitThis) {
6272   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6273       getOrderedEnableIfAttrs(Function);
6274   if (EnableIfAttrs.empty())
6275     return nullptr;
6276 
6277   SFINAETrap Trap(*this);
6278   SmallVector<Expr *, 16> ConvertedArgs;
6279   // FIXME: We should look into making enable_if late-parsed.
6280   Expr *DiscardedThis;
6281   if (!convertArgsForAvailabilityChecks(
6282           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6283           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6284     return EnableIfAttrs[0];
6285 
6286   for (auto *EIA : EnableIfAttrs) {
6287     APValue Result;
6288     // FIXME: This doesn't consider value-dependent cases, because doing so is
6289     // very difficult. Ideally, we should handle them more gracefully.
6290     if (!EIA->getCond()->EvaluateWithSubstitution(
6291             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6292       return EIA;
6293 
6294     if (!Result.isInt() || !Result.getInt().getBoolValue())
6295       return EIA;
6296   }
6297   return nullptr;
6298 }
6299 
6300 template <typename CheckFn>
6301 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6302                                         bool ArgDependent, SourceLocation Loc,
6303                                         CheckFn &&IsSuccessful) {
6304   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6305   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6306     if (ArgDependent == DIA->getArgDependent())
6307       Attrs.push_back(DIA);
6308   }
6309 
6310   // Common case: No diagnose_if attributes, so we can quit early.
6311   if (Attrs.empty())
6312     return false;
6313 
6314   auto WarningBegin = std::stable_partition(
6315       Attrs.begin(), Attrs.end(),
6316       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6317 
6318   // Note that diagnose_if attributes are late-parsed, so they appear in the
6319   // correct order (unlike enable_if attributes).
6320   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6321                                IsSuccessful);
6322   if (ErrAttr != WarningBegin) {
6323     const DiagnoseIfAttr *DIA = *ErrAttr;
6324     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6325     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6326         << DIA->getParent() << DIA->getCond()->getSourceRange();
6327     return true;
6328   }
6329 
6330   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6331     if (IsSuccessful(DIA)) {
6332       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6333       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6334           << DIA->getParent() << DIA->getCond()->getSourceRange();
6335     }
6336 
6337   return false;
6338 }
6339 
6340 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6341                                                const Expr *ThisArg,
6342                                                ArrayRef<const Expr *> Args,
6343                                                SourceLocation Loc) {
6344   return diagnoseDiagnoseIfAttrsWith(
6345       *this, Function, /*ArgDependent=*/true, Loc,
6346       [&](const DiagnoseIfAttr *DIA) {
6347         APValue Result;
6348         // It's sane to use the same Args for any redecl of this function, since
6349         // EvaluateWithSubstitution only cares about the position of each
6350         // argument in the arg list, not the ParmVarDecl* it maps to.
6351         if (!DIA->getCond()->EvaluateWithSubstitution(
6352                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6353           return false;
6354         return Result.isInt() && Result.getInt().getBoolValue();
6355       });
6356 }
6357 
6358 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6359                                                  SourceLocation Loc) {
6360   return diagnoseDiagnoseIfAttrsWith(
6361       *this, ND, /*ArgDependent=*/false, Loc,
6362       [&](const DiagnoseIfAttr *DIA) {
6363         bool Result;
6364         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6365                Result;
6366       });
6367 }
6368 
6369 /// \brief Add all of the function declarations in the given function set to
6370 /// the overload candidate set.
6371 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6372                                  ArrayRef<Expr *> Args,
6373                                  OverloadCandidateSet& CandidateSet,
6374                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6375                                  bool SuppressUserConversions,
6376                                  bool PartialOverloading,
6377                                  bool FirstArgumentIsBase) {
6378   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6379     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6380     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6381       ArrayRef<Expr *> FunctionArgs = Args;
6382       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6383         QualType ObjectType;
6384         Expr::Classification ObjectClassification;
6385         if (Args.size() > 0) {
6386           if (Expr *E = Args[0]) {
6387             // Use the explit base to restrict the lookup:
6388             ObjectType = E->getType();
6389             ObjectClassification = E->Classify(Context);
6390           } // .. else there is an implit base.
6391           FunctionArgs = Args.slice(1);
6392         }
6393         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6394                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6395                            ObjectClassification, FunctionArgs, CandidateSet,
6396                            SuppressUserConversions, PartialOverloading);
6397       } else {
6398         // Slice the first argument (which is the base) when we access
6399         // static method as non-static
6400         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6401                                              !isa<CXXConstructorDecl>(FD)))) {
6402           assert(cast<CXXMethodDecl>(FD)->isStatic());
6403           FunctionArgs = Args.slice(1);
6404         }
6405         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6406                              SuppressUserConversions, PartialOverloading);
6407       }
6408     } else {
6409       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6410       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6411           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6412         QualType ObjectType;
6413         Expr::Classification ObjectClassification;
6414         if (Expr *E = Args[0]) {
6415           // Use the explit base to restrict the lookup:
6416           ObjectType = E->getType();
6417           ObjectClassification = E->Classify(Context);
6418         } // .. else there is an implit base.
6419         AddMethodTemplateCandidate(
6420             FunTmpl, F.getPair(),
6421             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6422             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6423             Args.slice(1), CandidateSet, SuppressUserConversions,
6424             PartialOverloading);
6425       } else {
6426         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6427                                      ExplicitTemplateArgs, Args,
6428                                      CandidateSet, SuppressUserConversions,
6429                                      PartialOverloading);
6430       }
6431     }
6432   }
6433 }
6434 
6435 /// AddMethodCandidate - Adds a named decl (which is some kind of
6436 /// method) as a method candidate to the given overload set.
6437 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6438                               QualType ObjectType,
6439                               Expr::Classification ObjectClassification,
6440                               ArrayRef<Expr *> Args,
6441                               OverloadCandidateSet& CandidateSet,
6442                               bool SuppressUserConversions) {
6443   NamedDecl *Decl = FoundDecl.getDecl();
6444   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6445 
6446   if (isa<UsingShadowDecl>(Decl))
6447     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6448 
6449   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6450     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6451            "Expected a member function template");
6452     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6453                                /*ExplicitArgs*/ nullptr, ObjectType,
6454                                ObjectClassification, Args, CandidateSet,
6455                                SuppressUserConversions);
6456   } else {
6457     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6458                        ObjectType, ObjectClassification, Args, CandidateSet,
6459                        SuppressUserConversions);
6460   }
6461 }
6462 
6463 /// AddMethodCandidate - Adds the given C++ member function to the set
6464 /// of candidate functions, using the given function call arguments
6465 /// and the object argument (@c Object). For example, in a call
6466 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6467 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6468 /// allow user-defined conversions via constructors or conversion
6469 /// operators.
6470 void
6471 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6472                          CXXRecordDecl *ActingContext, QualType ObjectType,
6473                          Expr::Classification ObjectClassification,
6474                          ArrayRef<Expr *> Args,
6475                          OverloadCandidateSet &CandidateSet,
6476                          bool SuppressUserConversions,
6477                          bool PartialOverloading,
6478                          ConversionSequenceList EarlyConversions) {
6479   const FunctionProtoType *Proto
6480     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6481   assert(Proto && "Methods without a prototype cannot be overloaded");
6482   assert(!isa<CXXConstructorDecl>(Method) &&
6483          "Use AddOverloadCandidate for constructors");
6484 
6485   if (!CandidateSet.isNewCandidate(Method))
6486     return;
6487 
6488   // C++11 [class.copy]p23: [DR1402]
6489   //   A defaulted move assignment operator that is defined as deleted is
6490   //   ignored by overload resolution.
6491   if (Method->isDefaulted() && Method->isDeleted() &&
6492       Method->isMoveAssignmentOperator())
6493     return;
6494 
6495   // Overload resolution is always an unevaluated context.
6496   EnterExpressionEvaluationContext Unevaluated(
6497       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6498 
6499   // Add this candidate
6500   OverloadCandidate &Candidate =
6501       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6502   Candidate.FoundDecl = FoundDecl;
6503   Candidate.Function = Method;
6504   Candidate.IsSurrogate = false;
6505   Candidate.IgnoreObjectArgument = false;
6506   Candidate.ExplicitCallArguments = Args.size();
6507 
6508   unsigned NumParams = Proto->getNumParams();
6509 
6510   // (C++ 13.3.2p2): A candidate function having fewer than m
6511   // parameters is viable only if it has an ellipsis in its parameter
6512   // list (8.3.5).
6513   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6514       !Proto->isVariadic()) {
6515     Candidate.Viable = false;
6516     Candidate.FailureKind = ovl_fail_too_many_arguments;
6517     return;
6518   }
6519 
6520   // (C++ 13.3.2p2): A candidate function having more than m parameters
6521   // is viable only if the (m+1)st parameter has a default argument
6522   // (8.3.6). For the purposes of overload resolution, the
6523   // parameter list is truncated on the right, so that there are
6524   // exactly m parameters.
6525   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6526   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6527     // Not enough arguments.
6528     Candidate.Viable = false;
6529     Candidate.FailureKind = ovl_fail_too_few_arguments;
6530     return;
6531   }
6532 
6533   Candidate.Viable = true;
6534 
6535   if (Method->isStatic() || ObjectType.isNull())
6536     // The implicit object argument is ignored.
6537     Candidate.IgnoreObjectArgument = true;
6538   else {
6539     // Determine the implicit conversion sequence for the object
6540     // parameter.
6541     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6542         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6543         Method, ActingContext);
6544     if (Candidate.Conversions[0].isBad()) {
6545       Candidate.Viable = false;
6546       Candidate.FailureKind = ovl_fail_bad_conversion;
6547       return;
6548     }
6549   }
6550 
6551   // (CUDA B.1): Check for invalid calls between targets.
6552   if (getLangOpts().CUDA)
6553     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6554       if (!IsAllowedCUDACall(Caller, Method)) {
6555         Candidate.Viable = false;
6556         Candidate.FailureKind = ovl_fail_bad_target;
6557         return;
6558       }
6559 
6560   // Determine the implicit conversion sequences for each of the
6561   // arguments.
6562   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6563     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6564       // We already formed a conversion sequence for this parameter during
6565       // template argument deduction.
6566     } else if (ArgIdx < NumParams) {
6567       // (C++ 13.3.2p3): for F to be a viable function, there shall
6568       // exist for each argument an implicit conversion sequence
6569       // (13.3.3.1) that converts that argument to the corresponding
6570       // parameter of F.
6571       QualType ParamType = Proto->getParamType(ArgIdx);
6572       Candidate.Conversions[ArgIdx + 1]
6573         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6574                                 SuppressUserConversions,
6575                                 /*InOverloadResolution=*/true,
6576                                 /*AllowObjCWritebackConversion=*/
6577                                   getLangOpts().ObjCAutoRefCount);
6578       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6579         Candidate.Viable = false;
6580         Candidate.FailureKind = ovl_fail_bad_conversion;
6581         return;
6582       }
6583     } else {
6584       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6585       // argument for which there is no corresponding parameter is
6586       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6587       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6588     }
6589   }
6590 
6591   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6592     Candidate.Viable = false;
6593     Candidate.FailureKind = ovl_fail_enable_if;
6594     Candidate.DeductionFailure.Data = FailedAttr;
6595     return;
6596   }
6597 
6598   if (Method->isMultiVersion() &&
6599       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6600     Candidate.Viable = false;
6601     Candidate.FailureKind = ovl_non_default_multiversion_function;
6602   }
6603 }
6604 
6605 /// \brief Add a C++ member function template as a candidate to the candidate
6606 /// set, using template argument deduction to produce an appropriate member
6607 /// function template specialization.
6608 void
6609 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6610                                  DeclAccessPair FoundDecl,
6611                                  CXXRecordDecl *ActingContext,
6612                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6613                                  QualType ObjectType,
6614                                  Expr::Classification ObjectClassification,
6615                                  ArrayRef<Expr *> Args,
6616                                  OverloadCandidateSet& CandidateSet,
6617                                  bool SuppressUserConversions,
6618                                  bool PartialOverloading) {
6619   if (!CandidateSet.isNewCandidate(MethodTmpl))
6620     return;
6621 
6622   // C++ [over.match.funcs]p7:
6623   //   In each case where a candidate is a function template, candidate
6624   //   function template specializations are generated using template argument
6625   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6626   //   candidate functions in the usual way.113) A given name can refer to one
6627   //   or more function templates and also to a set of overloaded non-template
6628   //   functions. In such a case, the candidate functions generated from each
6629   //   function template are combined with the set of non-template candidate
6630   //   functions.
6631   TemplateDeductionInfo Info(CandidateSet.getLocation());
6632   FunctionDecl *Specialization = nullptr;
6633   ConversionSequenceList Conversions;
6634   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6635           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6636           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6637             return CheckNonDependentConversions(
6638                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6639                 SuppressUserConversions, ActingContext, ObjectType,
6640                 ObjectClassification);
6641           })) {
6642     OverloadCandidate &Candidate =
6643         CandidateSet.addCandidate(Conversions.size(), Conversions);
6644     Candidate.FoundDecl = FoundDecl;
6645     Candidate.Function = MethodTmpl->getTemplatedDecl();
6646     Candidate.Viable = false;
6647     Candidate.IsSurrogate = false;
6648     Candidate.IgnoreObjectArgument =
6649         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6650         ObjectType.isNull();
6651     Candidate.ExplicitCallArguments = Args.size();
6652     if (Result == TDK_NonDependentConversionFailure)
6653       Candidate.FailureKind = ovl_fail_bad_conversion;
6654     else {
6655       Candidate.FailureKind = ovl_fail_bad_deduction;
6656       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6657                                                             Info);
6658     }
6659     return;
6660   }
6661 
6662   // Add the function template specialization produced by template argument
6663   // deduction as a candidate.
6664   assert(Specialization && "Missing member function template specialization?");
6665   assert(isa<CXXMethodDecl>(Specialization) &&
6666          "Specialization is not a member function?");
6667   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6668                      ActingContext, ObjectType, ObjectClassification, Args,
6669                      CandidateSet, SuppressUserConversions, PartialOverloading,
6670                      Conversions);
6671 }
6672 
6673 /// \brief Add a C++ function template specialization as a candidate
6674 /// in the candidate set, using template argument deduction to produce
6675 /// an appropriate function template specialization.
6676 void
6677 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6678                                    DeclAccessPair FoundDecl,
6679                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6680                                    ArrayRef<Expr *> Args,
6681                                    OverloadCandidateSet& CandidateSet,
6682                                    bool SuppressUserConversions,
6683                                    bool PartialOverloading) {
6684   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6685     return;
6686 
6687   // C++ [over.match.funcs]p7:
6688   //   In each case where a candidate is a function template, candidate
6689   //   function template specializations are generated using template argument
6690   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6691   //   candidate functions in the usual way.113) A given name can refer to one
6692   //   or more function templates and also to a set of overloaded non-template
6693   //   functions. In such a case, the candidate functions generated from each
6694   //   function template are combined with the set of non-template candidate
6695   //   functions.
6696   TemplateDeductionInfo Info(CandidateSet.getLocation());
6697   FunctionDecl *Specialization = nullptr;
6698   ConversionSequenceList Conversions;
6699   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6700           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6701           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6702             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6703                                                 Args, CandidateSet, Conversions,
6704                                                 SuppressUserConversions);
6705           })) {
6706     OverloadCandidate &Candidate =
6707         CandidateSet.addCandidate(Conversions.size(), Conversions);
6708     Candidate.FoundDecl = FoundDecl;
6709     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6710     Candidate.Viable = false;
6711     Candidate.IsSurrogate = false;
6712     // Ignore the object argument if there is one, since we don't have an object
6713     // type.
6714     Candidate.IgnoreObjectArgument =
6715         isa<CXXMethodDecl>(Candidate.Function) &&
6716         !isa<CXXConstructorDecl>(Candidate.Function);
6717     Candidate.ExplicitCallArguments = Args.size();
6718     if (Result == TDK_NonDependentConversionFailure)
6719       Candidate.FailureKind = ovl_fail_bad_conversion;
6720     else {
6721       Candidate.FailureKind = ovl_fail_bad_deduction;
6722       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6723                                                             Info);
6724     }
6725     return;
6726   }
6727 
6728   // Add the function template specialization produced by template argument
6729   // deduction as a candidate.
6730   assert(Specialization && "Missing function template specialization?");
6731   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6732                        SuppressUserConversions, PartialOverloading,
6733                        /*AllowExplicit*/false, Conversions);
6734 }
6735 
6736 /// Check that implicit conversion sequences can be formed for each argument
6737 /// whose corresponding parameter has a non-dependent type, per DR1391's
6738 /// [temp.deduct.call]p10.
6739 bool Sema::CheckNonDependentConversions(
6740     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6741     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6742     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6743     CXXRecordDecl *ActingContext, QualType ObjectType,
6744     Expr::Classification ObjectClassification) {
6745   // FIXME: The cases in which we allow explicit conversions for constructor
6746   // arguments never consider calling a constructor template. It's not clear
6747   // that is correct.
6748   const bool AllowExplicit = false;
6749 
6750   auto *FD = FunctionTemplate->getTemplatedDecl();
6751   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6752   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6753   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6754 
6755   Conversions =
6756       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6757 
6758   // Overload resolution is always an unevaluated context.
6759   EnterExpressionEvaluationContext Unevaluated(
6760       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6761 
6762   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6763   // require that, but this check should never result in a hard error, and
6764   // overload resolution is permitted to sidestep instantiations.
6765   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6766       !ObjectType.isNull()) {
6767     Conversions[0] = TryObjectArgumentInitialization(
6768         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6769         Method, ActingContext);
6770     if (Conversions[0].isBad())
6771       return true;
6772   }
6773 
6774   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6775        ++I) {
6776     QualType ParamType = ParamTypes[I];
6777     if (!ParamType->isDependentType()) {
6778       Conversions[ThisConversions + I]
6779         = TryCopyInitialization(*this, Args[I], ParamType,
6780                                 SuppressUserConversions,
6781                                 /*InOverloadResolution=*/true,
6782                                 /*AllowObjCWritebackConversion=*/
6783                                   getLangOpts().ObjCAutoRefCount,
6784                                 AllowExplicit);
6785       if (Conversions[ThisConversions + I].isBad())
6786         return true;
6787     }
6788   }
6789 
6790   return false;
6791 }
6792 
6793 /// Determine whether this is an allowable conversion from the result
6794 /// of an explicit conversion operator to the expected type, per C++
6795 /// [over.match.conv]p1 and [over.match.ref]p1.
6796 ///
6797 /// \param ConvType The return type of the conversion function.
6798 ///
6799 /// \param ToType The type we are converting to.
6800 ///
6801 /// \param AllowObjCPointerConversion Allow a conversion from one
6802 /// Objective-C pointer to another.
6803 ///
6804 /// \returns true if the conversion is allowable, false otherwise.
6805 static bool isAllowableExplicitConversion(Sema &S,
6806                                           QualType ConvType, QualType ToType,
6807                                           bool AllowObjCPointerConversion) {
6808   QualType ToNonRefType = ToType.getNonReferenceType();
6809 
6810   // Easy case: the types are the same.
6811   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6812     return true;
6813 
6814   // Allow qualification conversions.
6815   bool ObjCLifetimeConversion;
6816   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6817                                   ObjCLifetimeConversion))
6818     return true;
6819 
6820   // If we're not allowed to consider Objective-C pointer conversions,
6821   // we're done.
6822   if (!AllowObjCPointerConversion)
6823     return false;
6824 
6825   // Is this an Objective-C pointer conversion?
6826   bool IncompatibleObjC = false;
6827   QualType ConvertedType;
6828   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6829                                    IncompatibleObjC);
6830 }
6831 
6832 /// AddConversionCandidate - Add a C++ conversion function as a
6833 /// candidate in the candidate set (C++ [over.match.conv],
6834 /// C++ [over.match.copy]). From is the expression we're converting from,
6835 /// and ToType is the type that we're eventually trying to convert to
6836 /// (which may or may not be the same type as the type that the
6837 /// conversion function produces).
6838 void
6839 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6840                              DeclAccessPair FoundDecl,
6841                              CXXRecordDecl *ActingContext,
6842                              Expr *From, QualType ToType,
6843                              OverloadCandidateSet& CandidateSet,
6844                              bool AllowObjCConversionOnExplicit,
6845                              bool AllowResultConversion) {
6846   assert(!Conversion->getDescribedFunctionTemplate() &&
6847          "Conversion function templates use AddTemplateConversionCandidate");
6848   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6849   if (!CandidateSet.isNewCandidate(Conversion))
6850     return;
6851 
6852   // If the conversion function has an undeduced return type, trigger its
6853   // deduction now.
6854   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6855     if (DeduceReturnType(Conversion, From->getExprLoc()))
6856       return;
6857     ConvType = Conversion->getConversionType().getNonReferenceType();
6858   }
6859 
6860   // If we don't allow any conversion of the result type, ignore conversion
6861   // functions that don't convert to exactly (possibly cv-qualified) T.
6862   if (!AllowResultConversion &&
6863       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6864     return;
6865 
6866   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6867   // operator is only a candidate if its return type is the target type or
6868   // can be converted to the target type with a qualification conversion.
6869   if (Conversion->isExplicit() &&
6870       !isAllowableExplicitConversion(*this, ConvType, ToType,
6871                                      AllowObjCConversionOnExplicit))
6872     return;
6873 
6874   // Overload resolution is always an unevaluated context.
6875   EnterExpressionEvaluationContext Unevaluated(
6876       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6877 
6878   // Add this candidate
6879   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6880   Candidate.FoundDecl = FoundDecl;
6881   Candidate.Function = Conversion;
6882   Candidate.IsSurrogate = false;
6883   Candidate.IgnoreObjectArgument = false;
6884   Candidate.FinalConversion.setAsIdentityConversion();
6885   Candidate.FinalConversion.setFromType(ConvType);
6886   Candidate.FinalConversion.setAllToTypes(ToType);
6887   Candidate.Viable = true;
6888   Candidate.ExplicitCallArguments = 1;
6889 
6890   // C++ [over.match.funcs]p4:
6891   //   For conversion functions, the function is considered to be a member of
6892   //   the class of the implicit implied object argument for the purpose of
6893   //   defining the type of the implicit object parameter.
6894   //
6895   // Determine the implicit conversion sequence for the implicit
6896   // object parameter.
6897   QualType ImplicitParamType = From->getType();
6898   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6899     ImplicitParamType = FromPtrType->getPointeeType();
6900   CXXRecordDecl *ConversionContext
6901     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6902 
6903   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6904       *this, CandidateSet.getLocation(), From->getType(),
6905       From->Classify(Context), Conversion, ConversionContext);
6906 
6907   if (Candidate.Conversions[0].isBad()) {
6908     Candidate.Viable = false;
6909     Candidate.FailureKind = ovl_fail_bad_conversion;
6910     return;
6911   }
6912 
6913   // We won't go through a user-defined type conversion function to convert a
6914   // derived to base as such conversions are given Conversion Rank. They only
6915   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6916   QualType FromCanon
6917     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6918   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6919   if (FromCanon == ToCanon ||
6920       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6921     Candidate.Viable = false;
6922     Candidate.FailureKind = ovl_fail_trivial_conversion;
6923     return;
6924   }
6925 
6926   // To determine what the conversion from the result of calling the
6927   // conversion function to the type we're eventually trying to
6928   // convert to (ToType), we need to synthesize a call to the
6929   // conversion function and attempt copy initialization from it. This
6930   // makes sure that we get the right semantics with respect to
6931   // lvalues/rvalues and the type. Fortunately, we can allocate this
6932   // call on the stack and we don't need its arguments to be
6933   // well-formed.
6934   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6935                             VK_LValue, From->getLocStart());
6936   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6937                                 Context.getPointerType(Conversion->getType()),
6938                                 CK_FunctionToPointerDecay,
6939                                 &ConversionRef, VK_RValue);
6940 
6941   QualType ConversionType = Conversion->getConversionType();
6942   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6943     Candidate.Viable = false;
6944     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6945     return;
6946   }
6947 
6948   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6949 
6950   // Note that it is safe to allocate CallExpr on the stack here because
6951   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6952   // allocator).
6953   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6954   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6955                 From->getLocStart());
6956   ImplicitConversionSequence ICS =
6957     TryCopyInitialization(*this, &Call, ToType,
6958                           /*SuppressUserConversions=*/true,
6959                           /*InOverloadResolution=*/false,
6960                           /*AllowObjCWritebackConversion=*/false);
6961 
6962   switch (ICS.getKind()) {
6963   case ImplicitConversionSequence::StandardConversion:
6964     Candidate.FinalConversion = ICS.Standard;
6965 
6966     // C++ [over.ics.user]p3:
6967     //   If the user-defined conversion is specified by a specialization of a
6968     //   conversion function template, the second standard conversion sequence
6969     //   shall have exact match rank.
6970     if (Conversion->getPrimaryTemplate() &&
6971         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6972       Candidate.Viable = false;
6973       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6974       return;
6975     }
6976 
6977     // C++0x [dcl.init.ref]p5:
6978     //    In the second case, if the reference is an rvalue reference and
6979     //    the second standard conversion sequence of the user-defined
6980     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6981     //    program is ill-formed.
6982     if (ToType->isRValueReferenceType() &&
6983         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6984       Candidate.Viable = false;
6985       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6986       return;
6987     }
6988     break;
6989 
6990   case ImplicitConversionSequence::BadConversion:
6991     Candidate.Viable = false;
6992     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6993     return;
6994 
6995   default:
6996     llvm_unreachable(
6997            "Can only end up with a standard conversion sequence or failure");
6998   }
6999 
7000   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7001     Candidate.Viable = false;
7002     Candidate.FailureKind = ovl_fail_enable_if;
7003     Candidate.DeductionFailure.Data = FailedAttr;
7004     return;
7005   }
7006 
7007   if (Conversion->isMultiVersion() &&
7008       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7009     Candidate.Viable = false;
7010     Candidate.FailureKind = ovl_non_default_multiversion_function;
7011   }
7012 }
7013 
7014 /// \brief Adds a conversion function template specialization
7015 /// candidate to the overload set, using template argument deduction
7016 /// to deduce the template arguments of the conversion function
7017 /// template from the type that we are converting to (C++
7018 /// [temp.deduct.conv]).
7019 void
7020 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7021                                      DeclAccessPair FoundDecl,
7022                                      CXXRecordDecl *ActingDC,
7023                                      Expr *From, QualType ToType,
7024                                      OverloadCandidateSet &CandidateSet,
7025                                      bool AllowObjCConversionOnExplicit,
7026                                      bool AllowResultConversion) {
7027   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7028          "Only conversion function templates permitted here");
7029 
7030   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7031     return;
7032 
7033   TemplateDeductionInfo Info(CandidateSet.getLocation());
7034   CXXConversionDecl *Specialization = nullptr;
7035   if (TemplateDeductionResult Result
7036         = DeduceTemplateArguments(FunctionTemplate, ToType,
7037                                   Specialization, Info)) {
7038     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7039     Candidate.FoundDecl = FoundDecl;
7040     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7041     Candidate.Viable = false;
7042     Candidate.FailureKind = ovl_fail_bad_deduction;
7043     Candidate.IsSurrogate = false;
7044     Candidate.IgnoreObjectArgument = false;
7045     Candidate.ExplicitCallArguments = 1;
7046     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7047                                                           Info);
7048     return;
7049   }
7050 
7051   // Add the conversion function template specialization produced by
7052   // template argument deduction as a candidate.
7053   assert(Specialization && "Missing function template specialization?");
7054   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7055                          CandidateSet, AllowObjCConversionOnExplicit,
7056                          AllowResultConversion);
7057 }
7058 
7059 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7060 /// converts the given @c Object to a function pointer via the
7061 /// conversion function @c Conversion, and then attempts to call it
7062 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7063 /// the type of function that we'll eventually be calling.
7064 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7065                                  DeclAccessPair FoundDecl,
7066                                  CXXRecordDecl *ActingContext,
7067                                  const FunctionProtoType *Proto,
7068                                  Expr *Object,
7069                                  ArrayRef<Expr *> Args,
7070                                  OverloadCandidateSet& CandidateSet) {
7071   if (!CandidateSet.isNewCandidate(Conversion))
7072     return;
7073 
7074   // Overload resolution is always an unevaluated context.
7075   EnterExpressionEvaluationContext Unevaluated(
7076       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7077 
7078   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7079   Candidate.FoundDecl = FoundDecl;
7080   Candidate.Function = nullptr;
7081   Candidate.Surrogate = Conversion;
7082   Candidate.Viable = true;
7083   Candidate.IsSurrogate = true;
7084   Candidate.IgnoreObjectArgument = false;
7085   Candidate.ExplicitCallArguments = Args.size();
7086 
7087   // Determine the implicit conversion sequence for the implicit
7088   // object parameter.
7089   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7090       *this, CandidateSet.getLocation(), Object->getType(),
7091       Object->Classify(Context), Conversion, ActingContext);
7092   if (ObjectInit.isBad()) {
7093     Candidate.Viable = false;
7094     Candidate.FailureKind = ovl_fail_bad_conversion;
7095     Candidate.Conversions[0] = ObjectInit;
7096     return;
7097   }
7098 
7099   // The first conversion is actually a user-defined conversion whose
7100   // first conversion is ObjectInit's standard conversion (which is
7101   // effectively a reference binding). Record it as such.
7102   Candidate.Conversions[0].setUserDefined();
7103   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7104   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7105   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7106   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7107   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7108   Candidate.Conversions[0].UserDefined.After
7109     = Candidate.Conversions[0].UserDefined.Before;
7110   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7111 
7112   // Find the
7113   unsigned NumParams = Proto->getNumParams();
7114 
7115   // (C++ 13.3.2p2): A candidate function having fewer than m
7116   // parameters is viable only if it has an ellipsis in its parameter
7117   // list (8.3.5).
7118   if (Args.size() > NumParams && !Proto->isVariadic()) {
7119     Candidate.Viable = false;
7120     Candidate.FailureKind = ovl_fail_too_many_arguments;
7121     return;
7122   }
7123 
7124   // Function types don't have any default arguments, so just check if
7125   // we have enough arguments.
7126   if (Args.size() < NumParams) {
7127     // Not enough arguments.
7128     Candidate.Viable = false;
7129     Candidate.FailureKind = ovl_fail_too_few_arguments;
7130     return;
7131   }
7132 
7133   // Determine the implicit conversion sequences for each of the
7134   // arguments.
7135   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7136     if (ArgIdx < NumParams) {
7137       // (C++ 13.3.2p3): for F to be a viable function, there shall
7138       // exist for each argument an implicit conversion sequence
7139       // (13.3.3.1) that converts that argument to the corresponding
7140       // parameter of F.
7141       QualType ParamType = Proto->getParamType(ArgIdx);
7142       Candidate.Conversions[ArgIdx + 1]
7143         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7144                                 /*SuppressUserConversions=*/false,
7145                                 /*InOverloadResolution=*/false,
7146                                 /*AllowObjCWritebackConversion=*/
7147                                   getLangOpts().ObjCAutoRefCount);
7148       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7149         Candidate.Viable = false;
7150         Candidate.FailureKind = ovl_fail_bad_conversion;
7151         return;
7152       }
7153     } else {
7154       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7155       // argument for which there is no corresponding parameter is
7156       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7157       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7158     }
7159   }
7160 
7161   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7162     Candidate.Viable = false;
7163     Candidate.FailureKind = ovl_fail_enable_if;
7164     Candidate.DeductionFailure.Data = FailedAttr;
7165     return;
7166   }
7167 }
7168 
7169 /// \brief Add overload candidates for overloaded operators that are
7170 /// member functions.
7171 ///
7172 /// Add the overloaded operator candidates that are member functions
7173 /// for the operator Op that was used in an operator expression such
7174 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7175 /// CandidateSet will store the added overload candidates. (C++
7176 /// [over.match.oper]).
7177 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7178                                        SourceLocation OpLoc,
7179                                        ArrayRef<Expr *> Args,
7180                                        OverloadCandidateSet& CandidateSet,
7181                                        SourceRange OpRange) {
7182   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7183 
7184   // C++ [over.match.oper]p3:
7185   //   For a unary operator @ with an operand of a type whose
7186   //   cv-unqualified version is T1, and for a binary operator @ with
7187   //   a left operand of a type whose cv-unqualified version is T1 and
7188   //   a right operand of a type whose cv-unqualified version is T2,
7189   //   three sets of candidate functions, designated member
7190   //   candidates, non-member candidates and built-in candidates, are
7191   //   constructed as follows:
7192   QualType T1 = Args[0]->getType();
7193 
7194   //     -- If T1 is a complete class type or a class currently being
7195   //        defined, the set of member candidates is the result of the
7196   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7197   //        the set of member candidates is empty.
7198   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7199     // Complete the type if it can be completed.
7200     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7201       return;
7202     // If the type is neither complete nor being defined, bail out now.
7203     if (!T1Rec->getDecl()->getDefinition())
7204       return;
7205 
7206     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7207     LookupQualifiedName(Operators, T1Rec->getDecl());
7208     Operators.suppressDiagnostics();
7209 
7210     for (LookupResult::iterator Oper = Operators.begin(),
7211                              OperEnd = Operators.end();
7212          Oper != OperEnd;
7213          ++Oper)
7214       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7215                          Args[0]->Classify(Context), Args.slice(1),
7216                          CandidateSet, /*SuppressUserConversions=*/false);
7217   }
7218 }
7219 
7220 /// AddBuiltinCandidate - Add a candidate for a built-in
7221 /// operator. ResultTy and ParamTys are the result and parameter types
7222 /// of the built-in candidate, respectively. Args and NumArgs are the
7223 /// arguments being passed to the candidate. IsAssignmentOperator
7224 /// should be true when this built-in candidate is an assignment
7225 /// operator. NumContextualBoolArguments is the number of arguments
7226 /// (at the beginning of the argument list) that will be contextually
7227 /// converted to bool.
7228 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7229                                OverloadCandidateSet& CandidateSet,
7230                                bool IsAssignmentOperator,
7231                                unsigned NumContextualBoolArguments) {
7232   // Overload resolution is always an unevaluated context.
7233   EnterExpressionEvaluationContext Unevaluated(
7234       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7235 
7236   // Add this candidate
7237   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7238   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7239   Candidate.Function = nullptr;
7240   Candidate.IsSurrogate = false;
7241   Candidate.IgnoreObjectArgument = false;
7242   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7243 
7244   // Determine the implicit conversion sequences for each of the
7245   // arguments.
7246   Candidate.Viable = true;
7247   Candidate.ExplicitCallArguments = Args.size();
7248   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7249     // C++ [over.match.oper]p4:
7250     //   For the built-in assignment operators, conversions of the
7251     //   left operand are restricted as follows:
7252     //     -- no temporaries are introduced to hold the left operand, and
7253     //     -- no user-defined conversions are applied to the left
7254     //        operand to achieve a type match with the left-most
7255     //        parameter of a built-in candidate.
7256     //
7257     // We block these conversions by turning off user-defined
7258     // conversions, since that is the only way that initialization of
7259     // a reference to a non-class type can occur from something that
7260     // is not of the same type.
7261     if (ArgIdx < NumContextualBoolArguments) {
7262       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7263              "Contextual conversion to bool requires bool type");
7264       Candidate.Conversions[ArgIdx]
7265         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7266     } else {
7267       Candidate.Conversions[ArgIdx]
7268         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7269                                 ArgIdx == 0 && IsAssignmentOperator,
7270                                 /*InOverloadResolution=*/false,
7271                                 /*AllowObjCWritebackConversion=*/
7272                                   getLangOpts().ObjCAutoRefCount);
7273     }
7274     if (Candidate.Conversions[ArgIdx].isBad()) {
7275       Candidate.Viable = false;
7276       Candidate.FailureKind = ovl_fail_bad_conversion;
7277       break;
7278     }
7279   }
7280 }
7281 
7282 namespace {
7283 
7284 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7285 /// candidate operator functions for built-in operators (C++
7286 /// [over.built]). The types are separated into pointer types and
7287 /// enumeration types.
7288 class BuiltinCandidateTypeSet  {
7289   /// TypeSet - A set of types.
7290   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7291                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7292 
7293   /// PointerTypes - The set of pointer types that will be used in the
7294   /// built-in candidates.
7295   TypeSet PointerTypes;
7296 
7297   /// MemberPointerTypes - The set of member pointer types that will be
7298   /// used in the built-in candidates.
7299   TypeSet MemberPointerTypes;
7300 
7301   /// EnumerationTypes - The set of enumeration types that will be
7302   /// used in the built-in candidates.
7303   TypeSet EnumerationTypes;
7304 
7305   /// \brief The set of vector types that will be used in the built-in
7306   /// candidates.
7307   TypeSet VectorTypes;
7308 
7309   /// \brief A flag indicating non-record types are viable candidates
7310   bool HasNonRecordTypes;
7311 
7312   /// \brief A flag indicating whether either arithmetic or enumeration types
7313   /// were present in the candidate set.
7314   bool HasArithmeticOrEnumeralTypes;
7315 
7316   /// \brief A flag indicating whether the nullptr type was present in the
7317   /// candidate set.
7318   bool HasNullPtrType;
7319 
7320   /// Sema - The semantic analysis instance where we are building the
7321   /// candidate type set.
7322   Sema &SemaRef;
7323 
7324   /// Context - The AST context in which we will build the type sets.
7325   ASTContext &Context;
7326 
7327   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7328                                                const Qualifiers &VisibleQuals);
7329   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7330 
7331 public:
7332   /// iterator - Iterates through the types that are part of the set.
7333   typedef TypeSet::iterator iterator;
7334 
7335   BuiltinCandidateTypeSet(Sema &SemaRef)
7336     : HasNonRecordTypes(false),
7337       HasArithmeticOrEnumeralTypes(false),
7338       HasNullPtrType(false),
7339       SemaRef(SemaRef),
7340       Context(SemaRef.Context) { }
7341 
7342   void AddTypesConvertedFrom(QualType Ty,
7343                              SourceLocation Loc,
7344                              bool AllowUserConversions,
7345                              bool AllowExplicitConversions,
7346                              const Qualifiers &VisibleTypeConversionsQuals);
7347 
7348   /// pointer_begin - First pointer type found;
7349   iterator pointer_begin() { return PointerTypes.begin(); }
7350 
7351   /// pointer_end - Past the last pointer type found;
7352   iterator pointer_end() { return PointerTypes.end(); }
7353 
7354   /// member_pointer_begin - First member pointer type found;
7355   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7356 
7357   /// member_pointer_end - Past the last member pointer type found;
7358   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7359 
7360   /// enumeration_begin - First enumeration type found;
7361   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7362 
7363   /// enumeration_end - Past the last enumeration type found;
7364   iterator enumeration_end() { return EnumerationTypes.end(); }
7365 
7366   iterator vector_begin() { return VectorTypes.begin(); }
7367   iterator vector_end() { return VectorTypes.end(); }
7368 
7369   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7370   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7371   bool hasNullPtrType() const { return HasNullPtrType; }
7372 };
7373 
7374 } // end anonymous namespace
7375 
7376 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7377 /// the set of pointer types along with any more-qualified variants of
7378 /// that type. For example, if @p Ty is "int const *", this routine
7379 /// will add "int const *", "int const volatile *", "int const
7380 /// restrict *", and "int const volatile restrict *" to the set of
7381 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7382 /// false otherwise.
7383 ///
7384 /// FIXME: what to do about extended qualifiers?
7385 bool
7386 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7387                                              const Qualifiers &VisibleQuals) {
7388 
7389   // Insert this type.
7390   if (!PointerTypes.insert(Ty))
7391     return false;
7392 
7393   QualType PointeeTy;
7394   const PointerType *PointerTy = Ty->getAs<PointerType>();
7395   bool buildObjCPtr = false;
7396   if (!PointerTy) {
7397     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7398     PointeeTy = PTy->getPointeeType();
7399     buildObjCPtr = true;
7400   } else {
7401     PointeeTy = PointerTy->getPointeeType();
7402   }
7403 
7404   // Don't add qualified variants of arrays. For one, they're not allowed
7405   // (the qualifier would sink to the element type), and for another, the
7406   // only overload situation where it matters is subscript or pointer +- int,
7407   // and those shouldn't have qualifier variants anyway.
7408   if (PointeeTy->isArrayType())
7409     return true;
7410 
7411   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7412   bool hasVolatile = VisibleQuals.hasVolatile();
7413   bool hasRestrict = VisibleQuals.hasRestrict();
7414 
7415   // Iterate through all strict supersets of BaseCVR.
7416   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7417     if ((CVR | BaseCVR) != CVR) continue;
7418     // Skip over volatile if no volatile found anywhere in the types.
7419     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7420 
7421     // Skip over restrict if no restrict found anywhere in the types, or if
7422     // the type cannot be restrict-qualified.
7423     if ((CVR & Qualifiers::Restrict) &&
7424         (!hasRestrict ||
7425          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7426       continue;
7427 
7428     // Build qualified pointee type.
7429     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7430 
7431     // Build qualified pointer type.
7432     QualType QPointerTy;
7433     if (!buildObjCPtr)
7434       QPointerTy = Context.getPointerType(QPointeeTy);
7435     else
7436       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7437 
7438     // Insert qualified pointer type.
7439     PointerTypes.insert(QPointerTy);
7440   }
7441 
7442   return true;
7443 }
7444 
7445 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7446 /// to the set of pointer types along with any more-qualified variants of
7447 /// that type. For example, if @p Ty is "int const *", this routine
7448 /// will add "int const *", "int const volatile *", "int const
7449 /// restrict *", and "int const volatile restrict *" to the set of
7450 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7451 /// false otherwise.
7452 ///
7453 /// FIXME: what to do about extended qualifiers?
7454 bool
7455 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7456     QualType Ty) {
7457   // Insert this type.
7458   if (!MemberPointerTypes.insert(Ty))
7459     return false;
7460 
7461   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7462   assert(PointerTy && "type was not a member pointer type!");
7463 
7464   QualType PointeeTy = PointerTy->getPointeeType();
7465   // Don't add qualified variants of arrays. For one, they're not allowed
7466   // (the qualifier would sink to the element type), and for another, the
7467   // only overload situation where it matters is subscript or pointer +- int,
7468   // and those shouldn't have qualifier variants anyway.
7469   if (PointeeTy->isArrayType())
7470     return true;
7471   const Type *ClassTy = PointerTy->getClass();
7472 
7473   // Iterate through all strict supersets of the pointee type's CVR
7474   // qualifiers.
7475   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7476   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7477     if ((CVR | BaseCVR) != CVR) continue;
7478 
7479     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7480     MemberPointerTypes.insert(
7481       Context.getMemberPointerType(QPointeeTy, ClassTy));
7482   }
7483 
7484   return true;
7485 }
7486 
7487 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7488 /// Ty can be implicit converted to the given set of @p Types. We're
7489 /// primarily interested in pointer types and enumeration types. We also
7490 /// take member pointer types, for the conditional operator.
7491 /// AllowUserConversions is true if we should look at the conversion
7492 /// functions of a class type, and AllowExplicitConversions if we
7493 /// should also include the explicit conversion functions of a class
7494 /// type.
7495 void
7496 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7497                                                SourceLocation Loc,
7498                                                bool AllowUserConversions,
7499                                                bool AllowExplicitConversions,
7500                                                const Qualifiers &VisibleQuals) {
7501   // Only deal with canonical types.
7502   Ty = Context.getCanonicalType(Ty);
7503 
7504   // Look through reference types; they aren't part of the type of an
7505   // expression for the purposes of conversions.
7506   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7507     Ty = RefTy->getPointeeType();
7508 
7509   // If we're dealing with an array type, decay to the pointer.
7510   if (Ty->isArrayType())
7511     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7512 
7513   // Otherwise, we don't care about qualifiers on the type.
7514   Ty = Ty.getLocalUnqualifiedType();
7515 
7516   // Flag if we ever add a non-record type.
7517   const RecordType *TyRec = Ty->getAs<RecordType>();
7518   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7519 
7520   // Flag if we encounter an arithmetic type.
7521   HasArithmeticOrEnumeralTypes =
7522     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7523 
7524   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7525     PointerTypes.insert(Ty);
7526   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7527     // Insert our type, and its more-qualified variants, into the set
7528     // of types.
7529     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7530       return;
7531   } else if (Ty->isMemberPointerType()) {
7532     // Member pointers are far easier, since the pointee can't be converted.
7533     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7534       return;
7535   } else if (Ty->isEnumeralType()) {
7536     HasArithmeticOrEnumeralTypes = true;
7537     EnumerationTypes.insert(Ty);
7538   } else if (Ty->isVectorType()) {
7539     // We treat vector types as arithmetic types in many contexts as an
7540     // extension.
7541     HasArithmeticOrEnumeralTypes = true;
7542     VectorTypes.insert(Ty);
7543   } else if (Ty->isNullPtrType()) {
7544     HasNullPtrType = true;
7545   } else if (AllowUserConversions && TyRec) {
7546     // No conversion functions in incomplete types.
7547     if (!SemaRef.isCompleteType(Loc, Ty))
7548       return;
7549 
7550     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7551     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7552       if (isa<UsingShadowDecl>(D))
7553         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7554 
7555       // Skip conversion function templates; they don't tell us anything
7556       // about which builtin types we can convert to.
7557       if (isa<FunctionTemplateDecl>(D))
7558         continue;
7559 
7560       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7561       if (AllowExplicitConversions || !Conv->isExplicit()) {
7562         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7563                               VisibleQuals);
7564       }
7565     }
7566   }
7567 }
7568 
7569 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7570 /// the volatile- and non-volatile-qualified assignment operators for the
7571 /// given type to the candidate set.
7572 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7573                                                    QualType T,
7574                                                    ArrayRef<Expr *> Args,
7575                                     OverloadCandidateSet &CandidateSet) {
7576   QualType ParamTypes[2];
7577 
7578   // T& operator=(T&, T)
7579   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7580   ParamTypes[1] = T;
7581   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7582                         /*IsAssignmentOperator=*/true);
7583 
7584   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7585     // volatile T& operator=(volatile T&, T)
7586     ParamTypes[0]
7587       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7588     ParamTypes[1] = T;
7589     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7590                           /*IsAssignmentOperator=*/true);
7591   }
7592 }
7593 
7594 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7595 /// if any, found in visible type conversion functions found in ArgExpr's type.
7596 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7597     Qualifiers VRQuals;
7598     const RecordType *TyRec;
7599     if (const MemberPointerType *RHSMPType =
7600         ArgExpr->getType()->getAs<MemberPointerType>())
7601       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7602     else
7603       TyRec = ArgExpr->getType()->getAs<RecordType>();
7604     if (!TyRec) {
7605       // Just to be safe, assume the worst case.
7606       VRQuals.addVolatile();
7607       VRQuals.addRestrict();
7608       return VRQuals;
7609     }
7610 
7611     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7612     if (!ClassDecl->hasDefinition())
7613       return VRQuals;
7614 
7615     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7616       if (isa<UsingShadowDecl>(D))
7617         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7618       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7619         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7620         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7621           CanTy = ResTypeRef->getPointeeType();
7622         // Need to go down the pointer/mempointer chain and add qualifiers
7623         // as see them.
7624         bool done = false;
7625         while (!done) {
7626           if (CanTy.isRestrictQualified())
7627             VRQuals.addRestrict();
7628           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7629             CanTy = ResTypePtr->getPointeeType();
7630           else if (const MemberPointerType *ResTypeMPtr =
7631                 CanTy->getAs<MemberPointerType>())
7632             CanTy = ResTypeMPtr->getPointeeType();
7633           else
7634             done = true;
7635           if (CanTy.isVolatileQualified())
7636             VRQuals.addVolatile();
7637           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7638             return VRQuals;
7639         }
7640       }
7641     }
7642     return VRQuals;
7643 }
7644 
7645 namespace {
7646 
7647 /// \brief Helper class to manage the addition of builtin operator overload
7648 /// candidates. It provides shared state and utility methods used throughout
7649 /// the process, as well as a helper method to add each group of builtin
7650 /// operator overloads from the standard to a candidate set.
7651 class BuiltinOperatorOverloadBuilder {
7652   // Common instance state available to all overload candidate addition methods.
7653   Sema &S;
7654   ArrayRef<Expr *> Args;
7655   Qualifiers VisibleTypeConversionsQuals;
7656   bool HasArithmeticOrEnumeralCandidateType;
7657   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7658   OverloadCandidateSet &CandidateSet;
7659 
7660   static constexpr int ArithmeticTypesCap = 24;
7661   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7662 
7663   // Define some indices used to iterate over the arithemetic types in
7664   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7665   // types are that preserved by promotion (C++ [over.built]p2).
7666   unsigned FirstIntegralType,
7667            LastIntegralType;
7668   unsigned FirstPromotedIntegralType,
7669            LastPromotedIntegralType;
7670   unsigned FirstPromotedArithmeticType,
7671            LastPromotedArithmeticType;
7672   unsigned NumArithmeticTypes;
7673 
7674   void InitArithmeticTypes() {
7675     // Start of promoted types.
7676     FirstPromotedArithmeticType = 0;
7677     ArithmeticTypes.push_back(S.Context.FloatTy);
7678     ArithmeticTypes.push_back(S.Context.DoubleTy);
7679     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7680     if (S.Context.getTargetInfo().hasFloat128Type())
7681       ArithmeticTypes.push_back(S.Context.Float128Ty);
7682 
7683     // Start of integral types.
7684     FirstIntegralType = ArithmeticTypes.size();
7685     FirstPromotedIntegralType = ArithmeticTypes.size();
7686     ArithmeticTypes.push_back(S.Context.IntTy);
7687     ArithmeticTypes.push_back(S.Context.LongTy);
7688     ArithmeticTypes.push_back(S.Context.LongLongTy);
7689     if (S.Context.getTargetInfo().hasInt128Type())
7690       ArithmeticTypes.push_back(S.Context.Int128Ty);
7691     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7692     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7693     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7694     if (S.Context.getTargetInfo().hasInt128Type())
7695       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7696     LastPromotedIntegralType = ArithmeticTypes.size();
7697     LastPromotedArithmeticType = ArithmeticTypes.size();
7698     // End of promoted types.
7699 
7700     ArithmeticTypes.push_back(S.Context.BoolTy);
7701     ArithmeticTypes.push_back(S.Context.CharTy);
7702     ArithmeticTypes.push_back(S.Context.WCharTy);
7703     ArithmeticTypes.push_back(S.Context.Char16Ty);
7704     ArithmeticTypes.push_back(S.Context.Char32Ty);
7705     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7706     ArithmeticTypes.push_back(S.Context.ShortTy);
7707     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7708     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7709     LastIntegralType = ArithmeticTypes.size();
7710     NumArithmeticTypes = ArithmeticTypes.size();
7711     // End of integral types.
7712     // FIXME: What about complex? What about half?
7713 
7714     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7715            "Enough inline storage for all arithmetic types.");
7716   }
7717 
7718   /// \brief Helper method to factor out the common pattern of adding overloads
7719   /// for '++' and '--' builtin operators.
7720   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7721                                            bool HasVolatile,
7722                                            bool HasRestrict) {
7723     QualType ParamTypes[2] = {
7724       S.Context.getLValueReferenceType(CandidateTy),
7725       S.Context.IntTy
7726     };
7727 
7728     // Non-volatile version.
7729     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7730 
7731     // Use a heuristic to reduce number of builtin candidates in the set:
7732     // add volatile version only if there are conversions to a volatile type.
7733     if (HasVolatile) {
7734       ParamTypes[0] =
7735         S.Context.getLValueReferenceType(
7736           S.Context.getVolatileType(CandidateTy));
7737       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7738     }
7739 
7740     // Add restrict version only if there are conversions to a restrict type
7741     // and our candidate type is a non-restrict-qualified pointer.
7742     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7743         !CandidateTy.isRestrictQualified()) {
7744       ParamTypes[0]
7745         = S.Context.getLValueReferenceType(
7746             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7747       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7748 
7749       if (HasVolatile) {
7750         ParamTypes[0]
7751           = S.Context.getLValueReferenceType(
7752               S.Context.getCVRQualifiedType(CandidateTy,
7753                                             (Qualifiers::Volatile |
7754                                              Qualifiers::Restrict)));
7755         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7756       }
7757     }
7758 
7759   }
7760 
7761 public:
7762   BuiltinOperatorOverloadBuilder(
7763     Sema &S, ArrayRef<Expr *> Args,
7764     Qualifiers VisibleTypeConversionsQuals,
7765     bool HasArithmeticOrEnumeralCandidateType,
7766     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7767     OverloadCandidateSet &CandidateSet)
7768     : S(S), Args(Args),
7769       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7770       HasArithmeticOrEnumeralCandidateType(
7771         HasArithmeticOrEnumeralCandidateType),
7772       CandidateTypes(CandidateTypes),
7773       CandidateSet(CandidateSet) {
7774 
7775     InitArithmeticTypes();
7776   }
7777 
7778   // C++ [over.built]p3:
7779   //
7780   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7781   //   is either volatile or empty, there exist candidate operator
7782   //   functions of the form
7783   //
7784   //       VQ T&      operator++(VQ T&);
7785   //       T          operator++(VQ T&, int);
7786   //
7787   // C++ [over.built]p4:
7788   //
7789   //   For every pair (T, VQ), where T is an arithmetic type other
7790   //   than bool, and VQ is either volatile or empty, there exist
7791   //   candidate operator functions of the form
7792   //
7793   //       VQ T&      operator--(VQ T&);
7794   //       T          operator--(VQ T&, int);
7795   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7796     if (!HasArithmeticOrEnumeralCandidateType)
7797       return;
7798 
7799     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7800          Arith < NumArithmeticTypes; ++Arith) {
7801       addPlusPlusMinusMinusStyleOverloads(
7802         ArithmeticTypes[Arith],
7803         VisibleTypeConversionsQuals.hasVolatile(),
7804         VisibleTypeConversionsQuals.hasRestrict());
7805     }
7806   }
7807 
7808   // C++ [over.built]p5:
7809   //
7810   //   For every pair (T, VQ), where T is a cv-qualified or
7811   //   cv-unqualified object type, and VQ is either volatile or
7812   //   empty, there exist candidate operator functions of the form
7813   //
7814   //       T*VQ&      operator++(T*VQ&);
7815   //       T*VQ&      operator--(T*VQ&);
7816   //       T*         operator++(T*VQ&, int);
7817   //       T*         operator--(T*VQ&, int);
7818   void addPlusPlusMinusMinusPointerOverloads() {
7819     for (BuiltinCandidateTypeSet::iterator
7820               Ptr = CandidateTypes[0].pointer_begin(),
7821            PtrEnd = CandidateTypes[0].pointer_end();
7822          Ptr != PtrEnd; ++Ptr) {
7823       // Skip pointer types that aren't pointers to object types.
7824       if (!(*Ptr)->getPointeeType()->isObjectType())
7825         continue;
7826 
7827       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7828         (!(*Ptr).isVolatileQualified() &&
7829          VisibleTypeConversionsQuals.hasVolatile()),
7830         (!(*Ptr).isRestrictQualified() &&
7831          VisibleTypeConversionsQuals.hasRestrict()));
7832     }
7833   }
7834 
7835   // C++ [over.built]p6:
7836   //   For every cv-qualified or cv-unqualified object type T, there
7837   //   exist candidate operator functions of the form
7838   //
7839   //       T&         operator*(T*);
7840   //
7841   // C++ [over.built]p7:
7842   //   For every function type T that does not have cv-qualifiers or a
7843   //   ref-qualifier, there exist candidate operator functions of the form
7844   //       T&         operator*(T*);
7845   void addUnaryStarPointerOverloads() {
7846     for (BuiltinCandidateTypeSet::iterator
7847               Ptr = CandidateTypes[0].pointer_begin(),
7848            PtrEnd = CandidateTypes[0].pointer_end();
7849          Ptr != PtrEnd; ++Ptr) {
7850       QualType ParamTy = *Ptr;
7851       QualType PointeeTy = ParamTy->getPointeeType();
7852       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7853         continue;
7854 
7855       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7856         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7857           continue;
7858 
7859       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7860     }
7861   }
7862 
7863   // C++ [over.built]p9:
7864   //  For every promoted arithmetic type T, there exist candidate
7865   //  operator functions of the form
7866   //
7867   //       T         operator+(T);
7868   //       T         operator-(T);
7869   void addUnaryPlusOrMinusArithmeticOverloads() {
7870     if (!HasArithmeticOrEnumeralCandidateType)
7871       return;
7872 
7873     for (unsigned Arith = FirstPromotedArithmeticType;
7874          Arith < LastPromotedArithmeticType; ++Arith) {
7875       QualType ArithTy = ArithmeticTypes[Arith];
7876       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7877     }
7878 
7879     // Extension: We also add these operators for vector types.
7880     for (BuiltinCandidateTypeSet::iterator
7881               Vec = CandidateTypes[0].vector_begin(),
7882            VecEnd = CandidateTypes[0].vector_end();
7883          Vec != VecEnd; ++Vec) {
7884       QualType VecTy = *Vec;
7885       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7886     }
7887   }
7888 
7889   // C++ [over.built]p8:
7890   //   For every type T, there exist candidate operator functions of
7891   //   the form
7892   //
7893   //       T*         operator+(T*);
7894   void addUnaryPlusPointerOverloads() {
7895     for (BuiltinCandidateTypeSet::iterator
7896               Ptr = CandidateTypes[0].pointer_begin(),
7897            PtrEnd = CandidateTypes[0].pointer_end();
7898          Ptr != PtrEnd; ++Ptr) {
7899       QualType ParamTy = *Ptr;
7900       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7901     }
7902   }
7903 
7904   // C++ [over.built]p10:
7905   //   For every promoted integral type T, there exist candidate
7906   //   operator functions of the form
7907   //
7908   //        T         operator~(T);
7909   void addUnaryTildePromotedIntegralOverloads() {
7910     if (!HasArithmeticOrEnumeralCandidateType)
7911       return;
7912 
7913     for (unsigned Int = FirstPromotedIntegralType;
7914          Int < LastPromotedIntegralType; ++Int) {
7915       QualType IntTy = ArithmeticTypes[Int];
7916       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7917     }
7918 
7919     // Extension: We also add this operator for vector types.
7920     for (BuiltinCandidateTypeSet::iterator
7921               Vec = CandidateTypes[0].vector_begin(),
7922            VecEnd = CandidateTypes[0].vector_end();
7923          Vec != VecEnd; ++Vec) {
7924       QualType VecTy = *Vec;
7925       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7926     }
7927   }
7928 
7929   // C++ [over.match.oper]p16:
7930   //   For every pointer to member type T or type std::nullptr_t, there
7931   //   exist candidate operator functions of the form
7932   //
7933   //        bool operator==(T,T);
7934   //        bool operator!=(T,T);
7935   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7936     /// Set of (canonical) types that we've already handled.
7937     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7938 
7939     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7940       for (BuiltinCandidateTypeSet::iterator
7941                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7942              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7943            MemPtr != MemPtrEnd;
7944            ++MemPtr) {
7945         // Don't add the same builtin candidate twice.
7946         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7947           continue;
7948 
7949         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7950         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7951       }
7952 
7953       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7954         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7955         if (AddedTypes.insert(NullPtrTy).second) {
7956           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7957           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7958         }
7959       }
7960     }
7961   }
7962 
7963   // C++ [over.built]p15:
7964   //
7965   //   For every T, where T is an enumeration type or a pointer type,
7966   //   there exist candidate operator functions of the form
7967   //
7968   //        bool       operator<(T, T);
7969   //        bool       operator>(T, T);
7970   //        bool       operator<=(T, T);
7971   //        bool       operator>=(T, T);
7972   //        bool       operator==(T, T);
7973   //        bool       operator!=(T, T);
7974   void addRelationalPointerOrEnumeralOverloads() {
7975     // C++ [over.match.oper]p3:
7976     //   [...]the built-in candidates include all of the candidate operator
7977     //   functions defined in 13.6 that, compared to the given operator, [...]
7978     //   do not have the same parameter-type-list as any non-template non-member
7979     //   candidate.
7980     //
7981     // Note that in practice, this only affects enumeration types because there
7982     // aren't any built-in candidates of record type, and a user-defined operator
7983     // must have an operand of record or enumeration type. Also, the only other
7984     // overloaded operator with enumeration arguments, operator=,
7985     // cannot be overloaded for enumeration types, so this is the only place
7986     // where we must suppress candidates like this.
7987     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7988       UserDefinedBinaryOperators;
7989 
7990     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7991       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7992           CandidateTypes[ArgIdx].enumeration_end()) {
7993         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7994                                          CEnd = CandidateSet.end();
7995              C != CEnd; ++C) {
7996           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7997             continue;
7998 
7999           if (C->Function->isFunctionTemplateSpecialization())
8000             continue;
8001 
8002           QualType FirstParamType =
8003             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8004           QualType SecondParamType =
8005             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8006 
8007           // Skip if either parameter isn't of enumeral type.
8008           if (!FirstParamType->isEnumeralType() ||
8009               !SecondParamType->isEnumeralType())
8010             continue;
8011 
8012           // Add this operator to the set of known user-defined operators.
8013           UserDefinedBinaryOperators.insert(
8014             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8015                            S.Context.getCanonicalType(SecondParamType)));
8016         }
8017       }
8018     }
8019 
8020     /// Set of (canonical) types that we've already handled.
8021     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8022 
8023     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8024       for (BuiltinCandidateTypeSet::iterator
8025                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8026              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8027            Ptr != PtrEnd; ++Ptr) {
8028         // Don't add the same builtin candidate twice.
8029         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8030           continue;
8031 
8032         QualType ParamTypes[2] = { *Ptr, *Ptr };
8033         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8034       }
8035       for (BuiltinCandidateTypeSet::iterator
8036                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8037              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8038            Enum != EnumEnd; ++Enum) {
8039         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8040 
8041         // Don't add the same builtin candidate twice, or if a user defined
8042         // candidate exists.
8043         if (!AddedTypes.insert(CanonType).second ||
8044             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8045                                                             CanonType)))
8046           continue;
8047 
8048         QualType ParamTypes[2] = { *Enum, *Enum };
8049         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8050       }
8051     }
8052   }
8053 
8054   // C++ [over.built]p13:
8055   //
8056   //   For every cv-qualified or cv-unqualified object type T
8057   //   there exist candidate operator functions of the form
8058   //
8059   //      T*         operator+(T*, ptrdiff_t);
8060   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8061   //      T*         operator-(T*, ptrdiff_t);
8062   //      T*         operator+(ptrdiff_t, T*);
8063   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8064   //
8065   // C++ [over.built]p14:
8066   //
8067   //   For every T, where T is a pointer to object type, there
8068   //   exist candidate operator functions of the form
8069   //
8070   //      ptrdiff_t  operator-(T, T);
8071   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8072     /// Set of (canonical) types that we've already handled.
8073     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8074 
8075     for (int Arg = 0; Arg < 2; ++Arg) {
8076       QualType AsymmetricParamTypes[2] = {
8077         S.Context.getPointerDiffType(),
8078         S.Context.getPointerDiffType(),
8079       };
8080       for (BuiltinCandidateTypeSet::iterator
8081                 Ptr = CandidateTypes[Arg].pointer_begin(),
8082              PtrEnd = CandidateTypes[Arg].pointer_end();
8083            Ptr != PtrEnd; ++Ptr) {
8084         QualType PointeeTy = (*Ptr)->getPointeeType();
8085         if (!PointeeTy->isObjectType())
8086           continue;
8087 
8088         AsymmetricParamTypes[Arg] = *Ptr;
8089         if (Arg == 0 || Op == OO_Plus) {
8090           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8091           // T* operator+(ptrdiff_t, T*);
8092           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8093         }
8094         if (Op == OO_Minus) {
8095           // ptrdiff_t operator-(T, T);
8096           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8097             continue;
8098 
8099           QualType ParamTypes[2] = { *Ptr, *Ptr };
8100           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8101         }
8102       }
8103     }
8104   }
8105 
8106   // C++ [over.built]p12:
8107   //
8108   //   For every pair of promoted arithmetic types L and R, there
8109   //   exist candidate operator functions of the form
8110   //
8111   //        LR         operator*(L, R);
8112   //        LR         operator/(L, R);
8113   //        LR         operator+(L, R);
8114   //        LR         operator-(L, R);
8115   //        bool       operator<(L, R);
8116   //        bool       operator>(L, R);
8117   //        bool       operator<=(L, R);
8118   //        bool       operator>=(L, R);
8119   //        bool       operator==(L, R);
8120   //        bool       operator!=(L, R);
8121   //
8122   //   where LR is the result of the usual arithmetic conversions
8123   //   between types L and R.
8124   //
8125   // C++ [over.built]p24:
8126   //
8127   //   For every pair of promoted arithmetic types L and R, there exist
8128   //   candidate operator functions of the form
8129   //
8130   //        LR       operator?(bool, L, R);
8131   //
8132   //   where LR is the result of the usual arithmetic conversions
8133   //   between types L and R.
8134   // Our candidates ignore the first parameter.
8135   void addGenericBinaryArithmeticOverloads() {
8136     if (!HasArithmeticOrEnumeralCandidateType)
8137       return;
8138 
8139     for (unsigned Left = FirstPromotedArithmeticType;
8140          Left < LastPromotedArithmeticType; ++Left) {
8141       for (unsigned Right = FirstPromotedArithmeticType;
8142            Right < LastPromotedArithmeticType; ++Right) {
8143         QualType LandR[2] = { ArithmeticTypes[Left],
8144                               ArithmeticTypes[Right] };
8145         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8146       }
8147     }
8148 
8149     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8150     // conditional operator for vector types.
8151     for (BuiltinCandidateTypeSet::iterator
8152               Vec1 = CandidateTypes[0].vector_begin(),
8153            Vec1End = CandidateTypes[0].vector_end();
8154          Vec1 != Vec1End; ++Vec1) {
8155       for (BuiltinCandidateTypeSet::iterator
8156                 Vec2 = CandidateTypes[1].vector_begin(),
8157              Vec2End = CandidateTypes[1].vector_end();
8158            Vec2 != Vec2End; ++Vec2) {
8159         QualType LandR[2] = { *Vec1, *Vec2 };
8160         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8161       }
8162     }
8163   }
8164 
8165   // C++ [over.built]p17:
8166   //
8167   //   For every pair of promoted integral types L and R, there
8168   //   exist candidate operator functions of the form
8169   //
8170   //      LR         operator%(L, R);
8171   //      LR         operator&(L, R);
8172   //      LR         operator^(L, R);
8173   //      LR         operator|(L, R);
8174   //      L          operator<<(L, R);
8175   //      L          operator>>(L, R);
8176   //
8177   //   where LR is the result of the usual arithmetic conversions
8178   //   between types L and R.
8179   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8180     if (!HasArithmeticOrEnumeralCandidateType)
8181       return;
8182 
8183     for (unsigned Left = FirstPromotedIntegralType;
8184          Left < LastPromotedIntegralType; ++Left) {
8185       for (unsigned Right = FirstPromotedIntegralType;
8186            Right < LastPromotedIntegralType; ++Right) {
8187         QualType LandR[2] = { ArithmeticTypes[Left],
8188                               ArithmeticTypes[Right] };
8189         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8190       }
8191     }
8192   }
8193 
8194   // C++ [over.built]p20:
8195   //
8196   //   For every pair (T, VQ), where T is an enumeration or
8197   //   pointer to member type and VQ is either volatile or
8198   //   empty, there exist candidate operator functions of the form
8199   //
8200   //        VQ T&      operator=(VQ T&, T);
8201   void addAssignmentMemberPointerOrEnumeralOverloads() {
8202     /// Set of (canonical) types that we've already handled.
8203     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8204 
8205     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8206       for (BuiltinCandidateTypeSet::iterator
8207                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8208              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8209            Enum != EnumEnd; ++Enum) {
8210         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8211           continue;
8212 
8213         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8214       }
8215 
8216       for (BuiltinCandidateTypeSet::iterator
8217                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8218              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8219            MemPtr != MemPtrEnd; ++MemPtr) {
8220         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8221           continue;
8222 
8223         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8224       }
8225     }
8226   }
8227 
8228   // C++ [over.built]p19:
8229   //
8230   //   For every pair (T, VQ), where T is any type and VQ is either
8231   //   volatile or empty, there exist candidate operator functions
8232   //   of the form
8233   //
8234   //        T*VQ&      operator=(T*VQ&, T*);
8235   //
8236   // C++ [over.built]p21:
8237   //
8238   //   For every pair (T, VQ), where T is a cv-qualified or
8239   //   cv-unqualified object type and VQ is either volatile or
8240   //   empty, there exist candidate operator functions of the form
8241   //
8242   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8243   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8244   void addAssignmentPointerOverloads(bool isEqualOp) {
8245     /// Set of (canonical) types that we've already handled.
8246     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8247 
8248     for (BuiltinCandidateTypeSet::iterator
8249               Ptr = CandidateTypes[0].pointer_begin(),
8250            PtrEnd = CandidateTypes[0].pointer_end();
8251          Ptr != PtrEnd; ++Ptr) {
8252       // If this is operator=, keep track of the builtin candidates we added.
8253       if (isEqualOp)
8254         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8255       else if (!(*Ptr)->getPointeeType()->isObjectType())
8256         continue;
8257 
8258       // non-volatile version
8259       QualType ParamTypes[2] = {
8260         S.Context.getLValueReferenceType(*Ptr),
8261         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8262       };
8263       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8264                             /*IsAssigmentOperator=*/ isEqualOp);
8265 
8266       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8267                           VisibleTypeConversionsQuals.hasVolatile();
8268       if (NeedVolatile) {
8269         // volatile version
8270         ParamTypes[0] =
8271           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8272         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8273                               /*IsAssigmentOperator=*/isEqualOp);
8274       }
8275 
8276       if (!(*Ptr).isRestrictQualified() &&
8277           VisibleTypeConversionsQuals.hasRestrict()) {
8278         // restrict version
8279         ParamTypes[0]
8280           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8281         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8282                               /*IsAssigmentOperator=*/isEqualOp);
8283 
8284         if (NeedVolatile) {
8285           // volatile restrict version
8286           ParamTypes[0]
8287             = S.Context.getLValueReferenceType(
8288                 S.Context.getCVRQualifiedType(*Ptr,
8289                                               (Qualifiers::Volatile |
8290                                                Qualifiers::Restrict)));
8291           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8292                                 /*IsAssigmentOperator=*/isEqualOp);
8293         }
8294       }
8295     }
8296 
8297     if (isEqualOp) {
8298       for (BuiltinCandidateTypeSet::iterator
8299                 Ptr = CandidateTypes[1].pointer_begin(),
8300              PtrEnd = CandidateTypes[1].pointer_end();
8301            Ptr != PtrEnd; ++Ptr) {
8302         // Make sure we don't add the same candidate twice.
8303         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8304           continue;
8305 
8306         QualType ParamTypes[2] = {
8307           S.Context.getLValueReferenceType(*Ptr),
8308           *Ptr,
8309         };
8310 
8311         // non-volatile version
8312         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8313                               /*IsAssigmentOperator=*/true);
8314 
8315         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8316                            VisibleTypeConversionsQuals.hasVolatile();
8317         if (NeedVolatile) {
8318           // volatile version
8319           ParamTypes[0] =
8320             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8321           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8322                                 /*IsAssigmentOperator=*/true);
8323         }
8324 
8325         if (!(*Ptr).isRestrictQualified() &&
8326             VisibleTypeConversionsQuals.hasRestrict()) {
8327           // restrict version
8328           ParamTypes[0]
8329             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8330           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8331                                 /*IsAssigmentOperator=*/true);
8332 
8333           if (NeedVolatile) {
8334             // volatile restrict version
8335             ParamTypes[0]
8336               = S.Context.getLValueReferenceType(
8337                   S.Context.getCVRQualifiedType(*Ptr,
8338                                                 (Qualifiers::Volatile |
8339                                                  Qualifiers::Restrict)));
8340             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8341                                   /*IsAssigmentOperator=*/true);
8342           }
8343         }
8344       }
8345     }
8346   }
8347 
8348   // C++ [over.built]p18:
8349   //
8350   //   For every triple (L, VQ, R), where L is an arithmetic type,
8351   //   VQ is either volatile or empty, and R is a promoted
8352   //   arithmetic type, there exist candidate operator functions of
8353   //   the form
8354   //
8355   //        VQ L&      operator=(VQ L&, R);
8356   //        VQ L&      operator*=(VQ L&, R);
8357   //        VQ L&      operator/=(VQ L&, R);
8358   //        VQ L&      operator+=(VQ L&, R);
8359   //        VQ L&      operator-=(VQ L&, R);
8360   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8361     if (!HasArithmeticOrEnumeralCandidateType)
8362       return;
8363 
8364     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8365       for (unsigned Right = FirstPromotedArithmeticType;
8366            Right < LastPromotedArithmeticType; ++Right) {
8367         QualType ParamTypes[2];
8368         ParamTypes[1] = ArithmeticTypes[Right];
8369 
8370         // Add this built-in operator as a candidate (VQ is empty).
8371         ParamTypes[0] =
8372           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8373         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8374                               /*IsAssigmentOperator=*/isEqualOp);
8375 
8376         // Add this built-in operator as a candidate (VQ is 'volatile').
8377         if (VisibleTypeConversionsQuals.hasVolatile()) {
8378           ParamTypes[0] =
8379             S.Context.getVolatileType(ArithmeticTypes[Left]);
8380           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8381           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8382                                 /*IsAssigmentOperator=*/isEqualOp);
8383         }
8384       }
8385     }
8386 
8387     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8388     for (BuiltinCandidateTypeSet::iterator
8389               Vec1 = CandidateTypes[0].vector_begin(),
8390            Vec1End = CandidateTypes[0].vector_end();
8391          Vec1 != Vec1End; ++Vec1) {
8392       for (BuiltinCandidateTypeSet::iterator
8393                 Vec2 = CandidateTypes[1].vector_begin(),
8394              Vec2End = CandidateTypes[1].vector_end();
8395            Vec2 != Vec2End; ++Vec2) {
8396         QualType ParamTypes[2];
8397         ParamTypes[1] = *Vec2;
8398         // Add this built-in operator as a candidate (VQ is empty).
8399         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8400         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8401                               /*IsAssigmentOperator=*/isEqualOp);
8402 
8403         // Add this built-in operator as a candidate (VQ is 'volatile').
8404         if (VisibleTypeConversionsQuals.hasVolatile()) {
8405           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8406           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8407           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8408                                 /*IsAssigmentOperator=*/isEqualOp);
8409         }
8410       }
8411     }
8412   }
8413 
8414   // C++ [over.built]p22:
8415   //
8416   //   For every triple (L, VQ, R), where L is an integral type, VQ
8417   //   is either volatile or empty, and R is a promoted integral
8418   //   type, there exist candidate operator functions of the form
8419   //
8420   //        VQ L&       operator%=(VQ L&, R);
8421   //        VQ L&       operator<<=(VQ L&, R);
8422   //        VQ L&       operator>>=(VQ L&, R);
8423   //        VQ L&       operator&=(VQ L&, R);
8424   //        VQ L&       operator^=(VQ L&, R);
8425   //        VQ L&       operator|=(VQ L&, R);
8426   void addAssignmentIntegralOverloads() {
8427     if (!HasArithmeticOrEnumeralCandidateType)
8428       return;
8429 
8430     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8431       for (unsigned Right = FirstPromotedIntegralType;
8432            Right < LastPromotedIntegralType; ++Right) {
8433         QualType ParamTypes[2];
8434         ParamTypes[1] = ArithmeticTypes[Right];
8435 
8436         // Add this built-in operator as a candidate (VQ is empty).
8437         ParamTypes[0] =
8438           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8439         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8440         if (VisibleTypeConversionsQuals.hasVolatile()) {
8441           // Add this built-in operator as a candidate (VQ is 'volatile').
8442           ParamTypes[0] = ArithmeticTypes[Left];
8443           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8444           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8445           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8446         }
8447       }
8448     }
8449   }
8450 
8451   // C++ [over.operator]p23:
8452   //
8453   //   There also exist candidate operator functions of the form
8454   //
8455   //        bool        operator!(bool);
8456   //        bool        operator&&(bool, bool);
8457   //        bool        operator||(bool, bool);
8458   void addExclaimOverload() {
8459     QualType ParamTy = S.Context.BoolTy;
8460     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8461                           /*IsAssignmentOperator=*/false,
8462                           /*NumContextualBoolArguments=*/1);
8463   }
8464   void addAmpAmpOrPipePipeOverload() {
8465     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8466     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8467                           /*IsAssignmentOperator=*/false,
8468                           /*NumContextualBoolArguments=*/2);
8469   }
8470 
8471   // C++ [over.built]p13:
8472   //
8473   //   For every cv-qualified or cv-unqualified object type T there
8474   //   exist candidate operator functions of the form
8475   //
8476   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8477   //        T&         operator[](T*, ptrdiff_t);
8478   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8479   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8480   //        T&         operator[](ptrdiff_t, T*);
8481   void addSubscriptOverloads() {
8482     for (BuiltinCandidateTypeSet::iterator
8483               Ptr = CandidateTypes[0].pointer_begin(),
8484            PtrEnd = CandidateTypes[0].pointer_end();
8485          Ptr != PtrEnd; ++Ptr) {
8486       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8487       QualType PointeeType = (*Ptr)->getPointeeType();
8488       if (!PointeeType->isObjectType())
8489         continue;
8490 
8491       // T& operator[](T*, ptrdiff_t)
8492       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8493     }
8494 
8495     for (BuiltinCandidateTypeSet::iterator
8496               Ptr = CandidateTypes[1].pointer_begin(),
8497            PtrEnd = CandidateTypes[1].pointer_end();
8498          Ptr != PtrEnd; ++Ptr) {
8499       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8500       QualType PointeeType = (*Ptr)->getPointeeType();
8501       if (!PointeeType->isObjectType())
8502         continue;
8503 
8504       // T& operator[](ptrdiff_t, T*)
8505       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8506     }
8507   }
8508 
8509   // C++ [over.built]p11:
8510   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8511   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8512   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8513   //    there exist candidate operator functions of the form
8514   //
8515   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8516   //
8517   //    where CV12 is the union of CV1 and CV2.
8518   void addArrowStarOverloads() {
8519     for (BuiltinCandidateTypeSet::iterator
8520              Ptr = CandidateTypes[0].pointer_begin(),
8521            PtrEnd = CandidateTypes[0].pointer_end();
8522          Ptr != PtrEnd; ++Ptr) {
8523       QualType C1Ty = (*Ptr);
8524       QualType C1;
8525       QualifierCollector Q1;
8526       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8527       if (!isa<RecordType>(C1))
8528         continue;
8529       // heuristic to reduce number of builtin candidates in the set.
8530       // Add volatile/restrict version only if there are conversions to a
8531       // volatile/restrict type.
8532       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8533         continue;
8534       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8535         continue;
8536       for (BuiltinCandidateTypeSet::iterator
8537                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8538              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8539            MemPtr != MemPtrEnd; ++MemPtr) {
8540         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8541         QualType C2 = QualType(mptr->getClass(), 0);
8542         C2 = C2.getUnqualifiedType();
8543         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8544           break;
8545         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8546         // build CV12 T&
8547         QualType T = mptr->getPointeeType();
8548         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8549             T.isVolatileQualified())
8550           continue;
8551         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8552             T.isRestrictQualified())
8553           continue;
8554         T = Q1.apply(S.Context, T);
8555         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8556       }
8557     }
8558   }
8559 
8560   // Note that we don't consider the first argument, since it has been
8561   // contextually converted to bool long ago. The candidates below are
8562   // therefore added as binary.
8563   //
8564   // C++ [over.built]p25:
8565   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8566   //   enumeration type, there exist candidate operator functions of the form
8567   //
8568   //        T        operator?(bool, T, T);
8569   //
8570   void addConditionalOperatorOverloads() {
8571     /// Set of (canonical) types that we've already handled.
8572     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8573 
8574     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8575       for (BuiltinCandidateTypeSet::iterator
8576                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8577              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8578            Ptr != PtrEnd; ++Ptr) {
8579         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8580           continue;
8581 
8582         QualType ParamTypes[2] = { *Ptr, *Ptr };
8583         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8584       }
8585 
8586       for (BuiltinCandidateTypeSet::iterator
8587                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8588              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8589            MemPtr != MemPtrEnd; ++MemPtr) {
8590         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8591           continue;
8592 
8593         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8594         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8595       }
8596 
8597       if (S.getLangOpts().CPlusPlus11) {
8598         for (BuiltinCandidateTypeSet::iterator
8599                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8600                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8601              Enum != EnumEnd; ++Enum) {
8602           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8603             continue;
8604 
8605           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8606             continue;
8607 
8608           QualType ParamTypes[2] = { *Enum, *Enum };
8609           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8610         }
8611       }
8612     }
8613   }
8614 };
8615 
8616 } // end anonymous namespace
8617 
8618 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8619 /// operator overloads to the candidate set (C++ [over.built]), based
8620 /// on the operator @p Op and the arguments given. For example, if the
8621 /// operator is a binary '+', this routine might add "int
8622 /// operator+(int, int)" to cover integer addition.
8623 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8624                                         SourceLocation OpLoc,
8625                                         ArrayRef<Expr *> Args,
8626                                         OverloadCandidateSet &CandidateSet) {
8627   // Find all of the types that the arguments can convert to, but only
8628   // if the operator we're looking at has built-in operator candidates
8629   // that make use of these types. Also record whether we encounter non-record
8630   // candidate types or either arithmetic or enumeral candidate types.
8631   Qualifiers VisibleTypeConversionsQuals;
8632   VisibleTypeConversionsQuals.addConst();
8633   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8634     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8635 
8636   bool HasNonRecordCandidateType = false;
8637   bool HasArithmeticOrEnumeralCandidateType = false;
8638   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8639   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8640     CandidateTypes.emplace_back(*this);
8641     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8642                                                  OpLoc,
8643                                                  true,
8644                                                  (Op == OO_Exclaim ||
8645                                                   Op == OO_AmpAmp ||
8646                                                   Op == OO_PipePipe),
8647                                                  VisibleTypeConversionsQuals);
8648     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8649         CandidateTypes[ArgIdx].hasNonRecordTypes();
8650     HasArithmeticOrEnumeralCandidateType =
8651         HasArithmeticOrEnumeralCandidateType ||
8652         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8653   }
8654 
8655   // Exit early when no non-record types have been added to the candidate set
8656   // for any of the arguments to the operator.
8657   //
8658   // We can't exit early for !, ||, or &&, since there we have always have
8659   // 'bool' overloads.
8660   if (!HasNonRecordCandidateType &&
8661       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8662     return;
8663 
8664   // Setup an object to manage the common state for building overloads.
8665   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8666                                            VisibleTypeConversionsQuals,
8667                                            HasArithmeticOrEnumeralCandidateType,
8668                                            CandidateTypes, CandidateSet);
8669 
8670   // Dispatch over the operation to add in only those overloads which apply.
8671   switch (Op) {
8672   case OO_None:
8673   case NUM_OVERLOADED_OPERATORS:
8674     llvm_unreachable("Expected an overloaded operator");
8675 
8676   case OO_New:
8677   case OO_Delete:
8678   case OO_Array_New:
8679   case OO_Array_Delete:
8680   case OO_Call:
8681     llvm_unreachable(
8682                     "Special operators don't use AddBuiltinOperatorCandidates");
8683 
8684   case OO_Comma:
8685   case OO_Arrow:
8686   case OO_Coawait:
8687     // C++ [over.match.oper]p3:
8688     //   -- For the operator ',', the unary operator '&', the
8689     //      operator '->', or the operator 'co_await', the
8690     //      built-in candidates set is empty.
8691     break;
8692 
8693   case OO_Plus: // '+' is either unary or binary
8694     if (Args.size() == 1)
8695       OpBuilder.addUnaryPlusPointerOverloads();
8696     LLVM_FALLTHROUGH;
8697 
8698   case OO_Minus: // '-' is either unary or binary
8699     if (Args.size() == 1) {
8700       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8701     } else {
8702       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8703       OpBuilder.addGenericBinaryArithmeticOverloads();
8704     }
8705     break;
8706 
8707   case OO_Star: // '*' is either unary or binary
8708     if (Args.size() == 1)
8709       OpBuilder.addUnaryStarPointerOverloads();
8710     else
8711       OpBuilder.addGenericBinaryArithmeticOverloads();
8712     break;
8713 
8714   case OO_Slash:
8715     OpBuilder.addGenericBinaryArithmeticOverloads();
8716     break;
8717 
8718   case OO_PlusPlus:
8719   case OO_MinusMinus:
8720     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8721     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8722     break;
8723 
8724   case OO_EqualEqual:
8725   case OO_ExclaimEqual:
8726     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8727     LLVM_FALLTHROUGH;
8728 
8729   case OO_Less:
8730   case OO_Greater:
8731   case OO_LessEqual:
8732   case OO_GreaterEqual:
8733     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8734     OpBuilder.addGenericBinaryArithmeticOverloads();
8735     break;
8736 
8737   case OO_Spaceship:
8738     llvm_unreachable("<=> expressions not supported yet");
8739 
8740   case OO_Percent:
8741   case OO_Caret:
8742   case OO_Pipe:
8743   case OO_LessLess:
8744   case OO_GreaterGreater:
8745     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8746     break;
8747 
8748   case OO_Amp: // '&' is either unary or binary
8749     if (Args.size() == 1)
8750       // C++ [over.match.oper]p3:
8751       //   -- For the operator ',', the unary operator '&', or the
8752       //      operator '->', the built-in candidates set is empty.
8753       break;
8754 
8755     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8756     break;
8757 
8758   case OO_Tilde:
8759     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8760     break;
8761 
8762   case OO_Equal:
8763     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8764     LLVM_FALLTHROUGH;
8765 
8766   case OO_PlusEqual:
8767   case OO_MinusEqual:
8768     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8769     LLVM_FALLTHROUGH;
8770 
8771   case OO_StarEqual:
8772   case OO_SlashEqual:
8773     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8774     break;
8775 
8776   case OO_PercentEqual:
8777   case OO_LessLessEqual:
8778   case OO_GreaterGreaterEqual:
8779   case OO_AmpEqual:
8780   case OO_CaretEqual:
8781   case OO_PipeEqual:
8782     OpBuilder.addAssignmentIntegralOverloads();
8783     break;
8784 
8785   case OO_Exclaim:
8786     OpBuilder.addExclaimOverload();
8787     break;
8788 
8789   case OO_AmpAmp:
8790   case OO_PipePipe:
8791     OpBuilder.addAmpAmpOrPipePipeOverload();
8792     break;
8793 
8794   case OO_Subscript:
8795     OpBuilder.addSubscriptOverloads();
8796     break;
8797 
8798   case OO_ArrowStar:
8799     OpBuilder.addArrowStarOverloads();
8800     break;
8801 
8802   case OO_Conditional:
8803     OpBuilder.addConditionalOperatorOverloads();
8804     OpBuilder.addGenericBinaryArithmeticOverloads();
8805     break;
8806   }
8807 }
8808 
8809 /// \brief Add function candidates found via argument-dependent lookup
8810 /// to the set of overloading candidates.
8811 ///
8812 /// This routine performs argument-dependent name lookup based on the
8813 /// given function name (which may also be an operator name) and adds
8814 /// all of the overload candidates found by ADL to the overload
8815 /// candidate set (C++ [basic.lookup.argdep]).
8816 void
8817 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8818                                            SourceLocation Loc,
8819                                            ArrayRef<Expr *> Args,
8820                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8821                                            OverloadCandidateSet& CandidateSet,
8822                                            bool PartialOverloading) {
8823   ADLResult Fns;
8824 
8825   // FIXME: This approach for uniquing ADL results (and removing
8826   // redundant candidates from the set) relies on pointer-equality,
8827   // which means we need to key off the canonical decl.  However,
8828   // always going back to the canonical decl might not get us the
8829   // right set of default arguments.  What default arguments are
8830   // we supposed to consider on ADL candidates, anyway?
8831 
8832   // FIXME: Pass in the explicit template arguments?
8833   ArgumentDependentLookup(Name, Loc, Args, Fns);
8834 
8835   // Erase all of the candidates we already knew about.
8836   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8837                                    CandEnd = CandidateSet.end();
8838        Cand != CandEnd; ++Cand)
8839     if (Cand->Function) {
8840       Fns.erase(Cand->Function);
8841       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8842         Fns.erase(FunTmpl);
8843     }
8844 
8845   // For each of the ADL candidates we found, add it to the overload
8846   // set.
8847   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8848     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8849     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8850       if (ExplicitTemplateArgs)
8851         continue;
8852 
8853       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8854                            PartialOverloading);
8855     } else
8856       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8857                                    FoundDecl, ExplicitTemplateArgs,
8858                                    Args, CandidateSet, PartialOverloading);
8859   }
8860 }
8861 
8862 namespace {
8863 enum class Comparison { Equal, Better, Worse };
8864 }
8865 
8866 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8867 /// overload resolution.
8868 ///
8869 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8870 /// Cand1's first N enable_if attributes have precisely the same conditions as
8871 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8872 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8873 ///
8874 /// Note that you can have a pair of candidates such that Cand1's enable_if
8875 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8876 /// worse than Cand1's.
8877 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8878                                        const FunctionDecl *Cand2) {
8879   // Common case: One (or both) decls don't have enable_if attrs.
8880   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8881   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8882   if (!Cand1Attr || !Cand2Attr) {
8883     if (Cand1Attr == Cand2Attr)
8884       return Comparison::Equal;
8885     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8886   }
8887 
8888   // FIXME: The next several lines are just
8889   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8890   // instead of reverse order which is how they're stored in the AST.
8891   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8892   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8893 
8894   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8895   // has fewer enable_if attributes than Cand2.
8896   if (Cand1Attrs.size() < Cand2Attrs.size())
8897     return Comparison::Worse;
8898 
8899   auto Cand1I = Cand1Attrs.begin();
8900   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8901   for (auto &Cand2A : Cand2Attrs) {
8902     Cand1ID.clear();
8903     Cand2ID.clear();
8904 
8905     auto &Cand1A = *Cand1I++;
8906     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8907     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8908     if (Cand1ID != Cand2ID)
8909       return Comparison::Worse;
8910   }
8911 
8912   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8913 }
8914 
8915 /// isBetterOverloadCandidate - Determines whether the first overload
8916 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8917 bool clang::isBetterOverloadCandidate(
8918     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8919     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8920   // Define viable functions to be better candidates than non-viable
8921   // functions.
8922   if (!Cand2.Viable)
8923     return Cand1.Viable;
8924   else if (!Cand1.Viable)
8925     return false;
8926 
8927   // C++ [over.match.best]p1:
8928   //
8929   //   -- if F is a static member function, ICS1(F) is defined such
8930   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8931   //      any function G, and, symmetrically, ICS1(G) is neither
8932   //      better nor worse than ICS1(F).
8933   unsigned StartArg = 0;
8934   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8935     StartArg = 1;
8936 
8937   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8938     // We don't allow incompatible pointer conversions in C++.
8939     if (!S.getLangOpts().CPlusPlus)
8940       return ICS.isStandard() &&
8941              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8942 
8943     // The only ill-formed conversion we allow in C++ is the string literal to
8944     // char* conversion, which is only considered ill-formed after C++11.
8945     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8946            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8947   };
8948 
8949   // Define functions that don't require ill-formed conversions for a given
8950   // argument to be better candidates than functions that do.
8951   unsigned NumArgs = Cand1.Conversions.size();
8952   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8953   bool HasBetterConversion = false;
8954   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8955     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8956     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8957     if (Cand1Bad != Cand2Bad) {
8958       if (Cand1Bad)
8959         return false;
8960       HasBetterConversion = true;
8961     }
8962   }
8963 
8964   if (HasBetterConversion)
8965     return true;
8966 
8967   // C++ [over.match.best]p1:
8968   //   A viable function F1 is defined to be a better function than another
8969   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8970   //   conversion sequence than ICSi(F2), and then...
8971   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8972     switch (CompareImplicitConversionSequences(S, Loc,
8973                                                Cand1.Conversions[ArgIdx],
8974                                                Cand2.Conversions[ArgIdx])) {
8975     case ImplicitConversionSequence::Better:
8976       // Cand1 has a better conversion sequence.
8977       HasBetterConversion = true;
8978       break;
8979 
8980     case ImplicitConversionSequence::Worse:
8981       // Cand1 can't be better than Cand2.
8982       return false;
8983 
8984     case ImplicitConversionSequence::Indistinguishable:
8985       // Do nothing.
8986       break;
8987     }
8988   }
8989 
8990   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8991   //       ICSj(F2), or, if not that,
8992   if (HasBetterConversion)
8993     return true;
8994 
8995   //   -- the context is an initialization by user-defined conversion
8996   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8997   //      from the return type of F1 to the destination type (i.e.,
8998   //      the type of the entity being initialized) is a better
8999   //      conversion sequence than the standard conversion sequence
9000   //      from the return type of F2 to the destination type.
9001   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9002       Cand1.Function && Cand2.Function &&
9003       isa<CXXConversionDecl>(Cand1.Function) &&
9004       isa<CXXConversionDecl>(Cand2.Function)) {
9005     // First check whether we prefer one of the conversion functions over the
9006     // other. This only distinguishes the results in non-standard, extension
9007     // cases such as the conversion from a lambda closure type to a function
9008     // pointer or block.
9009     ImplicitConversionSequence::CompareKind Result =
9010         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9011     if (Result == ImplicitConversionSequence::Indistinguishable)
9012       Result = CompareStandardConversionSequences(S, Loc,
9013                                                   Cand1.FinalConversion,
9014                                                   Cand2.FinalConversion);
9015 
9016     if (Result != ImplicitConversionSequence::Indistinguishable)
9017       return Result == ImplicitConversionSequence::Better;
9018 
9019     // FIXME: Compare kind of reference binding if conversion functions
9020     // convert to a reference type used in direct reference binding, per
9021     // C++14 [over.match.best]p1 section 2 bullet 3.
9022   }
9023 
9024   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9025   // as combined with the resolution to CWG issue 243.
9026   //
9027   // When the context is initialization by constructor ([over.match.ctor] or
9028   // either phase of [over.match.list]), a constructor is preferred over
9029   // a conversion function.
9030   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9031       Cand1.Function && Cand2.Function &&
9032       isa<CXXConstructorDecl>(Cand1.Function) !=
9033           isa<CXXConstructorDecl>(Cand2.Function))
9034     return isa<CXXConstructorDecl>(Cand1.Function);
9035 
9036   //    -- F1 is a non-template function and F2 is a function template
9037   //       specialization, or, if not that,
9038   bool Cand1IsSpecialization = Cand1.Function &&
9039                                Cand1.Function->getPrimaryTemplate();
9040   bool Cand2IsSpecialization = Cand2.Function &&
9041                                Cand2.Function->getPrimaryTemplate();
9042   if (Cand1IsSpecialization != Cand2IsSpecialization)
9043     return Cand2IsSpecialization;
9044 
9045   //   -- F1 and F2 are function template specializations, and the function
9046   //      template for F1 is more specialized than the template for F2
9047   //      according to the partial ordering rules described in 14.5.5.2, or,
9048   //      if not that,
9049   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9050     if (FunctionTemplateDecl *BetterTemplate
9051           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9052                                          Cand2.Function->getPrimaryTemplate(),
9053                                          Loc,
9054                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9055                                                              : TPOC_Call,
9056                                          Cand1.ExplicitCallArguments,
9057                                          Cand2.ExplicitCallArguments))
9058       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9059   }
9060 
9061   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9062   // A derived-class constructor beats an (inherited) base class constructor.
9063   bool Cand1IsInherited =
9064       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9065   bool Cand2IsInherited =
9066       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9067   if (Cand1IsInherited != Cand2IsInherited)
9068     return Cand2IsInherited;
9069   else if (Cand1IsInherited) {
9070     assert(Cand2IsInherited);
9071     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9072     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9073     if (Cand1Class->isDerivedFrom(Cand2Class))
9074       return true;
9075     if (Cand2Class->isDerivedFrom(Cand1Class))
9076       return false;
9077     // Inherited from sibling base classes: still ambiguous.
9078   }
9079 
9080   // Check C++17 tie-breakers for deduction guides.
9081   {
9082     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9083     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9084     if (Guide1 && Guide2) {
9085       //  -- F1 is generated from a deduction-guide and F2 is not
9086       if (Guide1->isImplicit() != Guide2->isImplicit())
9087         return Guide2->isImplicit();
9088 
9089       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9090       if (Guide1->isCopyDeductionCandidate())
9091         return true;
9092     }
9093   }
9094 
9095   // Check for enable_if value-based overload resolution.
9096   if (Cand1.Function && Cand2.Function) {
9097     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9098     if (Cmp != Comparison::Equal)
9099       return Cmp == Comparison::Better;
9100   }
9101 
9102   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9103     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9104     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9105            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9106   }
9107 
9108   bool HasPS1 = Cand1.Function != nullptr &&
9109                 functionHasPassObjectSizeParams(Cand1.Function);
9110   bool HasPS2 = Cand2.Function != nullptr &&
9111                 functionHasPassObjectSizeParams(Cand2.Function);
9112   return HasPS1 != HasPS2 && HasPS1;
9113 }
9114 
9115 /// Determine whether two declarations are "equivalent" for the purposes of
9116 /// name lookup and overload resolution. This applies when the same internal/no
9117 /// linkage entity is defined by two modules (probably by textually including
9118 /// the same header). In such a case, we don't consider the declarations to
9119 /// declare the same entity, but we also don't want lookups with both
9120 /// declarations visible to be ambiguous in some cases (this happens when using
9121 /// a modularized libstdc++).
9122 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9123                                                   const NamedDecl *B) {
9124   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9125   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9126   if (!VA || !VB)
9127     return false;
9128 
9129   // The declarations must be declaring the same name as an internal linkage
9130   // entity in different modules.
9131   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9132           VB->getDeclContext()->getRedeclContext()) ||
9133       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9134           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9135       VA->isExternallyVisible() || VB->isExternallyVisible())
9136     return false;
9137 
9138   // Check that the declarations appear to be equivalent.
9139   //
9140   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9141   // For constants and functions, we should check the initializer or body is
9142   // the same. For non-constant variables, we shouldn't allow it at all.
9143   if (Context.hasSameType(VA->getType(), VB->getType()))
9144     return true;
9145 
9146   // Enum constants within unnamed enumerations will have different types, but
9147   // may still be similar enough to be interchangeable for our purposes.
9148   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9149     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9150       // Only handle anonymous enums. If the enumerations were named and
9151       // equivalent, they would have been merged to the same type.
9152       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9153       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9154       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9155           !Context.hasSameType(EnumA->getIntegerType(),
9156                                EnumB->getIntegerType()))
9157         return false;
9158       // Allow this only if the value is the same for both enumerators.
9159       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9160     }
9161   }
9162 
9163   // Nothing else is sufficiently similar.
9164   return false;
9165 }
9166 
9167 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9168     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9169   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9170 
9171   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9172   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9173       << !M << (M ? M->getFullModuleName() : "");
9174 
9175   for (auto *E : Equiv) {
9176     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9177     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9178         << !M << (M ? M->getFullModuleName() : "");
9179   }
9180 }
9181 
9182 /// \brief Computes the best viable function (C++ 13.3.3)
9183 /// within an overload candidate set.
9184 ///
9185 /// \param Loc The location of the function name (or operator symbol) for
9186 /// which overload resolution occurs.
9187 ///
9188 /// \param Best If overload resolution was successful or found a deleted
9189 /// function, \p Best points to the candidate function found.
9190 ///
9191 /// \returns The result of overload resolution.
9192 OverloadingResult
9193 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9194                                          iterator &Best) {
9195   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9196   std::transform(begin(), end(), std::back_inserter(Candidates),
9197                  [](OverloadCandidate &Cand) { return &Cand; });
9198 
9199   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9200   // are accepted by both clang and NVCC. However, during a particular
9201   // compilation mode only one call variant is viable. We need to
9202   // exclude non-viable overload candidates from consideration based
9203   // only on their host/device attributes. Specifically, if one
9204   // candidate call is WrongSide and the other is SameSide, we ignore
9205   // the WrongSide candidate.
9206   if (S.getLangOpts().CUDA) {
9207     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9208     bool ContainsSameSideCandidate =
9209         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9210           return Cand->Function &&
9211                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9212                      Sema::CFP_SameSide;
9213         });
9214     if (ContainsSameSideCandidate) {
9215       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9216         return Cand->Function &&
9217                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9218                    Sema::CFP_WrongSide;
9219       };
9220       llvm::erase_if(Candidates, IsWrongSideCandidate);
9221     }
9222   }
9223 
9224   // Find the best viable function.
9225   Best = end();
9226   for (auto *Cand : Candidates)
9227     if (Cand->Viable)
9228       if (Best == end() ||
9229           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9230         Best = Cand;
9231 
9232   // If we didn't find any viable functions, abort.
9233   if (Best == end())
9234     return OR_No_Viable_Function;
9235 
9236   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9237 
9238   // Make sure that this function is better than every other viable
9239   // function. If not, we have an ambiguity.
9240   for (auto *Cand : Candidates) {
9241     if (Cand->Viable && Cand != Best &&
9242         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9243       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9244                                                    Cand->Function)) {
9245         EquivalentCands.push_back(Cand->Function);
9246         continue;
9247       }
9248 
9249       Best = end();
9250       return OR_Ambiguous;
9251     }
9252   }
9253 
9254   // Best is the best viable function.
9255   if (Best->Function &&
9256       (Best->Function->isDeleted() ||
9257        S.isFunctionConsideredUnavailable(Best->Function)))
9258     return OR_Deleted;
9259 
9260   if (!EquivalentCands.empty())
9261     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9262                                                     EquivalentCands);
9263 
9264   return OR_Success;
9265 }
9266 
9267 namespace {
9268 
9269 enum OverloadCandidateKind {
9270   oc_function,
9271   oc_method,
9272   oc_constructor,
9273   oc_function_template,
9274   oc_method_template,
9275   oc_constructor_template,
9276   oc_implicit_default_constructor,
9277   oc_implicit_copy_constructor,
9278   oc_implicit_move_constructor,
9279   oc_implicit_copy_assignment,
9280   oc_implicit_move_assignment,
9281   oc_inherited_constructor,
9282   oc_inherited_constructor_template
9283 };
9284 
9285 static OverloadCandidateKind
9286 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9287                           std::string &Description) {
9288   bool isTemplate = false;
9289 
9290   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9291     isTemplate = true;
9292     Description = S.getTemplateArgumentBindingsText(
9293       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9294   }
9295 
9296   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9297     if (!Ctor->isImplicit()) {
9298       if (isa<ConstructorUsingShadowDecl>(Found))
9299         return isTemplate ? oc_inherited_constructor_template
9300                           : oc_inherited_constructor;
9301       else
9302         return isTemplate ? oc_constructor_template : oc_constructor;
9303     }
9304 
9305     if (Ctor->isDefaultConstructor())
9306       return oc_implicit_default_constructor;
9307 
9308     if (Ctor->isMoveConstructor())
9309       return oc_implicit_move_constructor;
9310 
9311     assert(Ctor->isCopyConstructor() &&
9312            "unexpected sort of implicit constructor");
9313     return oc_implicit_copy_constructor;
9314   }
9315 
9316   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9317     // This actually gets spelled 'candidate function' for now, but
9318     // it doesn't hurt to split it out.
9319     if (!Meth->isImplicit())
9320       return isTemplate ? oc_method_template : oc_method;
9321 
9322     if (Meth->isMoveAssignmentOperator())
9323       return oc_implicit_move_assignment;
9324 
9325     if (Meth->isCopyAssignmentOperator())
9326       return oc_implicit_copy_assignment;
9327 
9328     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9329     return oc_method;
9330   }
9331 
9332   return isTemplate ? oc_function_template : oc_function;
9333 }
9334 
9335 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9336   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9337   // set.
9338   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9339     S.Diag(FoundDecl->getLocation(),
9340            diag::note_ovl_candidate_inherited_constructor)
9341       << Shadow->getNominatedBaseClass();
9342 }
9343 
9344 } // end anonymous namespace
9345 
9346 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9347                                     const FunctionDecl *FD) {
9348   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9349     bool AlwaysTrue;
9350     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9351       return false;
9352     if (!AlwaysTrue)
9353       return false;
9354   }
9355   return true;
9356 }
9357 
9358 /// \brief Returns true if we can take the address of the function.
9359 ///
9360 /// \param Complain - If true, we'll emit a diagnostic
9361 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9362 ///   we in overload resolution?
9363 /// \param Loc - The location of the statement we're complaining about. Ignored
9364 ///   if we're not complaining, or if we're in overload resolution.
9365 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9366                                               bool Complain,
9367                                               bool InOverloadResolution,
9368                                               SourceLocation Loc) {
9369   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9370     if (Complain) {
9371       if (InOverloadResolution)
9372         S.Diag(FD->getLocStart(),
9373                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9374       else
9375         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9376     }
9377     return false;
9378   }
9379 
9380   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9381     return P->hasAttr<PassObjectSizeAttr>();
9382   });
9383   if (I == FD->param_end())
9384     return true;
9385 
9386   if (Complain) {
9387     // Add one to ParamNo because it's user-facing
9388     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9389     if (InOverloadResolution)
9390       S.Diag(FD->getLocation(),
9391              diag::note_ovl_candidate_has_pass_object_size_params)
9392           << ParamNo;
9393     else
9394       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9395           << FD << ParamNo;
9396   }
9397   return false;
9398 }
9399 
9400 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9401                                                const FunctionDecl *FD) {
9402   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9403                                            /*InOverloadResolution=*/true,
9404                                            /*Loc=*/SourceLocation());
9405 }
9406 
9407 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9408                                              bool Complain,
9409                                              SourceLocation Loc) {
9410   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9411                                              /*InOverloadResolution=*/false,
9412                                              Loc);
9413 }
9414 
9415 // Notes the location of an overload candidate.
9416 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9417                                  QualType DestType, bool TakingAddress) {
9418   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9419     return;
9420   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9421     return;
9422 
9423   std::string FnDesc;
9424   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9425   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9426                              << (unsigned) K << Fn << FnDesc;
9427 
9428   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9429   Diag(Fn->getLocation(), PD);
9430   MaybeEmitInheritedConstructorNote(*this, Found);
9431 }
9432 
9433 // Notes the location of all overload candidates designated through
9434 // OverloadedExpr
9435 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9436                                      bool TakingAddress) {
9437   assert(OverloadedExpr->getType() == Context.OverloadTy);
9438 
9439   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9440   OverloadExpr *OvlExpr = Ovl.Expression;
9441 
9442   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9443                             IEnd = OvlExpr->decls_end();
9444        I != IEnd; ++I) {
9445     if (FunctionTemplateDecl *FunTmpl =
9446                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9447       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9448                             TakingAddress);
9449     } else if (FunctionDecl *Fun
9450                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9451       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9452     }
9453   }
9454 }
9455 
9456 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9457 /// "lead" diagnostic; it will be given two arguments, the source and
9458 /// target types of the conversion.
9459 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9460                                  Sema &S,
9461                                  SourceLocation CaretLoc,
9462                                  const PartialDiagnostic &PDiag) const {
9463   S.Diag(CaretLoc, PDiag)
9464     << Ambiguous.getFromType() << Ambiguous.getToType();
9465   // FIXME: The note limiting machinery is borrowed from
9466   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9467   // refactoring here.
9468   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9469   unsigned CandsShown = 0;
9470   AmbiguousConversionSequence::const_iterator I, E;
9471   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9472     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9473       break;
9474     ++CandsShown;
9475     S.NoteOverloadCandidate(I->first, I->second);
9476   }
9477   if (I != E)
9478     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9479 }
9480 
9481 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9482                                   unsigned I, bool TakingCandidateAddress) {
9483   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9484   assert(Conv.isBad());
9485   assert(Cand->Function && "for now, candidate must be a function");
9486   FunctionDecl *Fn = Cand->Function;
9487 
9488   // There's a conversion slot for the object argument if this is a
9489   // non-constructor method.  Note that 'I' corresponds the
9490   // conversion-slot index.
9491   bool isObjectArgument = false;
9492   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9493     if (I == 0)
9494       isObjectArgument = true;
9495     else
9496       I--;
9497   }
9498 
9499   std::string FnDesc;
9500   OverloadCandidateKind FnKind =
9501       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9502 
9503   Expr *FromExpr = Conv.Bad.FromExpr;
9504   QualType FromTy = Conv.Bad.getFromType();
9505   QualType ToTy = Conv.Bad.getToType();
9506 
9507   if (FromTy == S.Context.OverloadTy) {
9508     assert(FromExpr && "overload set argument came from implicit argument?");
9509     Expr *E = FromExpr->IgnoreParens();
9510     if (isa<UnaryOperator>(E))
9511       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9512     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9513 
9514     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9515       << (unsigned) FnKind << FnDesc
9516       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9517       << ToTy << Name << I+1;
9518     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9519     return;
9520   }
9521 
9522   // Do some hand-waving analysis to see if the non-viability is due
9523   // to a qualifier mismatch.
9524   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9525   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9526   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9527     CToTy = RT->getPointeeType();
9528   else {
9529     // TODO: detect and diagnose the full richness of const mismatches.
9530     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9531       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9532         CFromTy = FromPT->getPointeeType();
9533         CToTy = ToPT->getPointeeType();
9534       }
9535   }
9536 
9537   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9538       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9539     Qualifiers FromQs = CFromTy.getQualifiers();
9540     Qualifiers ToQs = CToTy.getQualifiers();
9541 
9542     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9543       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9544         << (unsigned) FnKind << FnDesc
9545         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9546         << FromTy
9547         << FromQs.getAddressSpaceAttributePrintValue()
9548         << ToQs.getAddressSpaceAttributePrintValue()
9549         << (unsigned) isObjectArgument << I+1;
9550       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9551       return;
9552     }
9553 
9554     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9555       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9556         << (unsigned) FnKind << FnDesc
9557         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9558         << FromTy
9559         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9560         << (unsigned) isObjectArgument << I+1;
9561       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9562       return;
9563     }
9564 
9565     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9566       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9567       << (unsigned) FnKind << FnDesc
9568       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9569       << FromTy
9570       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9571       << (unsigned) isObjectArgument << I+1;
9572       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9573       return;
9574     }
9575 
9576     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9577       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9578         << (unsigned) FnKind << FnDesc
9579         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9580         << FromTy << FromQs.hasUnaligned() << I+1;
9581       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9582       return;
9583     }
9584 
9585     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9586     assert(CVR && "unexpected qualifiers mismatch");
9587 
9588     if (isObjectArgument) {
9589       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9590         << (unsigned) FnKind << FnDesc
9591         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9592         << FromTy << (CVR - 1);
9593     } else {
9594       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9595         << (unsigned) FnKind << FnDesc
9596         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9597         << FromTy << (CVR - 1) << I+1;
9598     }
9599     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9600     return;
9601   }
9602 
9603   // Special diagnostic for failure to convert an initializer list, since
9604   // telling the user that it has type void is not useful.
9605   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9606     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9607       << (unsigned) FnKind << FnDesc
9608       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9609       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9610     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9611     return;
9612   }
9613 
9614   // Diagnose references or pointers to incomplete types differently,
9615   // since it's far from impossible that the incompleteness triggered
9616   // the failure.
9617   QualType TempFromTy = FromTy.getNonReferenceType();
9618   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9619     TempFromTy = PTy->getPointeeType();
9620   if (TempFromTy->isIncompleteType()) {
9621     // Emit the generic diagnostic and, optionally, add the hints to it.
9622     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9623       << (unsigned) FnKind << FnDesc
9624       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9625       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9626       << (unsigned) (Cand->Fix.Kind);
9627 
9628     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9629     return;
9630   }
9631 
9632   // Diagnose base -> derived pointer conversions.
9633   unsigned BaseToDerivedConversion = 0;
9634   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9635     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9636       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9637                                                FromPtrTy->getPointeeType()) &&
9638           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9639           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9640           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9641                           FromPtrTy->getPointeeType()))
9642         BaseToDerivedConversion = 1;
9643     }
9644   } else if (const ObjCObjectPointerType *FromPtrTy
9645                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9646     if (const ObjCObjectPointerType *ToPtrTy
9647                                         = ToTy->getAs<ObjCObjectPointerType>())
9648       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9649         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9650           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9651                                                 FromPtrTy->getPointeeType()) &&
9652               FromIface->isSuperClassOf(ToIface))
9653             BaseToDerivedConversion = 2;
9654   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9655     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9656         !FromTy->isIncompleteType() &&
9657         !ToRefTy->getPointeeType()->isIncompleteType() &&
9658         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9659       BaseToDerivedConversion = 3;
9660     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9661                ToTy.getNonReferenceType().getCanonicalType() ==
9662                FromTy.getNonReferenceType().getCanonicalType()) {
9663       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9664         << (unsigned) FnKind << FnDesc
9665         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9666         << (unsigned) isObjectArgument << I + 1;
9667       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9668       return;
9669     }
9670   }
9671 
9672   if (BaseToDerivedConversion) {
9673     S.Diag(Fn->getLocation(),
9674            diag::note_ovl_candidate_bad_base_to_derived_conv)
9675       << (unsigned) FnKind << FnDesc
9676       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9677       << (BaseToDerivedConversion - 1)
9678       << FromTy << ToTy << I+1;
9679     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9680     return;
9681   }
9682 
9683   if (isa<ObjCObjectPointerType>(CFromTy) &&
9684       isa<PointerType>(CToTy)) {
9685       Qualifiers FromQs = CFromTy.getQualifiers();
9686       Qualifiers ToQs = CToTy.getQualifiers();
9687       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9688         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9689         << (unsigned) FnKind << FnDesc
9690         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9691         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9692         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9693         return;
9694       }
9695   }
9696 
9697   if (TakingCandidateAddress &&
9698       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9699     return;
9700 
9701   // Emit the generic diagnostic and, optionally, add the hints to it.
9702   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9703   FDiag << (unsigned) FnKind << FnDesc
9704     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9705     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9706     << (unsigned) (Cand->Fix.Kind);
9707 
9708   // If we can fix the conversion, suggest the FixIts.
9709   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9710        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9711     FDiag << *HI;
9712   S.Diag(Fn->getLocation(), FDiag);
9713 
9714   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9715 }
9716 
9717 /// Additional arity mismatch diagnosis specific to a function overload
9718 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9719 /// over a candidate in any candidate set.
9720 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9721                                unsigned NumArgs) {
9722   FunctionDecl *Fn = Cand->Function;
9723   unsigned MinParams = Fn->getMinRequiredArguments();
9724 
9725   // With invalid overloaded operators, it's possible that we think we
9726   // have an arity mismatch when in fact it looks like we have the
9727   // right number of arguments, because only overloaded operators have
9728   // the weird behavior of overloading member and non-member functions.
9729   // Just don't report anything.
9730   if (Fn->isInvalidDecl() &&
9731       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9732     return true;
9733 
9734   if (NumArgs < MinParams) {
9735     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9736            (Cand->FailureKind == ovl_fail_bad_deduction &&
9737             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9738   } else {
9739     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9740            (Cand->FailureKind == ovl_fail_bad_deduction &&
9741             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9742   }
9743 
9744   return false;
9745 }
9746 
9747 /// General arity mismatch diagnosis over a candidate in a candidate set.
9748 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9749                                   unsigned NumFormalArgs) {
9750   assert(isa<FunctionDecl>(D) &&
9751       "The templated declaration should at least be a function"
9752       " when diagnosing bad template argument deduction due to too many"
9753       " or too few arguments");
9754 
9755   FunctionDecl *Fn = cast<FunctionDecl>(D);
9756 
9757   // TODO: treat calls to a missing default constructor as a special case
9758   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9759   unsigned MinParams = Fn->getMinRequiredArguments();
9760 
9761   // at least / at most / exactly
9762   unsigned mode, modeCount;
9763   if (NumFormalArgs < MinParams) {
9764     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9765         FnTy->isTemplateVariadic())
9766       mode = 0; // "at least"
9767     else
9768       mode = 2; // "exactly"
9769     modeCount = MinParams;
9770   } else {
9771     if (MinParams != FnTy->getNumParams())
9772       mode = 1; // "at most"
9773     else
9774       mode = 2; // "exactly"
9775     modeCount = FnTy->getNumParams();
9776   }
9777 
9778   std::string Description;
9779   OverloadCandidateKind FnKind =
9780       ClassifyOverloadCandidate(S, Found, Fn, Description);
9781 
9782   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9783     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9784       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9785       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9786   else
9787     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9788       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9789       << mode << modeCount << NumFormalArgs;
9790   MaybeEmitInheritedConstructorNote(S, Found);
9791 }
9792 
9793 /// Arity mismatch diagnosis specific to a function overload candidate.
9794 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9795                                   unsigned NumFormalArgs) {
9796   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9797     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9798 }
9799 
9800 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9801   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9802     return TD;
9803   llvm_unreachable("Unsupported: Getting the described template declaration"
9804                    " for bad deduction diagnosis");
9805 }
9806 
9807 /// Diagnose a failed template-argument deduction.
9808 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9809                                  DeductionFailureInfo &DeductionFailure,
9810                                  unsigned NumArgs,
9811                                  bool TakingCandidateAddress) {
9812   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9813   NamedDecl *ParamD;
9814   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9815   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9816   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9817   switch (DeductionFailure.Result) {
9818   case Sema::TDK_Success:
9819     llvm_unreachable("TDK_success while diagnosing bad deduction");
9820 
9821   case Sema::TDK_Incomplete: {
9822     assert(ParamD && "no parameter found for incomplete deduction result");
9823     S.Diag(Templated->getLocation(),
9824            diag::note_ovl_candidate_incomplete_deduction)
9825         << ParamD->getDeclName();
9826     MaybeEmitInheritedConstructorNote(S, Found);
9827     return;
9828   }
9829 
9830   case Sema::TDK_Underqualified: {
9831     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9832     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9833 
9834     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9835 
9836     // Param will have been canonicalized, but it should just be a
9837     // qualified version of ParamD, so move the qualifiers to that.
9838     QualifierCollector Qs;
9839     Qs.strip(Param);
9840     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9841     assert(S.Context.hasSameType(Param, NonCanonParam));
9842 
9843     // Arg has also been canonicalized, but there's nothing we can do
9844     // about that.  It also doesn't matter as much, because it won't
9845     // have any template parameters in it (because deduction isn't
9846     // done on dependent types).
9847     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9848 
9849     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9850         << ParamD->getDeclName() << Arg << NonCanonParam;
9851     MaybeEmitInheritedConstructorNote(S, Found);
9852     return;
9853   }
9854 
9855   case Sema::TDK_Inconsistent: {
9856     assert(ParamD && "no parameter found for inconsistent deduction result");
9857     int which = 0;
9858     if (isa<TemplateTypeParmDecl>(ParamD))
9859       which = 0;
9860     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9861       // Deduction might have failed because we deduced arguments of two
9862       // different types for a non-type template parameter.
9863       // FIXME: Use a different TDK value for this.
9864       QualType T1 =
9865           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9866       QualType T2 =
9867           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9868       if (!S.Context.hasSameType(T1, T2)) {
9869         S.Diag(Templated->getLocation(),
9870                diag::note_ovl_candidate_inconsistent_deduction_types)
9871           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9872           << *DeductionFailure.getSecondArg() << T2;
9873         MaybeEmitInheritedConstructorNote(S, Found);
9874         return;
9875       }
9876 
9877       which = 1;
9878     } else {
9879       which = 2;
9880     }
9881 
9882     S.Diag(Templated->getLocation(),
9883            diag::note_ovl_candidate_inconsistent_deduction)
9884         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9885         << *DeductionFailure.getSecondArg();
9886     MaybeEmitInheritedConstructorNote(S, Found);
9887     return;
9888   }
9889 
9890   case Sema::TDK_InvalidExplicitArguments:
9891     assert(ParamD && "no parameter found for invalid explicit arguments");
9892     if (ParamD->getDeclName())
9893       S.Diag(Templated->getLocation(),
9894              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9895           << ParamD->getDeclName();
9896     else {
9897       int index = 0;
9898       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9899         index = TTP->getIndex();
9900       else if (NonTypeTemplateParmDecl *NTTP
9901                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9902         index = NTTP->getIndex();
9903       else
9904         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9905       S.Diag(Templated->getLocation(),
9906              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9907           << (index + 1);
9908     }
9909     MaybeEmitInheritedConstructorNote(S, Found);
9910     return;
9911 
9912   case Sema::TDK_TooManyArguments:
9913   case Sema::TDK_TooFewArguments:
9914     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9915     return;
9916 
9917   case Sema::TDK_InstantiationDepth:
9918     S.Diag(Templated->getLocation(),
9919            diag::note_ovl_candidate_instantiation_depth);
9920     MaybeEmitInheritedConstructorNote(S, Found);
9921     return;
9922 
9923   case Sema::TDK_SubstitutionFailure: {
9924     // Format the template argument list into the argument string.
9925     SmallString<128> TemplateArgString;
9926     if (TemplateArgumentList *Args =
9927             DeductionFailure.getTemplateArgumentList()) {
9928       TemplateArgString = " ";
9929       TemplateArgString += S.getTemplateArgumentBindingsText(
9930           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9931     }
9932 
9933     // If this candidate was disabled by enable_if, say so.
9934     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9935     if (PDiag && PDiag->second.getDiagID() ==
9936           diag::err_typename_nested_not_found_enable_if) {
9937       // FIXME: Use the source range of the condition, and the fully-qualified
9938       //        name of the enable_if template. These are both present in PDiag.
9939       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9940         << "'enable_if'" << TemplateArgString;
9941       return;
9942     }
9943 
9944     // We found a specific requirement that disabled the enable_if.
9945     if (PDiag && PDiag->second.getDiagID() ==
9946         diag::err_typename_nested_not_found_requirement) {
9947       S.Diag(Templated->getLocation(),
9948              diag::note_ovl_candidate_disabled_by_requirement)
9949         << PDiag->second.getStringArg(0) << TemplateArgString;
9950       return;
9951     }
9952 
9953     // Format the SFINAE diagnostic into the argument string.
9954     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9955     //        formatted message in another diagnostic.
9956     SmallString<128> SFINAEArgString;
9957     SourceRange R;
9958     if (PDiag) {
9959       SFINAEArgString = ": ";
9960       R = SourceRange(PDiag->first, PDiag->first);
9961       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9962     }
9963 
9964     S.Diag(Templated->getLocation(),
9965            diag::note_ovl_candidate_substitution_failure)
9966         << TemplateArgString << SFINAEArgString << R;
9967     MaybeEmitInheritedConstructorNote(S, Found);
9968     return;
9969   }
9970 
9971   case Sema::TDK_DeducedMismatch:
9972   case Sema::TDK_DeducedMismatchNested: {
9973     // Format the template argument list into the argument string.
9974     SmallString<128> TemplateArgString;
9975     if (TemplateArgumentList *Args =
9976             DeductionFailure.getTemplateArgumentList()) {
9977       TemplateArgString = " ";
9978       TemplateArgString += S.getTemplateArgumentBindingsText(
9979           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9980     }
9981 
9982     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9983         << (*DeductionFailure.getCallArgIndex() + 1)
9984         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9985         << TemplateArgString
9986         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9987     break;
9988   }
9989 
9990   case Sema::TDK_NonDeducedMismatch: {
9991     // FIXME: Provide a source location to indicate what we couldn't match.
9992     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9993     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9994     if (FirstTA.getKind() == TemplateArgument::Template &&
9995         SecondTA.getKind() == TemplateArgument::Template) {
9996       TemplateName FirstTN = FirstTA.getAsTemplate();
9997       TemplateName SecondTN = SecondTA.getAsTemplate();
9998       if (FirstTN.getKind() == TemplateName::Template &&
9999           SecondTN.getKind() == TemplateName::Template) {
10000         if (FirstTN.getAsTemplateDecl()->getName() ==
10001             SecondTN.getAsTemplateDecl()->getName()) {
10002           // FIXME: This fixes a bad diagnostic where both templates are named
10003           // the same.  This particular case is a bit difficult since:
10004           // 1) It is passed as a string to the diagnostic printer.
10005           // 2) The diagnostic printer only attempts to find a better
10006           //    name for types, not decls.
10007           // Ideally, this should folded into the diagnostic printer.
10008           S.Diag(Templated->getLocation(),
10009                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10010               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10011           return;
10012         }
10013       }
10014     }
10015 
10016     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10017         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10018       return;
10019 
10020     // FIXME: For generic lambda parameters, check if the function is a lambda
10021     // call operator, and if so, emit a prettier and more informative
10022     // diagnostic that mentions 'auto' and lambda in addition to
10023     // (or instead of?) the canonical template type parameters.
10024     S.Diag(Templated->getLocation(),
10025            diag::note_ovl_candidate_non_deduced_mismatch)
10026         << FirstTA << SecondTA;
10027     return;
10028   }
10029   // TODO: diagnose these individually, then kill off
10030   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10031   case Sema::TDK_MiscellaneousDeductionFailure:
10032     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10033     MaybeEmitInheritedConstructorNote(S, Found);
10034     return;
10035   case Sema::TDK_CUDATargetMismatch:
10036     S.Diag(Templated->getLocation(),
10037            diag::note_cuda_ovl_candidate_target_mismatch);
10038     return;
10039   }
10040 }
10041 
10042 /// Diagnose a failed template-argument deduction, for function calls.
10043 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10044                                  unsigned NumArgs,
10045                                  bool TakingCandidateAddress) {
10046   unsigned TDK = Cand->DeductionFailure.Result;
10047   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10048     if (CheckArityMismatch(S, Cand, NumArgs))
10049       return;
10050   }
10051   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10052                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10053 }
10054 
10055 /// CUDA: diagnose an invalid call across targets.
10056 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10057   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10058   FunctionDecl *Callee = Cand->Function;
10059 
10060   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10061                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10062 
10063   std::string FnDesc;
10064   OverloadCandidateKind FnKind =
10065       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10066 
10067   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10068       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10069 
10070   // This could be an implicit constructor for which we could not infer the
10071   // target due to a collsion. Diagnose that case.
10072   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10073   if (Meth != nullptr && Meth->isImplicit()) {
10074     CXXRecordDecl *ParentClass = Meth->getParent();
10075     Sema::CXXSpecialMember CSM;
10076 
10077     switch (FnKind) {
10078     default:
10079       return;
10080     case oc_implicit_default_constructor:
10081       CSM = Sema::CXXDefaultConstructor;
10082       break;
10083     case oc_implicit_copy_constructor:
10084       CSM = Sema::CXXCopyConstructor;
10085       break;
10086     case oc_implicit_move_constructor:
10087       CSM = Sema::CXXMoveConstructor;
10088       break;
10089     case oc_implicit_copy_assignment:
10090       CSM = Sema::CXXCopyAssignment;
10091       break;
10092     case oc_implicit_move_assignment:
10093       CSM = Sema::CXXMoveAssignment;
10094       break;
10095     };
10096 
10097     bool ConstRHS = false;
10098     if (Meth->getNumParams()) {
10099       if (const ReferenceType *RT =
10100               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10101         ConstRHS = RT->getPointeeType().isConstQualified();
10102       }
10103     }
10104 
10105     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10106                                               /* ConstRHS */ ConstRHS,
10107                                               /* Diagnose */ true);
10108   }
10109 }
10110 
10111 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10112   FunctionDecl *Callee = Cand->Function;
10113   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10114 
10115   S.Diag(Callee->getLocation(),
10116          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10117       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10118 }
10119 
10120 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10121   FunctionDecl *Callee = Cand->Function;
10122 
10123   S.Diag(Callee->getLocation(),
10124          diag::note_ovl_candidate_disabled_by_extension);
10125 }
10126 
10127 /// Generates a 'note' diagnostic for an overload candidate.  We've
10128 /// already generated a primary error at the call site.
10129 ///
10130 /// It really does need to be a single diagnostic with its caret
10131 /// pointed at the candidate declaration.  Yes, this creates some
10132 /// major challenges of technical writing.  Yes, this makes pointing
10133 /// out problems with specific arguments quite awkward.  It's still
10134 /// better than generating twenty screens of text for every failed
10135 /// overload.
10136 ///
10137 /// It would be great to be able to express per-candidate problems
10138 /// more richly for those diagnostic clients that cared, but we'd
10139 /// still have to be just as careful with the default diagnostics.
10140 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10141                                   unsigned NumArgs,
10142                                   bool TakingCandidateAddress) {
10143   FunctionDecl *Fn = Cand->Function;
10144 
10145   // Note deleted candidates, but only if they're viable.
10146   if (Cand->Viable) {
10147     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10148       std::string FnDesc;
10149       OverloadCandidateKind FnKind =
10150         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10151 
10152       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10153         << FnKind << FnDesc
10154         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10155       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10156       return;
10157     }
10158 
10159     // We don't really have anything else to say about viable candidates.
10160     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10161     return;
10162   }
10163 
10164   switch (Cand->FailureKind) {
10165   case ovl_fail_too_many_arguments:
10166   case ovl_fail_too_few_arguments:
10167     return DiagnoseArityMismatch(S, Cand, NumArgs);
10168 
10169   case ovl_fail_bad_deduction:
10170     return DiagnoseBadDeduction(S, Cand, NumArgs,
10171                                 TakingCandidateAddress);
10172 
10173   case ovl_fail_illegal_constructor: {
10174     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10175       << (Fn->getPrimaryTemplate() ? 1 : 0);
10176     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10177     return;
10178   }
10179 
10180   case ovl_fail_trivial_conversion:
10181   case ovl_fail_bad_final_conversion:
10182   case ovl_fail_final_conversion_not_exact:
10183     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10184 
10185   case ovl_fail_bad_conversion: {
10186     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10187     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10188       if (Cand->Conversions[I].isBad())
10189         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10190 
10191     // FIXME: this currently happens when we're called from SemaInit
10192     // when user-conversion overload fails.  Figure out how to handle
10193     // those conditions and diagnose them well.
10194     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10195   }
10196 
10197   case ovl_fail_bad_target:
10198     return DiagnoseBadTarget(S, Cand);
10199 
10200   case ovl_fail_enable_if:
10201     return DiagnoseFailedEnableIfAttr(S, Cand);
10202 
10203   case ovl_fail_ext_disabled:
10204     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10205 
10206   case ovl_fail_inhctor_slice:
10207     // It's generally not interesting to note copy/move constructors here.
10208     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10209       return;
10210     S.Diag(Fn->getLocation(),
10211            diag::note_ovl_candidate_inherited_constructor_slice)
10212       << (Fn->getPrimaryTemplate() ? 1 : 0)
10213       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10214     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10215     return;
10216 
10217   case ovl_fail_addr_not_available: {
10218     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10219     (void)Available;
10220     assert(!Available);
10221     break;
10222   }
10223   case ovl_non_default_multiversion_function:
10224     // Do nothing, these should simply be ignored.
10225     break;
10226   }
10227 }
10228 
10229 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10230   // Desugar the type of the surrogate down to a function type,
10231   // retaining as many typedefs as possible while still showing
10232   // the function type (and, therefore, its parameter types).
10233   QualType FnType = Cand->Surrogate->getConversionType();
10234   bool isLValueReference = false;
10235   bool isRValueReference = false;
10236   bool isPointer = false;
10237   if (const LValueReferenceType *FnTypeRef =
10238         FnType->getAs<LValueReferenceType>()) {
10239     FnType = FnTypeRef->getPointeeType();
10240     isLValueReference = true;
10241   } else if (const RValueReferenceType *FnTypeRef =
10242                FnType->getAs<RValueReferenceType>()) {
10243     FnType = FnTypeRef->getPointeeType();
10244     isRValueReference = true;
10245   }
10246   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10247     FnType = FnTypePtr->getPointeeType();
10248     isPointer = true;
10249   }
10250   // Desugar down to a function type.
10251   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10252   // Reconstruct the pointer/reference as appropriate.
10253   if (isPointer) FnType = S.Context.getPointerType(FnType);
10254   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10255   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10256 
10257   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10258     << FnType;
10259 }
10260 
10261 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10262                                          SourceLocation OpLoc,
10263                                          OverloadCandidate *Cand) {
10264   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10265   std::string TypeStr("operator");
10266   TypeStr += Opc;
10267   TypeStr += "(";
10268   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10269   if (Cand->Conversions.size() == 1) {
10270     TypeStr += ")";
10271     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10272   } else {
10273     TypeStr += ", ";
10274     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10275     TypeStr += ")";
10276     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10277   }
10278 }
10279 
10280 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10281                                          OverloadCandidate *Cand) {
10282   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10283     if (ICS.isBad()) break; // all meaningless after first invalid
10284     if (!ICS.isAmbiguous()) continue;
10285 
10286     ICS.DiagnoseAmbiguousConversion(
10287         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10288   }
10289 }
10290 
10291 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10292   if (Cand->Function)
10293     return Cand->Function->getLocation();
10294   if (Cand->IsSurrogate)
10295     return Cand->Surrogate->getLocation();
10296   return SourceLocation();
10297 }
10298 
10299 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10300   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10301   case Sema::TDK_Success:
10302   case Sema::TDK_NonDependentConversionFailure:
10303     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10304 
10305   case Sema::TDK_Invalid:
10306   case Sema::TDK_Incomplete:
10307     return 1;
10308 
10309   case Sema::TDK_Underqualified:
10310   case Sema::TDK_Inconsistent:
10311     return 2;
10312 
10313   case Sema::TDK_SubstitutionFailure:
10314   case Sema::TDK_DeducedMismatch:
10315   case Sema::TDK_DeducedMismatchNested:
10316   case Sema::TDK_NonDeducedMismatch:
10317   case Sema::TDK_MiscellaneousDeductionFailure:
10318   case Sema::TDK_CUDATargetMismatch:
10319     return 3;
10320 
10321   case Sema::TDK_InstantiationDepth:
10322     return 4;
10323 
10324   case Sema::TDK_InvalidExplicitArguments:
10325     return 5;
10326 
10327   case Sema::TDK_TooManyArguments:
10328   case Sema::TDK_TooFewArguments:
10329     return 6;
10330   }
10331   llvm_unreachable("Unhandled deduction result");
10332 }
10333 
10334 namespace {
10335 struct CompareOverloadCandidatesForDisplay {
10336   Sema &S;
10337   SourceLocation Loc;
10338   size_t NumArgs;
10339   OverloadCandidateSet::CandidateSetKind CSK;
10340 
10341   CompareOverloadCandidatesForDisplay(
10342       Sema &S, SourceLocation Loc, size_t NArgs,
10343       OverloadCandidateSet::CandidateSetKind CSK)
10344       : S(S), NumArgs(NArgs), CSK(CSK) {}
10345 
10346   bool operator()(const OverloadCandidate *L,
10347                   const OverloadCandidate *R) {
10348     // Fast-path this check.
10349     if (L == R) return false;
10350 
10351     // Order first by viability.
10352     if (L->Viable) {
10353       if (!R->Viable) return true;
10354 
10355       // TODO: introduce a tri-valued comparison for overload
10356       // candidates.  Would be more worthwhile if we had a sort
10357       // that could exploit it.
10358       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10359         return true;
10360       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10361         return false;
10362     } else if (R->Viable)
10363       return false;
10364 
10365     assert(L->Viable == R->Viable);
10366 
10367     // Criteria by which we can sort non-viable candidates:
10368     if (!L->Viable) {
10369       // 1. Arity mismatches come after other candidates.
10370       if (L->FailureKind == ovl_fail_too_many_arguments ||
10371           L->FailureKind == ovl_fail_too_few_arguments) {
10372         if (R->FailureKind == ovl_fail_too_many_arguments ||
10373             R->FailureKind == ovl_fail_too_few_arguments) {
10374           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10375           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10376           if (LDist == RDist) {
10377             if (L->FailureKind == R->FailureKind)
10378               // Sort non-surrogates before surrogates.
10379               return !L->IsSurrogate && R->IsSurrogate;
10380             // Sort candidates requiring fewer parameters than there were
10381             // arguments given after candidates requiring more parameters
10382             // than there were arguments given.
10383             return L->FailureKind == ovl_fail_too_many_arguments;
10384           }
10385           return LDist < RDist;
10386         }
10387         return false;
10388       }
10389       if (R->FailureKind == ovl_fail_too_many_arguments ||
10390           R->FailureKind == ovl_fail_too_few_arguments)
10391         return true;
10392 
10393       // 2. Bad conversions come first and are ordered by the number
10394       // of bad conversions and quality of good conversions.
10395       if (L->FailureKind == ovl_fail_bad_conversion) {
10396         if (R->FailureKind != ovl_fail_bad_conversion)
10397           return true;
10398 
10399         // The conversion that can be fixed with a smaller number of changes,
10400         // comes first.
10401         unsigned numLFixes = L->Fix.NumConversionsFixed;
10402         unsigned numRFixes = R->Fix.NumConversionsFixed;
10403         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10404         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10405         if (numLFixes != numRFixes) {
10406           return numLFixes < numRFixes;
10407         }
10408 
10409         // If there's any ordering between the defined conversions...
10410         // FIXME: this might not be transitive.
10411         assert(L->Conversions.size() == R->Conversions.size());
10412 
10413         int leftBetter = 0;
10414         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10415         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10416           switch (CompareImplicitConversionSequences(S, Loc,
10417                                                      L->Conversions[I],
10418                                                      R->Conversions[I])) {
10419           case ImplicitConversionSequence::Better:
10420             leftBetter++;
10421             break;
10422 
10423           case ImplicitConversionSequence::Worse:
10424             leftBetter--;
10425             break;
10426 
10427           case ImplicitConversionSequence::Indistinguishable:
10428             break;
10429           }
10430         }
10431         if (leftBetter > 0) return true;
10432         if (leftBetter < 0) return false;
10433 
10434       } else if (R->FailureKind == ovl_fail_bad_conversion)
10435         return false;
10436 
10437       if (L->FailureKind == ovl_fail_bad_deduction) {
10438         if (R->FailureKind != ovl_fail_bad_deduction)
10439           return true;
10440 
10441         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10442           return RankDeductionFailure(L->DeductionFailure)
10443                < RankDeductionFailure(R->DeductionFailure);
10444       } else if (R->FailureKind == ovl_fail_bad_deduction)
10445         return false;
10446 
10447       // TODO: others?
10448     }
10449 
10450     // Sort everything else by location.
10451     SourceLocation LLoc = GetLocationForCandidate(L);
10452     SourceLocation RLoc = GetLocationForCandidate(R);
10453 
10454     // Put candidates without locations (e.g. builtins) at the end.
10455     if (LLoc.isInvalid()) return false;
10456     if (RLoc.isInvalid()) return true;
10457 
10458     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10459   }
10460 };
10461 }
10462 
10463 /// CompleteNonViableCandidate - Normally, overload resolution only
10464 /// computes up to the first bad conversion. Produces the FixIt set if
10465 /// possible.
10466 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10467                                        ArrayRef<Expr *> Args) {
10468   assert(!Cand->Viable);
10469 
10470   // Don't do anything on failures other than bad conversion.
10471   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10472 
10473   // We only want the FixIts if all the arguments can be corrected.
10474   bool Unfixable = false;
10475   // Use a implicit copy initialization to check conversion fixes.
10476   Cand->Fix.setConversionChecker(TryCopyInitialization);
10477 
10478   // Attempt to fix the bad conversion.
10479   unsigned ConvCount = Cand->Conversions.size();
10480   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10481        ++ConvIdx) {
10482     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10483     if (Cand->Conversions[ConvIdx].isInitialized() &&
10484         Cand->Conversions[ConvIdx].isBad()) {
10485       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10486       break;
10487     }
10488   }
10489 
10490   // FIXME: this should probably be preserved from the overload
10491   // operation somehow.
10492   bool SuppressUserConversions = false;
10493 
10494   unsigned ConvIdx = 0;
10495   ArrayRef<QualType> ParamTypes;
10496 
10497   if (Cand->IsSurrogate) {
10498     QualType ConvType
10499       = Cand->Surrogate->getConversionType().getNonReferenceType();
10500     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10501       ConvType = ConvPtrType->getPointeeType();
10502     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10503     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10504     ConvIdx = 1;
10505   } else if (Cand->Function) {
10506     ParamTypes =
10507         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10508     if (isa<CXXMethodDecl>(Cand->Function) &&
10509         !isa<CXXConstructorDecl>(Cand->Function)) {
10510       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10511       ConvIdx = 1;
10512     }
10513   } else {
10514     // Builtin operator.
10515     assert(ConvCount <= 3);
10516     ParamTypes = Cand->BuiltinParamTypes;
10517   }
10518 
10519   // Fill in the rest of the conversions.
10520   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10521     if (Cand->Conversions[ConvIdx].isInitialized()) {
10522       // We've already checked this conversion.
10523     } else if (ArgIdx < ParamTypes.size()) {
10524       if (ParamTypes[ArgIdx]->isDependentType())
10525         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10526             Args[ArgIdx]->getType());
10527       else {
10528         Cand->Conversions[ConvIdx] =
10529             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10530                                   SuppressUserConversions,
10531                                   /*InOverloadResolution=*/true,
10532                                   /*AllowObjCWritebackConversion=*/
10533                                   S.getLangOpts().ObjCAutoRefCount);
10534         // Store the FixIt in the candidate if it exists.
10535         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10536           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10537       }
10538     } else
10539       Cand->Conversions[ConvIdx].setEllipsis();
10540   }
10541 }
10542 
10543 /// When overload resolution fails, prints diagnostic messages containing the
10544 /// candidates in the candidate set.
10545 void OverloadCandidateSet::NoteCandidates(
10546     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10547     StringRef Opc, SourceLocation OpLoc,
10548     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10549   // Sort the candidates by viability and position.  Sorting directly would
10550   // be prohibitive, so we make a set of pointers and sort those.
10551   SmallVector<OverloadCandidate*, 32> Cands;
10552   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10553   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10554     if (!Filter(*Cand))
10555       continue;
10556     if (Cand->Viable)
10557       Cands.push_back(Cand);
10558     else if (OCD == OCD_AllCandidates) {
10559       CompleteNonViableCandidate(S, Cand, Args);
10560       if (Cand->Function || Cand->IsSurrogate)
10561         Cands.push_back(Cand);
10562       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10563       // want to list every possible builtin candidate.
10564     }
10565   }
10566 
10567   std::stable_sort(Cands.begin(), Cands.end(),
10568             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10569 
10570   bool ReportedAmbiguousConversions = false;
10571 
10572   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10573   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10574   unsigned CandsShown = 0;
10575   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10576     OverloadCandidate *Cand = *I;
10577 
10578     // Set an arbitrary limit on the number of candidate functions we'll spam
10579     // the user with.  FIXME: This limit should depend on details of the
10580     // candidate list.
10581     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10582       break;
10583     }
10584     ++CandsShown;
10585 
10586     if (Cand->Function)
10587       NoteFunctionCandidate(S, Cand, Args.size(),
10588                             /*TakingCandidateAddress=*/false);
10589     else if (Cand->IsSurrogate)
10590       NoteSurrogateCandidate(S, Cand);
10591     else {
10592       assert(Cand->Viable &&
10593              "Non-viable built-in candidates are not added to Cands.");
10594       // Generally we only see ambiguities including viable builtin
10595       // operators if overload resolution got screwed up by an
10596       // ambiguous user-defined conversion.
10597       //
10598       // FIXME: It's quite possible for different conversions to see
10599       // different ambiguities, though.
10600       if (!ReportedAmbiguousConversions) {
10601         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10602         ReportedAmbiguousConversions = true;
10603       }
10604 
10605       // If this is a viable builtin, print it.
10606       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10607     }
10608   }
10609 
10610   if (I != E)
10611     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10612 }
10613 
10614 static SourceLocation
10615 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10616   return Cand->Specialization ? Cand->Specialization->getLocation()
10617                               : SourceLocation();
10618 }
10619 
10620 namespace {
10621 struct CompareTemplateSpecCandidatesForDisplay {
10622   Sema &S;
10623   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10624 
10625   bool operator()(const TemplateSpecCandidate *L,
10626                   const TemplateSpecCandidate *R) {
10627     // Fast-path this check.
10628     if (L == R)
10629       return false;
10630 
10631     // Assuming that both candidates are not matches...
10632 
10633     // Sort by the ranking of deduction failures.
10634     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10635       return RankDeductionFailure(L->DeductionFailure) <
10636              RankDeductionFailure(R->DeductionFailure);
10637 
10638     // Sort everything else by location.
10639     SourceLocation LLoc = GetLocationForCandidate(L);
10640     SourceLocation RLoc = GetLocationForCandidate(R);
10641 
10642     // Put candidates without locations (e.g. builtins) at the end.
10643     if (LLoc.isInvalid())
10644       return false;
10645     if (RLoc.isInvalid())
10646       return true;
10647 
10648     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10649   }
10650 };
10651 }
10652 
10653 /// Diagnose a template argument deduction failure.
10654 /// We are treating these failures as overload failures due to bad
10655 /// deductions.
10656 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10657                                                  bool ForTakingAddress) {
10658   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10659                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10660 }
10661 
10662 void TemplateSpecCandidateSet::destroyCandidates() {
10663   for (iterator i = begin(), e = end(); i != e; ++i) {
10664     i->DeductionFailure.Destroy();
10665   }
10666 }
10667 
10668 void TemplateSpecCandidateSet::clear() {
10669   destroyCandidates();
10670   Candidates.clear();
10671 }
10672 
10673 /// NoteCandidates - When no template specialization match is found, prints
10674 /// diagnostic messages containing the non-matching specializations that form
10675 /// the candidate set.
10676 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10677 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10678 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10679   // Sort the candidates by position (assuming no candidate is a match).
10680   // Sorting directly would be prohibitive, so we make a set of pointers
10681   // and sort those.
10682   SmallVector<TemplateSpecCandidate *, 32> Cands;
10683   Cands.reserve(size());
10684   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10685     if (Cand->Specialization)
10686       Cands.push_back(Cand);
10687     // Otherwise, this is a non-matching builtin candidate.  We do not,
10688     // in general, want to list every possible builtin candidate.
10689   }
10690 
10691   llvm::sort(Cands.begin(), Cands.end(),
10692              CompareTemplateSpecCandidatesForDisplay(S));
10693 
10694   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10695   // for generalization purposes (?).
10696   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10697 
10698   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10699   unsigned CandsShown = 0;
10700   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10701     TemplateSpecCandidate *Cand = *I;
10702 
10703     // Set an arbitrary limit on the number of candidates we'll spam
10704     // the user with.  FIXME: This limit should depend on details of the
10705     // candidate list.
10706     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10707       break;
10708     ++CandsShown;
10709 
10710     assert(Cand->Specialization &&
10711            "Non-matching built-in candidates are not added to Cands.");
10712     Cand->NoteDeductionFailure(S, ForTakingAddress);
10713   }
10714 
10715   if (I != E)
10716     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10717 }
10718 
10719 // [PossiblyAFunctionType]  -->   [Return]
10720 // NonFunctionType --> NonFunctionType
10721 // R (A) --> R(A)
10722 // R (*)(A) --> R (A)
10723 // R (&)(A) --> R (A)
10724 // R (S::*)(A) --> R (A)
10725 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10726   QualType Ret = PossiblyAFunctionType;
10727   if (const PointerType *ToTypePtr =
10728     PossiblyAFunctionType->getAs<PointerType>())
10729     Ret = ToTypePtr->getPointeeType();
10730   else if (const ReferenceType *ToTypeRef =
10731     PossiblyAFunctionType->getAs<ReferenceType>())
10732     Ret = ToTypeRef->getPointeeType();
10733   else if (const MemberPointerType *MemTypePtr =
10734     PossiblyAFunctionType->getAs<MemberPointerType>())
10735     Ret = MemTypePtr->getPointeeType();
10736   Ret =
10737     Context.getCanonicalType(Ret).getUnqualifiedType();
10738   return Ret;
10739 }
10740 
10741 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10742                                  bool Complain = true) {
10743   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10744       S.DeduceReturnType(FD, Loc, Complain))
10745     return true;
10746 
10747   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10748   if (S.getLangOpts().CPlusPlus17 &&
10749       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10750       !S.ResolveExceptionSpec(Loc, FPT))
10751     return true;
10752 
10753   return false;
10754 }
10755 
10756 namespace {
10757 // A helper class to help with address of function resolution
10758 // - allows us to avoid passing around all those ugly parameters
10759 class AddressOfFunctionResolver {
10760   Sema& S;
10761   Expr* SourceExpr;
10762   const QualType& TargetType;
10763   QualType TargetFunctionType; // Extracted function type from target type
10764 
10765   bool Complain;
10766   //DeclAccessPair& ResultFunctionAccessPair;
10767   ASTContext& Context;
10768 
10769   bool TargetTypeIsNonStaticMemberFunction;
10770   bool FoundNonTemplateFunction;
10771   bool StaticMemberFunctionFromBoundPointer;
10772   bool HasComplained;
10773 
10774   OverloadExpr::FindResult OvlExprInfo;
10775   OverloadExpr *OvlExpr;
10776   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10777   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10778   TemplateSpecCandidateSet FailedCandidates;
10779 
10780 public:
10781   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10782                             const QualType &TargetType, bool Complain)
10783       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10784         Complain(Complain), Context(S.getASTContext()),
10785         TargetTypeIsNonStaticMemberFunction(
10786             !!TargetType->getAs<MemberPointerType>()),
10787         FoundNonTemplateFunction(false),
10788         StaticMemberFunctionFromBoundPointer(false),
10789         HasComplained(false),
10790         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10791         OvlExpr(OvlExprInfo.Expression),
10792         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10793     ExtractUnqualifiedFunctionTypeFromTargetType();
10794 
10795     if (TargetFunctionType->isFunctionType()) {
10796       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10797         if (!UME->isImplicitAccess() &&
10798             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10799           StaticMemberFunctionFromBoundPointer = true;
10800     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10801       DeclAccessPair dap;
10802       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10803               OvlExpr, false, &dap)) {
10804         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10805           if (!Method->isStatic()) {
10806             // If the target type is a non-function type and the function found
10807             // is a non-static member function, pretend as if that was the
10808             // target, it's the only possible type to end up with.
10809             TargetTypeIsNonStaticMemberFunction = true;
10810 
10811             // And skip adding the function if its not in the proper form.
10812             // We'll diagnose this due to an empty set of functions.
10813             if (!OvlExprInfo.HasFormOfMemberPointer)
10814               return;
10815           }
10816 
10817         Matches.push_back(std::make_pair(dap, Fn));
10818       }
10819       return;
10820     }
10821 
10822     if (OvlExpr->hasExplicitTemplateArgs())
10823       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10824 
10825     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10826       // C++ [over.over]p4:
10827       //   If more than one function is selected, [...]
10828       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10829         if (FoundNonTemplateFunction)
10830           EliminateAllTemplateMatches();
10831         else
10832           EliminateAllExceptMostSpecializedTemplate();
10833       }
10834     }
10835 
10836     if (S.getLangOpts().CUDA && Matches.size() > 1)
10837       EliminateSuboptimalCudaMatches();
10838   }
10839 
10840   bool hasComplained() const { return HasComplained; }
10841 
10842 private:
10843   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10844     QualType Discard;
10845     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10846            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10847   }
10848 
10849   /// \return true if A is considered a better overload candidate for the
10850   /// desired type than B.
10851   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10852     // If A doesn't have exactly the correct type, we don't want to classify it
10853     // as "better" than anything else. This way, the user is required to
10854     // disambiguate for us if there are multiple candidates and no exact match.
10855     return candidateHasExactlyCorrectType(A) &&
10856            (!candidateHasExactlyCorrectType(B) ||
10857             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10858   }
10859 
10860   /// \return true if we were able to eliminate all but one overload candidate,
10861   /// false otherwise.
10862   bool eliminiateSuboptimalOverloadCandidates() {
10863     // Same algorithm as overload resolution -- one pass to pick the "best",
10864     // another pass to be sure that nothing is better than the best.
10865     auto Best = Matches.begin();
10866     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10867       if (isBetterCandidate(I->second, Best->second))
10868         Best = I;
10869 
10870     const FunctionDecl *BestFn = Best->second;
10871     auto IsBestOrInferiorToBest = [this, BestFn](
10872         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10873       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10874     };
10875 
10876     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10877     // option, so we can potentially give the user a better error
10878     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10879       return false;
10880     Matches[0] = *Best;
10881     Matches.resize(1);
10882     return true;
10883   }
10884 
10885   bool isTargetTypeAFunction() const {
10886     return TargetFunctionType->isFunctionType();
10887   }
10888 
10889   // [ToType]     [Return]
10890 
10891   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10892   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10893   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10894   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10895     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10896   }
10897 
10898   // return true if any matching specializations were found
10899   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10900                                    const DeclAccessPair& CurAccessFunPair) {
10901     if (CXXMethodDecl *Method
10902               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10903       // Skip non-static function templates when converting to pointer, and
10904       // static when converting to member pointer.
10905       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10906         return false;
10907     }
10908     else if (TargetTypeIsNonStaticMemberFunction)
10909       return false;
10910 
10911     // C++ [over.over]p2:
10912     //   If the name is a function template, template argument deduction is
10913     //   done (14.8.2.2), and if the argument deduction succeeds, the
10914     //   resulting template argument list is used to generate a single
10915     //   function template specialization, which is added to the set of
10916     //   overloaded functions considered.
10917     FunctionDecl *Specialization = nullptr;
10918     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10919     if (Sema::TemplateDeductionResult Result
10920           = S.DeduceTemplateArguments(FunctionTemplate,
10921                                       &OvlExplicitTemplateArgs,
10922                                       TargetFunctionType, Specialization,
10923                                       Info, /*IsAddressOfFunction*/true)) {
10924       // Make a note of the failed deduction for diagnostics.
10925       FailedCandidates.addCandidate()
10926           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10927                MakeDeductionFailureInfo(Context, Result, Info));
10928       return false;
10929     }
10930 
10931     // Template argument deduction ensures that we have an exact match or
10932     // compatible pointer-to-function arguments that would be adjusted by ICS.
10933     // This function template specicalization works.
10934     assert(S.isSameOrCompatibleFunctionType(
10935               Context.getCanonicalType(Specialization->getType()),
10936               Context.getCanonicalType(TargetFunctionType)));
10937 
10938     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10939       return false;
10940 
10941     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10942     return true;
10943   }
10944 
10945   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10946                                       const DeclAccessPair& CurAccessFunPair) {
10947     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10948       // Skip non-static functions when converting to pointer, and static
10949       // when converting to member pointer.
10950       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10951         return false;
10952     }
10953     else if (TargetTypeIsNonStaticMemberFunction)
10954       return false;
10955 
10956     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10957       if (S.getLangOpts().CUDA)
10958         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10959           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10960             return false;
10961       if (FunDecl->isMultiVersion()) {
10962         const auto *TA = FunDecl->getAttr<TargetAttr>();
10963         assert(TA && "Multiversioned functions require a target attribute");
10964         if (!TA->isDefaultVersion())
10965           return false;
10966       }
10967 
10968       // If any candidate has a placeholder return type, trigger its deduction
10969       // now.
10970       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10971                                Complain)) {
10972         HasComplained |= Complain;
10973         return false;
10974       }
10975 
10976       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10977         return false;
10978 
10979       // If we're in C, we need to support types that aren't exactly identical.
10980       if (!S.getLangOpts().CPlusPlus ||
10981           candidateHasExactlyCorrectType(FunDecl)) {
10982         Matches.push_back(std::make_pair(
10983             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10984         FoundNonTemplateFunction = true;
10985         return true;
10986       }
10987     }
10988 
10989     return false;
10990   }
10991 
10992   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10993     bool Ret = false;
10994 
10995     // If the overload expression doesn't have the form of a pointer to
10996     // member, don't try to convert it to a pointer-to-member type.
10997     if (IsInvalidFormOfPointerToMemberFunction())
10998       return false;
10999 
11000     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11001                                E = OvlExpr->decls_end();
11002          I != E; ++I) {
11003       // Look through any using declarations to find the underlying function.
11004       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11005 
11006       // C++ [over.over]p3:
11007       //   Non-member functions and static member functions match
11008       //   targets of type "pointer-to-function" or "reference-to-function."
11009       //   Nonstatic member functions match targets of
11010       //   type "pointer-to-member-function."
11011       // Note that according to DR 247, the containing class does not matter.
11012       if (FunctionTemplateDecl *FunctionTemplate
11013                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11014         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11015           Ret = true;
11016       }
11017       // If we have explicit template arguments supplied, skip non-templates.
11018       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11019                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11020         Ret = true;
11021     }
11022     assert(Ret || Matches.empty());
11023     return Ret;
11024   }
11025 
11026   void EliminateAllExceptMostSpecializedTemplate() {
11027     //   [...] and any given function template specialization F1 is
11028     //   eliminated if the set contains a second function template
11029     //   specialization whose function template is more specialized
11030     //   than the function template of F1 according to the partial
11031     //   ordering rules of 14.5.5.2.
11032 
11033     // The algorithm specified above is quadratic. We instead use a
11034     // two-pass algorithm (similar to the one used to identify the
11035     // best viable function in an overload set) that identifies the
11036     // best function template (if it exists).
11037 
11038     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11039     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11040       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11041 
11042     // TODO: It looks like FailedCandidates does not serve much purpose
11043     // here, since the no_viable diagnostic has index 0.
11044     UnresolvedSetIterator Result = S.getMostSpecialized(
11045         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11046         SourceExpr->getLocStart(), S.PDiag(),
11047         S.PDiag(diag::err_addr_ovl_ambiguous)
11048           << Matches[0].second->getDeclName(),
11049         S.PDiag(diag::note_ovl_candidate)
11050           << (unsigned)oc_function_template,
11051         Complain, TargetFunctionType);
11052 
11053     if (Result != MatchesCopy.end()) {
11054       // Make it the first and only element
11055       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11056       Matches[0].second = cast<FunctionDecl>(*Result);
11057       Matches.resize(1);
11058     } else
11059       HasComplained |= Complain;
11060   }
11061 
11062   void EliminateAllTemplateMatches() {
11063     //   [...] any function template specializations in the set are
11064     //   eliminated if the set also contains a non-template function, [...]
11065     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11066       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11067         ++I;
11068       else {
11069         Matches[I] = Matches[--N];
11070         Matches.resize(N);
11071       }
11072     }
11073   }
11074 
11075   void EliminateSuboptimalCudaMatches() {
11076     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11077   }
11078 
11079 public:
11080   void ComplainNoMatchesFound() const {
11081     assert(Matches.empty());
11082     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11083         << OvlExpr->getName() << TargetFunctionType
11084         << OvlExpr->getSourceRange();
11085     if (FailedCandidates.empty())
11086       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11087                                   /*TakingAddress=*/true);
11088     else {
11089       // We have some deduction failure messages. Use them to diagnose
11090       // the function templates, and diagnose the non-template candidates
11091       // normally.
11092       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11093                                  IEnd = OvlExpr->decls_end();
11094            I != IEnd; ++I)
11095         if (FunctionDecl *Fun =
11096                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11097           if (!functionHasPassObjectSizeParams(Fun))
11098             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11099                                     /*TakingAddress=*/true);
11100       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11101     }
11102   }
11103 
11104   bool IsInvalidFormOfPointerToMemberFunction() const {
11105     return TargetTypeIsNonStaticMemberFunction &&
11106       !OvlExprInfo.HasFormOfMemberPointer;
11107   }
11108 
11109   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11110       // TODO: Should we condition this on whether any functions might
11111       // have matched, or is it more appropriate to do that in callers?
11112       // TODO: a fixit wouldn't hurt.
11113       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11114         << TargetType << OvlExpr->getSourceRange();
11115   }
11116 
11117   bool IsStaticMemberFunctionFromBoundPointer() const {
11118     return StaticMemberFunctionFromBoundPointer;
11119   }
11120 
11121   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11122     S.Diag(OvlExpr->getLocStart(),
11123            diag::err_invalid_form_pointer_member_function)
11124       << OvlExpr->getSourceRange();
11125   }
11126 
11127   void ComplainOfInvalidConversion() const {
11128     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11129       << OvlExpr->getName() << TargetType;
11130   }
11131 
11132   void ComplainMultipleMatchesFound() const {
11133     assert(Matches.size() > 1);
11134     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11135       << OvlExpr->getName()
11136       << OvlExpr->getSourceRange();
11137     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11138                                 /*TakingAddress=*/true);
11139   }
11140 
11141   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11142 
11143   int getNumMatches() const { return Matches.size(); }
11144 
11145   FunctionDecl* getMatchingFunctionDecl() const {
11146     if (Matches.size() != 1) return nullptr;
11147     return Matches[0].second;
11148   }
11149 
11150   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11151     if (Matches.size() != 1) return nullptr;
11152     return &Matches[0].first;
11153   }
11154 };
11155 }
11156 
11157 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11158 /// an overloaded function (C++ [over.over]), where @p From is an
11159 /// expression with overloaded function type and @p ToType is the type
11160 /// we're trying to resolve to. For example:
11161 ///
11162 /// @code
11163 /// int f(double);
11164 /// int f(int);
11165 ///
11166 /// int (*pfd)(double) = f; // selects f(double)
11167 /// @endcode
11168 ///
11169 /// This routine returns the resulting FunctionDecl if it could be
11170 /// resolved, and NULL otherwise. When @p Complain is true, this
11171 /// routine will emit diagnostics if there is an error.
11172 FunctionDecl *
11173 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11174                                          QualType TargetType,
11175                                          bool Complain,
11176                                          DeclAccessPair &FoundResult,
11177                                          bool *pHadMultipleCandidates) {
11178   assert(AddressOfExpr->getType() == Context.OverloadTy);
11179 
11180   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11181                                      Complain);
11182   int NumMatches = Resolver.getNumMatches();
11183   FunctionDecl *Fn = nullptr;
11184   bool ShouldComplain = Complain && !Resolver.hasComplained();
11185   if (NumMatches == 0 && ShouldComplain) {
11186     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11187       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11188     else
11189       Resolver.ComplainNoMatchesFound();
11190   }
11191   else if (NumMatches > 1 && ShouldComplain)
11192     Resolver.ComplainMultipleMatchesFound();
11193   else if (NumMatches == 1) {
11194     Fn = Resolver.getMatchingFunctionDecl();
11195     assert(Fn);
11196     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11197       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11198     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11199     if (Complain) {
11200       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11201         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11202       else
11203         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11204     }
11205   }
11206 
11207   if (pHadMultipleCandidates)
11208     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11209   return Fn;
11210 }
11211 
11212 /// \brief Given an expression that refers to an overloaded function, try to
11213 /// resolve that function to a single function that can have its address taken.
11214 /// This will modify `Pair` iff it returns non-null.
11215 ///
11216 /// This routine can only realistically succeed if all but one candidates in the
11217 /// overload set for SrcExpr cannot have their addresses taken.
11218 FunctionDecl *
11219 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11220                                                   DeclAccessPair &Pair) {
11221   OverloadExpr::FindResult R = OverloadExpr::find(E);
11222   OverloadExpr *Ovl = R.Expression;
11223   FunctionDecl *Result = nullptr;
11224   DeclAccessPair DAP;
11225   // Don't use the AddressOfResolver because we're specifically looking for
11226   // cases where we have one overload candidate that lacks
11227   // enable_if/pass_object_size/...
11228   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11229     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11230     if (!FD)
11231       return nullptr;
11232 
11233     if (!checkAddressOfFunctionIsAvailable(FD))
11234       continue;
11235 
11236     // We have more than one result; quit.
11237     if (Result)
11238       return nullptr;
11239     DAP = I.getPair();
11240     Result = FD;
11241   }
11242 
11243   if (Result)
11244     Pair = DAP;
11245   return Result;
11246 }
11247 
11248 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11249 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11250 /// will perform access checks, diagnose the use of the resultant decl, and, if
11251 /// requested, potentially perform a function-to-pointer decay.
11252 ///
11253 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11254 /// Otherwise, returns true. This may emit diagnostics and return true.
11255 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11256     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11257   Expr *E = SrcExpr.get();
11258   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11259 
11260   DeclAccessPair DAP;
11261   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11262   if (!Found)
11263     return false;
11264 
11265   // Emitting multiple diagnostics for a function that is both inaccessible and
11266   // unavailable is consistent with our behavior elsewhere. So, always check
11267   // for both.
11268   DiagnoseUseOfDecl(Found, E->getExprLoc());
11269   CheckAddressOfMemberAccess(E, DAP);
11270   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11271   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11272     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11273   else
11274     SrcExpr = Fixed;
11275   return true;
11276 }
11277 
11278 /// \brief Given an expression that refers to an overloaded function, try to
11279 /// resolve that overloaded function expression down to a single function.
11280 ///
11281 /// This routine can only resolve template-ids that refer to a single function
11282 /// template, where that template-id refers to a single template whose template
11283 /// arguments are either provided by the template-id or have defaults,
11284 /// as described in C++0x [temp.arg.explicit]p3.
11285 ///
11286 /// If no template-ids are found, no diagnostics are emitted and NULL is
11287 /// returned.
11288 FunctionDecl *
11289 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11290                                                   bool Complain,
11291                                                   DeclAccessPair *FoundResult) {
11292   // C++ [over.over]p1:
11293   //   [...] [Note: any redundant set of parentheses surrounding the
11294   //   overloaded function name is ignored (5.1). ]
11295   // C++ [over.over]p1:
11296   //   [...] The overloaded function name can be preceded by the &
11297   //   operator.
11298 
11299   // If we didn't actually find any template-ids, we're done.
11300   if (!ovl->hasExplicitTemplateArgs())
11301     return nullptr;
11302 
11303   TemplateArgumentListInfo ExplicitTemplateArgs;
11304   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11305   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11306 
11307   // Look through all of the overloaded functions, searching for one
11308   // whose type matches exactly.
11309   FunctionDecl *Matched = nullptr;
11310   for (UnresolvedSetIterator I = ovl->decls_begin(),
11311          E = ovl->decls_end(); I != E; ++I) {
11312     // C++0x [temp.arg.explicit]p3:
11313     //   [...] In contexts where deduction is done and fails, or in contexts
11314     //   where deduction is not done, if a template argument list is
11315     //   specified and it, along with any default template arguments,
11316     //   identifies a single function template specialization, then the
11317     //   template-id is an lvalue for the function template specialization.
11318     FunctionTemplateDecl *FunctionTemplate
11319       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11320 
11321     // C++ [over.over]p2:
11322     //   If the name is a function template, template argument deduction is
11323     //   done (14.8.2.2), and if the argument deduction succeeds, the
11324     //   resulting template argument list is used to generate a single
11325     //   function template specialization, which is added to the set of
11326     //   overloaded functions considered.
11327     FunctionDecl *Specialization = nullptr;
11328     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11329     if (TemplateDeductionResult Result
11330           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11331                                     Specialization, Info,
11332                                     /*IsAddressOfFunction*/true)) {
11333       // Make a note of the failed deduction for diagnostics.
11334       // TODO: Actually use the failed-deduction info?
11335       FailedCandidates.addCandidate()
11336           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11337                MakeDeductionFailureInfo(Context, Result, Info));
11338       continue;
11339     }
11340 
11341     assert(Specialization && "no specialization and no error?");
11342 
11343     // Multiple matches; we can't resolve to a single declaration.
11344     if (Matched) {
11345       if (Complain) {
11346         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11347           << ovl->getName();
11348         NoteAllOverloadCandidates(ovl);
11349       }
11350       return nullptr;
11351     }
11352 
11353     Matched = Specialization;
11354     if (FoundResult) *FoundResult = I.getPair();
11355   }
11356 
11357   if (Matched &&
11358       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11359     return nullptr;
11360 
11361   return Matched;
11362 }
11363 
11364 // Resolve and fix an overloaded expression that can be resolved
11365 // because it identifies a single function template specialization.
11366 //
11367 // Last three arguments should only be supplied if Complain = true
11368 //
11369 // Return true if it was logically possible to so resolve the
11370 // expression, regardless of whether or not it succeeded.  Always
11371 // returns true if 'complain' is set.
11372 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11373                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11374                       bool complain, SourceRange OpRangeForComplaining,
11375                                            QualType DestTypeForComplaining,
11376                                             unsigned DiagIDForComplaining) {
11377   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11378 
11379   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11380 
11381   DeclAccessPair found;
11382   ExprResult SingleFunctionExpression;
11383   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11384                            ovl.Expression, /*complain*/ false, &found)) {
11385     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11386       SrcExpr = ExprError();
11387       return true;
11388     }
11389 
11390     // It is only correct to resolve to an instance method if we're
11391     // resolving a form that's permitted to be a pointer to member.
11392     // Otherwise we'll end up making a bound member expression, which
11393     // is illegal in all the contexts we resolve like this.
11394     if (!ovl.HasFormOfMemberPointer &&
11395         isa<CXXMethodDecl>(fn) &&
11396         cast<CXXMethodDecl>(fn)->isInstance()) {
11397       if (!complain) return false;
11398 
11399       Diag(ovl.Expression->getExprLoc(),
11400            diag::err_bound_member_function)
11401         << 0 << ovl.Expression->getSourceRange();
11402 
11403       // TODO: I believe we only end up here if there's a mix of
11404       // static and non-static candidates (otherwise the expression
11405       // would have 'bound member' type, not 'overload' type).
11406       // Ideally we would note which candidate was chosen and why
11407       // the static candidates were rejected.
11408       SrcExpr = ExprError();
11409       return true;
11410     }
11411 
11412     // Fix the expression to refer to 'fn'.
11413     SingleFunctionExpression =
11414         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11415 
11416     // If desired, do function-to-pointer decay.
11417     if (doFunctionPointerConverion) {
11418       SingleFunctionExpression =
11419         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11420       if (SingleFunctionExpression.isInvalid()) {
11421         SrcExpr = ExprError();
11422         return true;
11423       }
11424     }
11425   }
11426 
11427   if (!SingleFunctionExpression.isUsable()) {
11428     if (complain) {
11429       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11430         << ovl.Expression->getName()
11431         << DestTypeForComplaining
11432         << OpRangeForComplaining
11433         << ovl.Expression->getQualifierLoc().getSourceRange();
11434       NoteAllOverloadCandidates(SrcExpr.get());
11435 
11436       SrcExpr = ExprError();
11437       return true;
11438     }
11439 
11440     return false;
11441   }
11442 
11443   SrcExpr = SingleFunctionExpression;
11444   return true;
11445 }
11446 
11447 /// \brief Add a single candidate to the overload set.
11448 static void AddOverloadedCallCandidate(Sema &S,
11449                                        DeclAccessPair FoundDecl,
11450                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11451                                        ArrayRef<Expr *> Args,
11452                                        OverloadCandidateSet &CandidateSet,
11453                                        bool PartialOverloading,
11454                                        bool KnownValid) {
11455   NamedDecl *Callee = FoundDecl.getDecl();
11456   if (isa<UsingShadowDecl>(Callee))
11457     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11458 
11459   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11460     if (ExplicitTemplateArgs) {
11461       assert(!KnownValid && "Explicit template arguments?");
11462       return;
11463     }
11464     // Prevent ill-formed function decls to be added as overload candidates.
11465     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11466       return;
11467 
11468     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11469                            /*SuppressUsedConversions=*/false,
11470                            PartialOverloading);
11471     return;
11472   }
11473 
11474   if (FunctionTemplateDecl *FuncTemplate
11475       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11476     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11477                                    ExplicitTemplateArgs, Args, CandidateSet,
11478                                    /*SuppressUsedConversions=*/false,
11479                                    PartialOverloading);
11480     return;
11481   }
11482 
11483   assert(!KnownValid && "unhandled case in overloaded call candidate");
11484 }
11485 
11486 /// \brief Add the overload candidates named by callee and/or found by argument
11487 /// dependent lookup to the given overload set.
11488 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11489                                        ArrayRef<Expr *> Args,
11490                                        OverloadCandidateSet &CandidateSet,
11491                                        bool PartialOverloading) {
11492 
11493 #ifndef NDEBUG
11494   // Verify that ArgumentDependentLookup is consistent with the rules
11495   // in C++0x [basic.lookup.argdep]p3:
11496   //
11497   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11498   //   and let Y be the lookup set produced by argument dependent
11499   //   lookup (defined as follows). If X contains
11500   //
11501   //     -- a declaration of a class member, or
11502   //
11503   //     -- a block-scope function declaration that is not a
11504   //        using-declaration, or
11505   //
11506   //     -- a declaration that is neither a function or a function
11507   //        template
11508   //
11509   //   then Y is empty.
11510 
11511   if (ULE->requiresADL()) {
11512     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11513            E = ULE->decls_end(); I != E; ++I) {
11514       assert(!(*I)->getDeclContext()->isRecord());
11515       assert(isa<UsingShadowDecl>(*I) ||
11516              !(*I)->getDeclContext()->isFunctionOrMethod());
11517       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11518     }
11519   }
11520 #endif
11521 
11522   // It would be nice to avoid this copy.
11523   TemplateArgumentListInfo TABuffer;
11524   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11525   if (ULE->hasExplicitTemplateArgs()) {
11526     ULE->copyTemplateArgumentsInto(TABuffer);
11527     ExplicitTemplateArgs = &TABuffer;
11528   }
11529 
11530   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11531          E = ULE->decls_end(); I != E; ++I)
11532     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11533                                CandidateSet, PartialOverloading,
11534                                /*KnownValid*/ true);
11535 
11536   if (ULE->requiresADL())
11537     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11538                                          Args, ExplicitTemplateArgs,
11539                                          CandidateSet, PartialOverloading);
11540 }
11541 
11542 /// Determine whether a declaration with the specified name could be moved into
11543 /// a different namespace.
11544 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11545   switch (Name.getCXXOverloadedOperator()) {
11546   case OO_New: case OO_Array_New:
11547   case OO_Delete: case OO_Array_Delete:
11548     return false;
11549 
11550   default:
11551     return true;
11552   }
11553 }
11554 
11555 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11556 /// template, where the non-dependent name was declared after the template
11557 /// was defined. This is common in code written for a compilers which do not
11558 /// correctly implement two-stage name lookup.
11559 ///
11560 /// Returns true if a viable candidate was found and a diagnostic was issued.
11561 static bool
11562 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11563                        const CXXScopeSpec &SS, LookupResult &R,
11564                        OverloadCandidateSet::CandidateSetKind CSK,
11565                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11566                        ArrayRef<Expr *> Args,
11567                        bool *DoDiagnoseEmptyLookup = nullptr) {
11568   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11569     return false;
11570 
11571   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11572     if (DC->isTransparentContext())
11573       continue;
11574 
11575     SemaRef.LookupQualifiedName(R, DC);
11576 
11577     if (!R.empty()) {
11578       R.suppressDiagnostics();
11579 
11580       if (isa<CXXRecordDecl>(DC)) {
11581         // Don't diagnose names we find in classes; we get much better
11582         // diagnostics for these from DiagnoseEmptyLookup.
11583         R.clear();
11584         if (DoDiagnoseEmptyLookup)
11585           *DoDiagnoseEmptyLookup = true;
11586         return false;
11587       }
11588 
11589       OverloadCandidateSet Candidates(FnLoc, CSK);
11590       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11591         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11592                                    ExplicitTemplateArgs, Args,
11593                                    Candidates, false, /*KnownValid*/ false);
11594 
11595       OverloadCandidateSet::iterator Best;
11596       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11597         // No viable functions. Don't bother the user with notes for functions
11598         // which don't work and shouldn't be found anyway.
11599         R.clear();
11600         return false;
11601       }
11602 
11603       // Find the namespaces where ADL would have looked, and suggest
11604       // declaring the function there instead.
11605       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11606       Sema::AssociatedClassSet AssociatedClasses;
11607       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11608                                                  AssociatedNamespaces,
11609                                                  AssociatedClasses);
11610       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11611       if (canBeDeclaredInNamespace(R.getLookupName())) {
11612         DeclContext *Std = SemaRef.getStdNamespace();
11613         for (Sema::AssociatedNamespaceSet::iterator
11614                it = AssociatedNamespaces.begin(),
11615                end = AssociatedNamespaces.end(); it != end; ++it) {
11616           // Never suggest declaring a function within namespace 'std'.
11617           if (Std && Std->Encloses(*it))
11618             continue;
11619 
11620           // Never suggest declaring a function within a namespace with a
11621           // reserved name, like __gnu_cxx.
11622           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11623           if (NS &&
11624               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11625             continue;
11626 
11627           SuggestedNamespaces.insert(*it);
11628         }
11629       }
11630 
11631       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11632         << R.getLookupName();
11633       if (SuggestedNamespaces.empty()) {
11634         SemaRef.Diag(Best->Function->getLocation(),
11635                      diag::note_not_found_by_two_phase_lookup)
11636           << R.getLookupName() << 0;
11637       } else if (SuggestedNamespaces.size() == 1) {
11638         SemaRef.Diag(Best->Function->getLocation(),
11639                      diag::note_not_found_by_two_phase_lookup)
11640           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11641       } else {
11642         // FIXME: It would be useful to list the associated namespaces here,
11643         // but the diagnostics infrastructure doesn't provide a way to produce
11644         // a localized representation of a list of items.
11645         SemaRef.Diag(Best->Function->getLocation(),
11646                      diag::note_not_found_by_two_phase_lookup)
11647           << R.getLookupName() << 2;
11648       }
11649 
11650       // Try to recover by calling this function.
11651       return true;
11652     }
11653 
11654     R.clear();
11655   }
11656 
11657   return false;
11658 }
11659 
11660 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11661 /// template, where the non-dependent operator was declared after the template
11662 /// was defined.
11663 ///
11664 /// Returns true if a viable candidate was found and a diagnostic was issued.
11665 static bool
11666 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11667                                SourceLocation OpLoc,
11668                                ArrayRef<Expr *> Args) {
11669   DeclarationName OpName =
11670     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11671   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11672   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11673                                 OverloadCandidateSet::CSK_Operator,
11674                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11675 }
11676 
11677 namespace {
11678 class BuildRecoveryCallExprRAII {
11679   Sema &SemaRef;
11680 public:
11681   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11682     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11683     SemaRef.IsBuildingRecoveryCallExpr = true;
11684   }
11685 
11686   ~BuildRecoveryCallExprRAII() {
11687     SemaRef.IsBuildingRecoveryCallExpr = false;
11688   }
11689 };
11690 
11691 }
11692 
11693 static std::unique_ptr<CorrectionCandidateCallback>
11694 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11695               bool HasTemplateArgs, bool AllowTypoCorrection) {
11696   if (!AllowTypoCorrection)
11697     return llvm::make_unique<NoTypoCorrectionCCC>();
11698   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11699                                                   HasTemplateArgs, ME);
11700 }
11701 
11702 /// Attempts to recover from a call where no functions were found.
11703 ///
11704 /// Returns true if new candidates were found.
11705 static ExprResult
11706 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11707                       UnresolvedLookupExpr *ULE,
11708                       SourceLocation LParenLoc,
11709                       MutableArrayRef<Expr *> Args,
11710                       SourceLocation RParenLoc,
11711                       bool EmptyLookup, bool AllowTypoCorrection) {
11712   // Do not try to recover if it is already building a recovery call.
11713   // This stops infinite loops for template instantiations like
11714   //
11715   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11716   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11717   //
11718   if (SemaRef.IsBuildingRecoveryCallExpr)
11719     return ExprError();
11720   BuildRecoveryCallExprRAII RCE(SemaRef);
11721 
11722   CXXScopeSpec SS;
11723   SS.Adopt(ULE->getQualifierLoc());
11724   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11725 
11726   TemplateArgumentListInfo TABuffer;
11727   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11728   if (ULE->hasExplicitTemplateArgs()) {
11729     ULE->copyTemplateArgumentsInto(TABuffer);
11730     ExplicitTemplateArgs = &TABuffer;
11731   }
11732 
11733   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11734                  Sema::LookupOrdinaryName);
11735   bool DoDiagnoseEmptyLookup = EmptyLookup;
11736   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11737                               OverloadCandidateSet::CSK_Normal,
11738                               ExplicitTemplateArgs, Args,
11739                               &DoDiagnoseEmptyLookup) &&
11740     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11741         S, SS, R,
11742         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11743                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11744         ExplicitTemplateArgs, Args)))
11745     return ExprError();
11746 
11747   assert(!R.empty() && "lookup results empty despite recovery");
11748 
11749   // If recovery created an ambiguity, just bail out.
11750   if (R.isAmbiguous()) {
11751     R.suppressDiagnostics();
11752     return ExprError();
11753   }
11754 
11755   // Build an implicit member call if appropriate.  Just drop the
11756   // casts and such from the call, we don't really care.
11757   ExprResult NewFn = ExprError();
11758   if ((*R.begin())->isCXXClassMember())
11759     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11760                                                     ExplicitTemplateArgs, S);
11761   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11762     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11763                                         ExplicitTemplateArgs);
11764   else
11765     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11766 
11767   if (NewFn.isInvalid())
11768     return ExprError();
11769 
11770   // This shouldn't cause an infinite loop because we're giving it
11771   // an expression with viable lookup results, which should never
11772   // end up here.
11773   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11774                                MultiExprArg(Args.data(), Args.size()),
11775                                RParenLoc);
11776 }
11777 
11778 /// \brief Constructs and populates an OverloadedCandidateSet from
11779 /// the given function.
11780 /// \returns true when an the ExprResult output parameter has been set.
11781 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11782                                   UnresolvedLookupExpr *ULE,
11783                                   MultiExprArg Args,
11784                                   SourceLocation RParenLoc,
11785                                   OverloadCandidateSet *CandidateSet,
11786                                   ExprResult *Result) {
11787 #ifndef NDEBUG
11788   if (ULE->requiresADL()) {
11789     // To do ADL, we must have found an unqualified name.
11790     assert(!ULE->getQualifier() && "qualified name with ADL");
11791 
11792     // We don't perform ADL for implicit declarations of builtins.
11793     // Verify that this was correctly set up.
11794     FunctionDecl *F;
11795     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11796         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11797         F->getBuiltinID() && F->isImplicit())
11798       llvm_unreachable("performing ADL for builtin");
11799 
11800     // We don't perform ADL in C.
11801     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11802   }
11803 #endif
11804 
11805   UnbridgedCastsSet UnbridgedCasts;
11806   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11807     *Result = ExprError();
11808     return true;
11809   }
11810 
11811   // Add the functions denoted by the callee to the set of candidate
11812   // functions, including those from argument-dependent lookup.
11813   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11814 
11815   if (getLangOpts().MSVCCompat &&
11816       CurContext->isDependentContext() && !isSFINAEContext() &&
11817       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11818 
11819     OverloadCandidateSet::iterator Best;
11820     if (CandidateSet->empty() ||
11821         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11822             OR_No_Viable_Function) {
11823       // In Microsoft mode, if we are inside a template class member function then
11824       // create a type dependent CallExpr. The goal is to postpone name lookup
11825       // to instantiation time to be able to search into type dependent base
11826       // classes.
11827       CallExpr *CE = new (Context) CallExpr(
11828           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11829       CE->setTypeDependent(true);
11830       CE->setValueDependent(true);
11831       CE->setInstantiationDependent(true);
11832       *Result = CE;
11833       return true;
11834     }
11835   }
11836 
11837   if (CandidateSet->empty())
11838     return false;
11839 
11840   UnbridgedCasts.restore();
11841   return false;
11842 }
11843 
11844 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11845 /// the completed call expression. If overload resolution fails, emits
11846 /// diagnostics and returns ExprError()
11847 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11848                                            UnresolvedLookupExpr *ULE,
11849                                            SourceLocation LParenLoc,
11850                                            MultiExprArg Args,
11851                                            SourceLocation RParenLoc,
11852                                            Expr *ExecConfig,
11853                                            OverloadCandidateSet *CandidateSet,
11854                                            OverloadCandidateSet::iterator *Best,
11855                                            OverloadingResult OverloadResult,
11856                                            bool AllowTypoCorrection) {
11857   if (CandidateSet->empty())
11858     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11859                                  RParenLoc, /*EmptyLookup=*/true,
11860                                  AllowTypoCorrection);
11861 
11862   switch (OverloadResult) {
11863   case OR_Success: {
11864     FunctionDecl *FDecl = (*Best)->Function;
11865     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11866     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11867       return ExprError();
11868     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11869     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11870                                          ExecConfig);
11871   }
11872 
11873   case OR_No_Viable_Function: {
11874     // Try to recover by looking for viable functions which the user might
11875     // have meant to call.
11876     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11877                                                 Args, RParenLoc,
11878                                                 /*EmptyLookup=*/false,
11879                                                 AllowTypoCorrection);
11880     if (!Recovery.isInvalid())
11881       return Recovery;
11882 
11883     // If the user passes in a function that we can't take the address of, we
11884     // generally end up emitting really bad error messages. Here, we attempt to
11885     // emit better ones.
11886     for (const Expr *Arg : Args) {
11887       if (!Arg->getType()->isFunctionType())
11888         continue;
11889       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11890         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11891         if (FD &&
11892             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11893                                                        Arg->getExprLoc()))
11894           return ExprError();
11895       }
11896     }
11897 
11898     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11899         << ULE->getName() << Fn->getSourceRange();
11900     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11901     break;
11902   }
11903 
11904   case OR_Ambiguous:
11905     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11906       << ULE->getName() << Fn->getSourceRange();
11907     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11908     break;
11909 
11910   case OR_Deleted: {
11911     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11912       << (*Best)->Function->isDeleted()
11913       << ULE->getName()
11914       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11915       << Fn->getSourceRange();
11916     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11917 
11918     // We emitted an error for the unvailable/deleted function call but keep
11919     // the call in the AST.
11920     FunctionDecl *FDecl = (*Best)->Function;
11921     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11922     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11923                                          ExecConfig);
11924   }
11925   }
11926 
11927   // Overload resolution failed.
11928   return ExprError();
11929 }
11930 
11931 static void markUnaddressableCandidatesUnviable(Sema &S,
11932                                                 OverloadCandidateSet &CS) {
11933   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11934     if (I->Viable &&
11935         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11936       I->Viable = false;
11937       I->FailureKind = ovl_fail_addr_not_available;
11938     }
11939   }
11940 }
11941 
11942 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11943 /// (which eventually refers to the declaration Func) and the call
11944 /// arguments Args/NumArgs, attempt to resolve the function call down
11945 /// to a specific function. If overload resolution succeeds, returns
11946 /// the call expression produced by overload resolution.
11947 /// Otherwise, emits diagnostics and returns ExprError.
11948 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11949                                          UnresolvedLookupExpr *ULE,
11950                                          SourceLocation LParenLoc,
11951                                          MultiExprArg Args,
11952                                          SourceLocation RParenLoc,
11953                                          Expr *ExecConfig,
11954                                          bool AllowTypoCorrection,
11955                                          bool CalleesAddressIsTaken) {
11956   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11957                                     OverloadCandidateSet::CSK_Normal);
11958   ExprResult result;
11959 
11960   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11961                              &result))
11962     return result;
11963 
11964   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11965   // functions that aren't addressible are considered unviable.
11966   if (CalleesAddressIsTaken)
11967     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11968 
11969   OverloadCandidateSet::iterator Best;
11970   OverloadingResult OverloadResult =
11971       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11972 
11973   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11974                                   RParenLoc, ExecConfig, &CandidateSet,
11975                                   &Best, OverloadResult,
11976                                   AllowTypoCorrection);
11977 }
11978 
11979 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11980   return Functions.size() > 1 ||
11981     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11982 }
11983 
11984 /// \brief Create a unary operation that may resolve to an overloaded
11985 /// operator.
11986 ///
11987 /// \param OpLoc The location of the operator itself (e.g., '*').
11988 ///
11989 /// \param Opc The UnaryOperatorKind that describes this operator.
11990 ///
11991 /// \param Fns The set of non-member functions that will be
11992 /// considered by overload resolution. The caller needs to build this
11993 /// set based on the context using, e.g.,
11994 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11995 /// set should not contain any member functions; those will be added
11996 /// by CreateOverloadedUnaryOp().
11997 ///
11998 /// \param Input The input argument.
11999 ExprResult
12000 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12001                               const UnresolvedSetImpl &Fns,
12002                               Expr *Input, bool PerformADL) {
12003   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12004   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12005   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12006   // TODO: provide better source location info.
12007   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12008 
12009   if (checkPlaceholderForOverload(*this, Input))
12010     return ExprError();
12011 
12012   Expr *Args[2] = { Input, nullptr };
12013   unsigned NumArgs = 1;
12014 
12015   // For post-increment and post-decrement, add the implicit '0' as
12016   // the second argument, so that we know this is a post-increment or
12017   // post-decrement.
12018   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12019     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12020     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12021                                      SourceLocation());
12022     NumArgs = 2;
12023   }
12024 
12025   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12026 
12027   if (Input->isTypeDependent()) {
12028     if (Fns.empty())
12029       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12030                                          VK_RValue, OK_Ordinary, OpLoc, false);
12031 
12032     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12033     UnresolvedLookupExpr *Fn
12034       = UnresolvedLookupExpr::Create(Context, NamingClass,
12035                                      NestedNameSpecifierLoc(), OpNameInfo,
12036                                      /*ADL*/ true, IsOverloaded(Fns),
12037                                      Fns.begin(), Fns.end());
12038     return new (Context)
12039         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12040                             VK_RValue, OpLoc, FPOptions());
12041   }
12042 
12043   // Build an empty overload set.
12044   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12045 
12046   // Add the candidates from the given function set.
12047   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12048 
12049   // Add operator candidates that are member functions.
12050   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12051 
12052   // Add candidates from ADL.
12053   if (PerformADL) {
12054     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12055                                          /*ExplicitTemplateArgs*/nullptr,
12056                                          CandidateSet);
12057   }
12058 
12059   // Add builtin operator candidates.
12060   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12061 
12062   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12063 
12064   // Perform overload resolution.
12065   OverloadCandidateSet::iterator Best;
12066   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12067   case OR_Success: {
12068     // We found a built-in operator or an overloaded operator.
12069     FunctionDecl *FnDecl = Best->Function;
12070 
12071     if (FnDecl) {
12072       Expr *Base = nullptr;
12073       // We matched an overloaded operator. Build a call to that
12074       // operator.
12075 
12076       // Convert the arguments.
12077       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12078         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12079 
12080         ExprResult InputRes =
12081           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12082                                               Best->FoundDecl, Method);
12083         if (InputRes.isInvalid())
12084           return ExprError();
12085         Base = Input = InputRes.get();
12086       } else {
12087         // Convert the arguments.
12088         ExprResult InputInit
12089           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12090                                                       Context,
12091                                                       FnDecl->getParamDecl(0)),
12092                                       SourceLocation(),
12093                                       Input);
12094         if (InputInit.isInvalid())
12095           return ExprError();
12096         Input = InputInit.get();
12097       }
12098 
12099       // Build the actual expression node.
12100       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12101                                                 Base, HadMultipleCandidates,
12102                                                 OpLoc);
12103       if (FnExpr.isInvalid())
12104         return ExprError();
12105 
12106       // Determine the result type.
12107       QualType ResultTy = FnDecl->getReturnType();
12108       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12109       ResultTy = ResultTy.getNonLValueExprType(Context);
12110 
12111       Args[0] = Input;
12112       CallExpr *TheCall =
12113         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12114                                           ResultTy, VK, OpLoc, FPOptions());
12115 
12116       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12117         return ExprError();
12118 
12119       if (CheckFunctionCall(FnDecl, TheCall,
12120                             FnDecl->getType()->castAs<FunctionProtoType>()))
12121         return ExprError();
12122 
12123       return MaybeBindToTemporary(TheCall);
12124     } else {
12125       // We matched a built-in operator. Convert the arguments, then
12126       // break out so that we will build the appropriate built-in
12127       // operator node.
12128       ExprResult InputRes = PerformImplicitConversion(
12129           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12130       if (InputRes.isInvalid())
12131         return ExprError();
12132       Input = InputRes.get();
12133       break;
12134     }
12135   }
12136 
12137   case OR_No_Viable_Function:
12138     // This is an erroneous use of an operator which can be overloaded by
12139     // a non-member function. Check for non-member operators which were
12140     // defined too late to be candidates.
12141     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12142       // FIXME: Recover by calling the found function.
12143       return ExprError();
12144 
12145     // No viable function; fall through to handling this as a
12146     // built-in operator, which will produce an error message for us.
12147     break;
12148 
12149   case OR_Ambiguous:
12150     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12151         << UnaryOperator::getOpcodeStr(Opc)
12152         << Input->getType()
12153         << Input->getSourceRange();
12154     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12155                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12156     return ExprError();
12157 
12158   case OR_Deleted:
12159     Diag(OpLoc, diag::err_ovl_deleted_oper)
12160       << Best->Function->isDeleted()
12161       << UnaryOperator::getOpcodeStr(Opc)
12162       << getDeletedOrUnavailableSuffix(Best->Function)
12163       << Input->getSourceRange();
12164     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12165                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12166     return ExprError();
12167   }
12168 
12169   // Either we found no viable overloaded operator or we matched a
12170   // built-in operator. In either case, fall through to trying to
12171   // build a built-in operation.
12172   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12173 }
12174 
12175 /// \brief Create a binary operation that may resolve to an overloaded
12176 /// operator.
12177 ///
12178 /// \param OpLoc The location of the operator itself (e.g., '+').
12179 ///
12180 /// \param Opc The BinaryOperatorKind that describes this operator.
12181 ///
12182 /// \param Fns The set of non-member functions that will be
12183 /// considered by overload resolution. The caller needs to build this
12184 /// set based on the context using, e.g.,
12185 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12186 /// set should not contain any member functions; those will be added
12187 /// by CreateOverloadedBinOp().
12188 ///
12189 /// \param LHS Left-hand argument.
12190 /// \param RHS Right-hand argument.
12191 ExprResult
12192 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12193                             BinaryOperatorKind Opc,
12194                             const UnresolvedSetImpl &Fns,
12195                             Expr *LHS, Expr *RHS, bool PerformADL) {
12196   Expr *Args[2] = { LHS, RHS };
12197   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12198 
12199   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12200   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12201 
12202   // If either side is type-dependent, create an appropriate dependent
12203   // expression.
12204   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12205     if (Fns.empty()) {
12206       // If there are no functions to store, just build a dependent
12207       // BinaryOperator or CompoundAssignment.
12208       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12209         return new (Context) BinaryOperator(
12210             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12211             OpLoc, FPFeatures);
12212 
12213       return new (Context) CompoundAssignOperator(
12214           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12215           Context.DependentTy, Context.DependentTy, OpLoc,
12216           FPFeatures);
12217     }
12218 
12219     // FIXME: save results of ADL from here?
12220     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12221     // TODO: provide better source location info in DNLoc component.
12222     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12223     UnresolvedLookupExpr *Fn
12224       = UnresolvedLookupExpr::Create(Context, NamingClass,
12225                                      NestedNameSpecifierLoc(), OpNameInfo,
12226                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12227                                      Fns.begin(), Fns.end());
12228     return new (Context)
12229         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12230                             VK_RValue, OpLoc, FPFeatures);
12231   }
12232 
12233   // Always do placeholder-like conversions on the RHS.
12234   if (checkPlaceholderForOverload(*this, Args[1]))
12235     return ExprError();
12236 
12237   // Do placeholder-like conversion on the LHS; note that we should
12238   // not get here with a PseudoObject LHS.
12239   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12240   if (checkPlaceholderForOverload(*this, Args[0]))
12241     return ExprError();
12242 
12243   // If this is the assignment operator, we only perform overload resolution
12244   // if the left-hand side is a class or enumeration type. This is actually
12245   // a hack. The standard requires that we do overload resolution between the
12246   // various built-in candidates, but as DR507 points out, this can lead to
12247   // problems. So we do it this way, which pretty much follows what GCC does.
12248   // Note that we go the traditional code path for compound assignment forms.
12249   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12250     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12251 
12252   // If this is the .* operator, which is not overloadable, just
12253   // create a built-in binary operator.
12254   if (Opc == BO_PtrMemD)
12255     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12256 
12257   // Build an empty overload set.
12258   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12259 
12260   // Add the candidates from the given function set.
12261   AddFunctionCandidates(Fns, Args, CandidateSet);
12262 
12263   // Add operator candidates that are member functions.
12264   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12265 
12266   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12267   // performed for an assignment operator (nor for operator[] nor operator->,
12268   // which don't get here).
12269   if (Opc != BO_Assign && PerformADL)
12270     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12271                                          /*ExplicitTemplateArgs*/ nullptr,
12272                                          CandidateSet);
12273 
12274   // Add builtin operator candidates.
12275   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12276 
12277   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12278 
12279   // Perform overload resolution.
12280   OverloadCandidateSet::iterator Best;
12281   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12282     case OR_Success: {
12283       // We found a built-in operator or an overloaded operator.
12284       FunctionDecl *FnDecl = Best->Function;
12285 
12286       if (FnDecl) {
12287         Expr *Base = nullptr;
12288         // We matched an overloaded operator. Build a call to that
12289         // operator.
12290 
12291         // Convert the arguments.
12292         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12293           // Best->Access is only meaningful for class members.
12294           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12295 
12296           ExprResult Arg1 =
12297             PerformCopyInitialization(
12298               InitializedEntity::InitializeParameter(Context,
12299                                                      FnDecl->getParamDecl(0)),
12300               SourceLocation(), Args[1]);
12301           if (Arg1.isInvalid())
12302             return ExprError();
12303 
12304           ExprResult Arg0 =
12305             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12306                                                 Best->FoundDecl, Method);
12307           if (Arg0.isInvalid())
12308             return ExprError();
12309           Base = Args[0] = Arg0.getAs<Expr>();
12310           Args[1] = RHS = Arg1.getAs<Expr>();
12311         } else {
12312           // Convert the arguments.
12313           ExprResult Arg0 = PerformCopyInitialization(
12314             InitializedEntity::InitializeParameter(Context,
12315                                                    FnDecl->getParamDecl(0)),
12316             SourceLocation(), Args[0]);
12317           if (Arg0.isInvalid())
12318             return ExprError();
12319 
12320           ExprResult Arg1 =
12321             PerformCopyInitialization(
12322               InitializedEntity::InitializeParameter(Context,
12323                                                      FnDecl->getParamDecl(1)),
12324               SourceLocation(), Args[1]);
12325           if (Arg1.isInvalid())
12326             return ExprError();
12327           Args[0] = LHS = Arg0.getAs<Expr>();
12328           Args[1] = RHS = Arg1.getAs<Expr>();
12329         }
12330 
12331         // Build the actual expression node.
12332         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12333                                                   Best->FoundDecl, Base,
12334                                                   HadMultipleCandidates, OpLoc);
12335         if (FnExpr.isInvalid())
12336           return ExprError();
12337 
12338         // Determine the result type.
12339         QualType ResultTy = FnDecl->getReturnType();
12340         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12341         ResultTy = ResultTy.getNonLValueExprType(Context);
12342 
12343         CXXOperatorCallExpr *TheCall =
12344           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12345                                             Args, ResultTy, VK, OpLoc,
12346                                             FPFeatures);
12347 
12348         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12349                                 FnDecl))
12350           return ExprError();
12351 
12352         ArrayRef<const Expr *> ArgsArray(Args, 2);
12353         const Expr *ImplicitThis = nullptr;
12354         // Cut off the implicit 'this'.
12355         if (isa<CXXMethodDecl>(FnDecl)) {
12356           ImplicitThis = ArgsArray[0];
12357           ArgsArray = ArgsArray.slice(1);
12358         }
12359 
12360         // Check for a self move.
12361         if (Op == OO_Equal)
12362           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12363 
12364         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12365                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12366                   VariadicDoesNotApply);
12367 
12368         return MaybeBindToTemporary(TheCall);
12369       } else {
12370         // We matched a built-in operator. Convert the arguments, then
12371         // break out so that we will build the appropriate built-in
12372         // operator node.
12373         ExprResult ArgsRes0 =
12374             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12375                                       Best->Conversions[0], AA_Passing);
12376         if (ArgsRes0.isInvalid())
12377           return ExprError();
12378         Args[0] = ArgsRes0.get();
12379 
12380         ExprResult ArgsRes1 =
12381             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12382                                       Best->Conversions[1], AA_Passing);
12383         if (ArgsRes1.isInvalid())
12384           return ExprError();
12385         Args[1] = ArgsRes1.get();
12386         break;
12387       }
12388     }
12389 
12390     case OR_No_Viable_Function: {
12391       // C++ [over.match.oper]p9:
12392       //   If the operator is the operator , [...] and there are no
12393       //   viable functions, then the operator is assumed to be the
12394       //   built-in operator and interpreted according to clause 5.
12395       if (Opc == BO_Comma)
12396         break;
12397 
12398       // For class as left operand for assignment or compound assigment
12399       // operator do not fall through to handling in built-in, but report that
12400       // no overloaded assignment operator found
12401       ExprResult Result = ExprError();
12402       if (Args[0]->getType()->isRecordType() &&
12403           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12404         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12405              << BinaryOperator::getOpcodeStr(Opc)
12406              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12407         if (Args[0]->getType()->isIncompleteType()) {
12408           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12409             << Args[0]->getType()
12410             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12411         }
12412       } else {
12413         // This is an erroneous use of an operator which can be overloaded by
12414         // a non-member function. Check for non-member operators which were
12415         // defined too late to be candidates.
12416         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12417           // FIXME: Recover by calling the found function.
12418           return ExprError();
12419 
12420         // No viable function; try to create a built-in operation, which will
12421         // produce an error. Then, show the non-viable candidates.
12422         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12423       }
12424       assert(Result.isInvalid() &&
12425              "C++ binary operator overloading is missing candidates!");
12426       if (Result.isInvalid())
12427         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12428                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12429       return Result;
12430     }
12431 
12432     case OR_Ambiguous:
12433       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12434           << BinaryOperator::getOpcodeStr(Opc)
12435           << Args[0]->getType() << Args[1]->getType()
12436           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12437       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12438                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12439       return ExprError();
12440 
12441     case OR_Deleted:
12442       if (isImplicitlyDeleted(Best->Function)) {
12443         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12444         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12445           << Context.getRecordType(Method->getParent())
12446           << getSpecialMember(Method);
12447 
12448         // The user probably meant to call this special member. Just
12449         // explain why it's deleted.
12450         NoteDeletedFunction(Method);
12451         return ExprError();
12452       } else {
12453         Diag(OpLoc, diag::err_ovl_deleted_oper)
12454           << Best->Function->isDeleted()
12455           << BinaryOperator::getOpcodeStr(Opc)
12456           << getDeletedOrUnavailableSuffix(Best->Function)
12457           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12458       }
12459       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12460                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12461       return ExprError();
12462   }
12463 
12464   // We matched a built-in operator; build it.
12465   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12466 }
12467 
12468 ExprResult
12469 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12470                                          SourceLocation RLoc,
12471                                          Expr *Base, Expr *Idx) {
12472   Expr *Args[2] = { Base, Idx };
12473   DeclarationName OpName =
12474       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12475 
12476   // If either side is type-dependent, create an appropriate dependent
12477   // expression.
12478   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12479 
12480     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12481     // CHECKME: no 'operator' keyword?
12482     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12483     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12484     UnresolvedLookupExpr *Fn
12485       = UnresolvedLookupExpr::Create(Context, NamingClass,
12486                                      NestedNameSpecifierLoc(), OpNameInfo,
12487                                      /*ADL*/ true, /*Overloaded*/ false,
12488                                      UnresolvedSetIterator(),
12489                                      UnresolvedSetIterator());
12490     // Can't add any actual overloads yet
12491 
12492     return new (Context)
12493         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12494                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12495   }
12496 
12497   // Handle placeholders on both operands.
12498   if (checkPlaceholderForOverload(*this, Args[0]))
12499     return ExprError();
12500   if (checkPlaceholderForOverload(*this, Args[1]))
12501     return ExprError();
12502 
12503   // Build an empty overload set.
12504   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12505 
12506   // Subscript can only be overloaded as a member function.
12507 
12508   // Add operator candidates that are member functions.
12509   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12510 
12511   // Add builtin operator candidates.
12512   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12513 
12514   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12515 
12516   // Perform overload resolution.
12517   OverloadCandidateSet::iterator Best;
12518   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12519     case OR_Success: {
12520       // We found a built-in operator or an overloaded operator.
12521       FunctionDecl *FnDecl = Best->Function;
12522 
12523       if (FnDecl) {
12524         // We matched an overloaded operator. Build a call to that
12525         // operator.
12526 
12527         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12528 
12529         // Convert the arguments.
12530         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12531         ExprResult Arg0 =
12532           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12533                                               Best->FoundDecl, Method);
12534         if (Arg0.isInvalid())
12535           return ExprError();
12536         Args[0] = Arg0.get();
12537 
12538         // Convert the arguments.
12539         ExprResult InputInit
12540           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12541                                                       Context,
12542                                                       FnDecl->getParamDecl(0)),
12543                                       SourceLocation(),
12544                                       Args[1]);
12545         if (InputInit.isInvalid())
12546           return ExprError();
12547 
12548         Args[1] = InputInit.getAs<Expr>();
12549 
12550         // Build the actual expression node.
12551         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12552         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12553         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12554                                                   Best->FoundDecl,
12555                                                   Base,
12556                                                   HadMultipleCandidates,
12557                                                   OpLocInfo.getLoc(),
12558                                                   OpLocInfo.getInfo());
12559         if (FnExpr.isInvalid())
12560           return ExprError();
12561 
12562         // Determine the result type
12563         QualType ResultTy = FnDecl->getReturnType();
12564         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12565         ResultTy = ResultTy.getNonLValueExprType(Context);
12566 
12567         CXXOperatorCallExpr *TheCall =
12568           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12569                                             FnExpr.get(), Args,
12570                                             ResultTy, VK, RLoc,
12571                                             FPOptions());
12572 
12573         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12574           return ExprError();
12575 
12576         if (CheckFunctionCall(Method, TheCall,
12577                               Method->getType()->castAs<FunctionProtoType>()))
12578           return ExprError();
12579 
12580         return MaybeBindToTemporary(TheCall);
12581       } else {
12582         // We matched a built-in operator. Convert the arguments, then
12583         // break out so that we will build the appropriate built-in
12584         // operator node.
12585         ExprResult ArgsRes0 =
12586             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12587                                       Best->Conversions[0], AA_Passing);
12588         if (ArgsRes0.isInvalid())
12589           return ExprError();
12590         Args[0] = ArgsRes0.get();
12591 
12592         ExprResult ArgsRes1 =
12593             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12594                                       Best->Conversions[1], AA_Passing);
12595         if (ArgsRes1.isInvalid())
12596           return ExprError();
12597         Args[1] = ArgsRes1.get();
12598 
12599         break;
12600       }
12601     }
12602 
12603     case OR_No_Viable_Function: {
12604       if (CandidateSet.empty())
12605         Diag(LLoc, diag::err_ovl_no_oper)
12606           << Args[0]->getType() << /*subscript*/ 0
12607           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12608       else
12609         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12610           << Args[0]->getType()
12611           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12612       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12613                                   "[]", LLoc);
12614       return ExprError();
12615     }
12616 
12617     case OR_Ambiguous:
12618       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12619           << "[]"
12620           << Args[0]->getType() << Args[1]->getType()
12621           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12622       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12623                                   "[]", LLoc);
12624       return ExprError();
12625 
12626     case OR_Deleted:
12627       Diag(LLoc, diag::err_ovl_deleted_oper)
12628         << Best->Function->isDeleted() << "[]"
12629         << getDeletedOrUnavailableSuffix(Best->Function)
12630         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12631       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12632                                   "[]", LLoc);
12633       return ExprError();
12634     }
12635 
12636   // We matched a built-in operator; build it.
12637   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12638 }
12639 
12640 /// BuildCallToMemberFunction - Build a call to a member
12641 /// function. MemExpr is the expression that refers to the member
12642 /// function (and includes the object parameter), Args/NumArgs are the
12643 /// arguments to the function call (not including the object
12644 /// parameter). The caller needs to validate that the member
12645 /// expression refers to a non-static member function or an overloaded
12646 /// member function.
12647 ExprResult
12648 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12649                                 SourceLocation LParenLoc,
12650                                 MultiExprArg Args,
12651                                 SourceLocation RParenLoc) {
12652   assert(MemExprE->getType() == Context.BoundMemberTy ||
12653          MemExprE->getType() == Context.OverloadTy);
12654 
12655   // Dig out the member expression. This holds both the object
12656   // argument and the member function we're referring to.
12657   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12658 
12659   // Determine whether this is a call to a pointer-to-member function.
12660   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12661     assert(op->getType() == Context.BoundMemberTy);
12662     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12663 
12664     QualType fnType =
12665       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12666 
12667     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12668     QualType resultType = proto->getCallResultType(Context);
12669     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12670 
12671     // Check that the object type isn't more qualified than the
12672     // member function we're calling.
12673     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12674 
12675     QualType objectType = op->getLHS()->getType();
12676     if (op->getOpcode() == BO_PtrMemI)
12677       objectType = objectType->castAs<PointerType>()->getPointeeType();
12678     Qualifiers objectQuals = objectType.getQualifiers();
12679 
12680     Qualifiers difference = objectQuals - funcQuals;
12681     difference.removeObjCGCAttr();
12682     difference.removeAddressSpace();
12683     if (difference) {
12684       std::string qualsString = difference.getAsString();
12685       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12686         << fnType.getUnqualifiedType()
12687         << qualsString
12688         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12689     }
12690 
12691     CXXMemberCallExpr *call
12692       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12693                                         resultType, valueKind, RParenLoc);
12694 
12695     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12696                             call, nullptr))
12697       return ExprError();
12698 
12699     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12700       return ExprError();
12701 
12702     if (CheckOtherCall(call, proto))
12703       return ExprError();
12704 
12705     return MaybeBindToTemporary(call);
12706   }
12707 
12708   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12709     return new (Context)
12710         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12711 
12712   UnbridgedCastsSet UnbridgedCasts;
12713   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12714     return ExprError();
12715 
12716   MemberExpr *MemExpr;
12717   CXXMethodDecl *Method = nullptr;
12718   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12719   NestedNameSpecifier *Qualifier = nullptr;
12720   if (isa<MemberExpr>(NakedMemExpr)) {
12721     MemExpr = cast<MemberExpr>(NakedMemExpr);
12722     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12723     FoundDecl = MemExpr->getFoundDecl();
12724     Qualifier = MemExpr->getQualifier();
12725     UnbridgedCasts.restore();
12726   } else {
12727     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12728     Qualifier = UnresExpr->getQualifier();
12729 
12730     QualType ObjectType = UnresExpr->getBaseType();
12731     Expr::Classification ObjectClassification
12732       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12733                             : UnresExpr->getBase()->Classify(Context);
12734 
12735     // Add overload candidates
12736     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12737                                       OverloadCandidateSet::CSK_Normal);
12738 
12739     // FIXME: avoid copy.
12740     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12741     if (UnresExpr->hasExplicitTemplateArgs()) {
12742       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12743       TemplateArgs = &TemplateArgsBuffer;
12744     }
12745 
12746     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12747            E = UnresExpr->decls_end(); I != E; ++I) {
12748 
12749       NamedDecl *Func = *I;
12750       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12751       if (isa<UsingShadowDecl>(Func))
12752         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12753 
12754 
12755       // Microsoft supports direct constructor calls.
12756       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12757         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12758                              Args, CandidateSet);
12759       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12760         // If explicit template arguments were provided, we can't call a
12761         // non-template member function.
12762         if (TemplateArgs)
12763           continue;
12764 
12765         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12766                            ObjectClassification, Args, CandidateSet,
12767                            /*SuppressUserConversions=*/false);
12768       } else {
12769         AddMethodTemplateCandidate(
12770             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12771             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12772             /*SuppressUsedConversions=*/false);
12773       }
12774     }
12775 
12776     DeclarationName DeclName = UnresExpr->getMemberName();
12777 
12778     UnbridgedCasts.restore();
12779 
12780     OverloadCandidateSet::iterator Best;
12781     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12782                                             Best)) {
12783     case OR_Success:
12784       Method = cast<CXXMethodDecl>(Best->Function);
12785       FoundDecl = Best->FoundDecl;
12786       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12787       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12788         return ExprError();
12789       // If FoundDecl is different from Method (such as if one is a template
12790       // and the other a specialization), make sure DiagnoseUseOfDecl is
12791       // called on both.
12792       // FIXME: This would be more comprehensively addressed by modifying
12793       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12794       // being used.
12795       if (Method != FoundDecl.getDecl() &&
12796                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12797         return ExprError();
12798       break;
12799 
12800     case OR_No_Viable_Function:
12801       Diag(UnresExpr->getMemberLoc(),
12802            diag::err_ovl_no_viable_member_function_in_call)
12803         << DeclName << MemExprE->getSourceRange();
12804       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12805       // FIXME: Leaking incoming expressions!
12806       return ExprError();
12807 
12808     case OR_Ambiguous:
12809       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12810         << DeclName << MemExprE->getSourceRange();
12811       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12812       // FIXME: Leaking incoming expressions!
12813       return ExprError();
12814 
12815     case OR_Deleted:
12816       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12817         << Best->Function->isDeleted()
12818         << DeclName
12819         << getDeletedOrUnavailableSuffix(Best->Function)
12820         << MemExprE->getSourceRange();
12821       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12822       // FIXME: Leaking incoming expressions!
12823       return ExprError();
12824     }
12825 
12826     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12827 
12828     // If overload resolution picked a static member, build a
12829     // non-member call based on that function.
12830     if (Method->isStatic()) {
12831       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12832                                    RParenLoc);
12833     }
12834 
12835     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12836   }
12837 
12838   QualType ResultType = Method->getReturnType();
12839   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12840   ResultType = ResultType.getNonLValueExprType(Context);
12841 
12842   assert(Method && "Member call to something that isn't a method?");
12843   CXXMemberCallExpr *TheCall =
12844     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12845                                     ResultType, VK, RParenLoc);
12846 
12847   // Check for a valid return type.
12848   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12849                           TheCall, Method))
12850     return ExprError();
12851 
12852   // Convert the object argument (for a non-static member function call).
12853   // We only need to do this if there was actually an overload; otherwise
12854   // it was done at lookup.
12855   if (!Method->isStatic()) {
12856     ExprResult ObjectArg =
12857       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12858                                           FoundDecl, Method);
12859     if (ObjectArg.isInvalid())
12860       return ExprError();
12861     MemExpr->setBase(ObjectArg.get());
12862   }
12863 
12864   // Convert the rest of the arguments
12865   const FunctionProtoType *Proto =
12866     Method->getType()->getAs<FunctionProtoType>();
12867   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12868                               RParenLoc))
12869     return ExprError();
12870 
12871   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12872 
12873   if (CheckFunctionCall(Method, TheCall, Proto))
12874     return ExprError();
12875 
12876   // In the case the method to call was not selected by the overloading
12877   // resolution process, we still need to handle the enable_if attribute. Do
12878   // that here, so it will not hide previous -- and more relevant -- errors.
12879   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12880     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12881       Diag(MemE->getMemberLoc(),
12882            diag::err_ovl_no_viable_member_function_in_call)
12883           << Method << Method->getSourceRange();
12884       Diag(Method->getLocation(),
12885            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12886           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12887       return ExprError();
12888     }
12889   }
12890 
12891   if ((isa<CXXConstructorDecl>(CurContext) ||
12892        isa<CXXDestructorDecl>(CurContext)) &&
12893       TheCall->getMethodDecl()->isPure()) {
12894     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12895 
12896     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12897         MemExpr->performsVirtualDispatch(getLangOpts())) {
12898       Diag(MemExpr->getLocStart(),
12899            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12900         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12901         << MD->getParent()->getDeclName();
12902 
12903       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12904       if (getLangOpts().AppleKext)
12905         Diag(MemExpr->getLocStart(),
12906              diag::note_pure_qualified_call_kext)
12907              << MD->getParent()->getDeclName()
12908              << MD->getDeclName();
12909     }
12910   }
12911 
12912   if (CXXDestructorDecl *DD =
12913           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12914     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12915     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12916     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12917                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12918                          MemExpr->getMemberLoc());
12919   }
12920 
12921   return MaybeBindToTemporary(TheCall);
12922 }
12923 
12924 /// BuildCallToObjectOfClassType - Build a call to an object of class
12925 /// type (C++ [over.call.object]), which can end up invoking an
12926 /// overloaded function call operator (@c operator()) or performing a
12927 /// user-defined conversion on the object argument.
12928 ExprResult
12929 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12930                                    SourceLocation LParenLoc,
12931                                    MultiExprArg Args,
12932                                    SourceLocation RParenLoc) {
12933   if (checkPlaceholderForOverload(*this, Obj))
12934     return ExprError();
12935   ExprResult Object = Obj;
12936 
12937   UnbridgedCastsSet UnbridgedCasts;
12938   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12939     return ExprError();
12940 
12941   assert(Object.get()->getType()->isRecordType() &&
12942          "Requires object type argument");
12943   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12944 
12945   // C++ [over.call.object]p1:
12946   //  If the primary-expression E in the function call syntax
12947   //  evaluates to a class object of type "cv T", then the set of
12948   //  candidate functions includes at least the function call
12949   //  operators of T. The function call operators of T are obtained by
12950   //  ordinary lookup of the name operator() in the context of
12951   //  (E).operator().
12952   OverloadCandidateSet CandidateSet(LParenLoc,
12953                                     OverloadCandidateSet::CSK_Operator);
12954   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12955 
12956   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12957                           diag::err_incomplete_object_call, Object.get()))
12958     return true;
12959 
12960   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12961   LookupQualifiedName(R, Record->getDecl());
12962   R.suppressDiagnostics();
12963 
12964   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12965        Oper != OperEnd; ++Oper) {
12966     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12967                        Object.get()->Classify(Context), Args, CandidateSet,
12968                        /*SuppressUserConversions=*/false);
12969   }
12970 
12971   // C++ [over.call.object]p2:
12972   //   In addition, for each (non-explicit in C++0x) conversion function
12973   //   declared in T of the form
12974   //
12975   //        operator conversion-type-id () cv-qualifier;
12976   //
12977   //   where cv-qualifier is the same cv-qualification as, or a
12978   //   greater cv-qualification than, cv, and where conversion-type-id
12979   //   denotes the type "pointer to function of (P1,...,Pn) returning
12980   //   R", or the type "reference to pointer to function of
12981   //   (P1,...,Pn) returning R", or the type "reference to function
12982   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12983   //   is also considered as a candidate function. Similarly,
12984   //   surrogate call functions are added to the set of candidate
12985   //   functions for each conversion function declared in an
12986   //   accessible base class provided the function is not hidden
12987   //   within T by another intervening declaration.
12988   const auto &Conversions =
12989       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12990   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12991     NamedDecl *D = *I;
12992     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12993     if (isa<UsingShadowDecl>(D))
12994       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12995 
12996     // Skip over templated conversion functions; they aren't
12997     // surrogates.
12998     if (isa<FunctionTemplateDecl>(D))
12999       continue;
13000 
13001     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13002     if (!Conv->isExplicit()) {
13003       // Strip the reference type (if any) and then the pointer type (if
13004       // any) to get down to what might be a function type.
13005       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13006       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13007         ConvType = ConvPtrType->getPointeeType();
13008 
13009       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13010       {
13011         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13012                               Object.get(), Args, CandidateSet);
13013       }
13014     }
13015   }
13016 
13017   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13018 
13019   // Perform overload resolution.
13020   OverloadCandidateSet::iterator Best;
13021   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13022                                           Best)) {
13023   case OR_Success:
13024     // Overload resolution succeeded; we'll build the appropriate call
13025     // below.
13026     break;
13027 
13028   case OR_No_Viable_Function:
13029     if (CandidateSet.empty())
13030       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13031         << Object.get()->getType() << /*call*/ 1
13032         << Object.get()->getSourceRange();
13033     else
13034       Diag(Object.get()->getLocStart(),
13035            diag::err_ovl_no_viable_object_call)
13036         << Object.get()->getType() << Object.get()->getSourceRange();
13037     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13038     break;
13039 
13040   case OR_Ambiguous:
13041     Diag(Object.get()->getLocStart(),
13042          diag::err_ovl_ambiguous_object_call)
13043       << Object.get()->getType() << Object.get()->getSourceRange();
13044     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13045     break;
13046 
13047   case OR_Deleted:
13048     Diag(Object.get()->getLocStart(),
13049          diag::err_ovl_deleted_object_call)
13050       << Best->Function->isDeleted()
13051       << Object.get()->getType()
13052       << getDeletedOrUnavailableSuffix(Best->Function)
13053       << Object.get()->getSourceRange();
13054     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13055     break;
13056   }
13057 
13058   if (Best == CandidateSet.end())
13059     return true;
13060 
13061   UnbridgedCasts.restore();
13062 
13063   if (Best->Function == nullptr) {
13064     // Since there is no function declaration, this is one of the
13065     // surrogate candidates. Dig out the conversion function.
13066     CXXConversionDecl *Conv
13067       = cast<CXXConversionDecl>(
13068                          Best->Conversions[0].UserDefined.ConversionFunction);
13069 
13070     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13071                               Best->FoundDecl);
13072     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13073       return ExprError();
13074     assert(Conv == Best->FoundDecl.getDecl() &&
13075              "Found Decl & conversion-to-functionptr should be same, right?!");
13076     // We selected one of the surrogate functions that converts the
13077     // object parameter to a function pointer. Perform the conversion
13078     // on the object argument, then let ActOnCallExpr finish the job.
13079 
13080     // Create an implicit member expr to refer to the conversion operator.
13081     // and then call it.
13082     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13083                                              Conv, HadMultipleCandidates);
13084     if (Call.isInvalid())
13085       return ExprError();
13086     // Record usage of conversion in an implicit cast.
13087     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13088                                     CK_UserDefinedConversion, Call.get(),
13089                                     nullptr, VK_RValue);
13090 
13091     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13092   }
13093 
13094   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13095 
13096   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13097   // that calls this method, using Object for the implicit object
13098   // parameter and passing along the remaining arguments.
13099   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13100 
13101   // An error diagnostic has already been printed when parsing the declaration.
13102   if (Method->isInvalidDecl())
13103     return ExprError();
13104 
13105   const FunctionProtoType *Proto =
13106     Method->getType()->getAs<FunctionProtoType>();
13107 
13108   unsigned NumParams = Proto->getNumParams();
13109 
13110   DeclarationNameInfo OpLocInfo(
13111                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13112   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13113   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13114                                            Obj, HadMultipleCandidates,
13115                                            OpLocInfo.getLoc(),
13116                                            OpLocInfo.getInfo());
13117   if (NewFn.isInvalid())
13118     return true;
13119 
13120   // Build the full argument list for the method call (the implicit object
13121   // parameter is placed at the beginning of the list).
13122   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13123   MethodArgs[0] = Object.get();
13124   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13125 
13126   // Once we've built TheCall, all of the expressions are properly
13127   // owned.
13128   QualType ResultTy = Method->getReturnType();
13129   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13130   ResultTy = ResultTy.getNonLValueExprType(Context);
13131 
13132   CXXOperatorCallExpr *TheCall = new (Context)
13133       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13134                           VK, RParenLoc, FPOptions());
13135 
13136   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13137     return true;
13138 
13139   // We may have default arguments. If so, we need to allocate more
13140   // slots in the call for them.
13141   if (Args.size() < NumParams)
13142     TheCall->setNumArgs(Context, NumParams + 1);
13143 
13144   bool IsError = false;
13145 
13146   // Initialize the implicit object parameter.
13147   ExprResult ObjRes =
13148     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13149                                         Best->FoundDecl, Method);
13150   if (ObjRes.isInvalid())
13151     IsError = true;
13152   else
13153     Object = ObjRes;
13154   TheCall->setArg(0, Object.get());
13155 
13156   // Check the argument types.
13157   for (unsigned i = 0; i != NumParams; i++) {
13158     Expr *Arg;
13159     if (i < Args.size()) {
13160       Arg = Args[i];
13161 
13162       // Pass the argument.
13163 
13164       ExprResult InputInit
13165         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13166                                                     Context,
13167                                                     Method->getParamDecl(i)),
13168                                     SourceLocation(), Arg);
13169 
13170       IsError |= InputInit.isInvalid();
13171       Arg = InputInit.getAs<Expr>();
13172     } else {
13173       ExprResult DefArg
13174         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13175       if (DefArg.isInvalid()) {
13176         IsError = true;
13177         break;
13178       }
13179 
13180       Arg = DefArg.getAs<Expr>();
13181     }
13182 
13183     TheCall->setArg(i + 1, Arg);
13184   }
13185 
13186   // If this is a variadic call, handle args passed through "...".
13187   if (Proto->isVariadic()) {
13188     // Promote the arguments (C99 6.5.2.2p7).
13189     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13190       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13191                                                         nullptr);
13192       IsError |= Arg.isInvalid();
13193       TheCall->setArg(i + 1, Arg.get());
13194     }
13195   }
13196 
13197   if (IsError) return true;
13198 
13199   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13200 
13201   if (CheckFunctionCall(Method, TheCall, Proto))
13202     return true;
13203 
13204   return MaybeBindToTemporary(TheCall);
13205 }
13206 
13207 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13208 ///  (if one exists), where @c Base is an expression of class type and
13209 /// @c Member is the name of the member we're trying to find.
13210 ExprResult
13211 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13212                                bool *NoArrowOperatorFound) {
13213   assert(Base->getType()->isRecordType() &&
13214          "left-hand side must have class type");
13215 
13216   if (checkPlaceholderForOverload(*this, Base))
13217     return ExprError();
13218 
13219   SourceLocation Loc = Base->getExprLoc();
13220 
13221   // C++ [over.ref]p1:
13222   //
13223   //   [...] An expression x->m is interpreted as (x.operator->())->m
13224   //   for a class object x of type T if T::operator->() exists and if
13225   //   the operator is selected as the best match function by the
13226   //   overload resolution mechanism (13.3).
13227   DeclarationName OpName =
13228     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13229   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13230   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13231 
13232   if (RequireCompleteType(Loc, Base->getType(),
13233                           diag::err_typecheck_incomplete_tag, Base))
13234     return ExprError();
13235 
13236   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13237   LookupQualifiedName(R, BaseRecord->getDecl());
13238   R.suppressDiagnostics();
13239 
13240   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13241        Oper != OperEnd; ++Oper) {
13242     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13243                        None, CandidateSet, /*SuppressUserConversions=*/false);
13244   }
13245 
13246   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13247 
13248   // Perform overload resolution.
13249   OverloadCandidateSet::iterator Best;
13250   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13251   case OR_Success:
13252     // Overload resolution succeeded; we'll build the call below.
13253     break;
13254 
13255   case OR_No_Viable_Function:
13256     if (CandidateSet.empty()) {
13257       QualType BaseType = Base->getType();
13258       if (NoArrowOperatorFound) {
13259         // Report this specific error to the caller instead of emitting a
13260         // diagnostic, as requested.
13261         *NoArrowOperatorFound = true;
13262         return ExprError();
13263       }
13264       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13265         << BaseType << Base->getSourceRange();
13266       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13267         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13268           << FixItHint::CreateReplacement(OpLoc, ".");
13269       }
13270     } else
13271       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13272         << "operator->" << Base->getSourceRange();
13273     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13274     return ExprError();
13275 
13276   case OR_Ambiguous:
13277     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13278       << "->" << Base->getType() << Base->getSourceRange();
13279     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13280     return ExprError();
13281 
13282   case OR_Deleted:
13283     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13284       << Best->Function->isDeleted()
13285       << "->"
13286       << getDeletedOrUnavailableSuffix(Best->Function)
13287       << Base->getSourceRange();
13288     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13289     return ExprError();
13290   }
13291 
13292   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13293 
13294   // Convert the object parameter.
13295   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13296   ExprResult BaseResult =
13297     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13298                                         Best->FoundDecl, Method);
13299   if (BaseResult.isInvalid())
13300     return ExprError();
13301   Base = BaseResult.get();
13302 
13303   // Build the operator call.
13304   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13305                                             Base, HadMultipleCandidates, OpLoc);
13306   if (FnExpr.isInvalid())
13307     return ExprError();
13308 
13309   QualType ResultTy = Method->getReturnType();
13310   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13311   ResultTy = ResultTy.getNonLValueExprType(Context);
13312   CXXOperatorCallExpr *TheCall =
13313     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13314                                       Base, ResultTy, VK, OpLoc, FPOptions());
13315 
13316   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13317     return ExprError();
13318 
13319   if (CheckFunctionCall(Method, TheCall,
13320                         Method->getType()->castAs<FunctionProtoType>()))
13321     return ExprError();
13322 
13323   return MaybeBindToTemporary(TheCall);
13324 }
13325 
13326 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13327 /// a literal operator described by the provided lookup results.
13328 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13329                                           DeclarationNameInfo &SuffixInfo,
13330                                           ArrayRef<Expr*> Args,
13331                                           SourceLocation LitEndLoc,
13332                                        TemplateArgumentListInfo *TemplateArgs) {
13333   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13334 
13335   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13336                                     OverloadCandidateSet::CSK_Normal);
13337   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13338                         /*SuppressUserConversions=*/true);
13339 
13340   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13341 
13342   // Perform overload resolution. This will usually be trivial, but might need
13343   // to perform substitutions for a literal operator template.
13344   OverloadCandidateSet::iterator Best;
13345   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13346   case OR_Success:
13347   case OR_Deleted:
13348     break;
13349 
13350   case OR_No_Viable_Function:
13351     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13352       << R.getLookupName();
13353     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13354     return ExprError();
13355 
13356   case OR_Ambiguous:
13357     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13358     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13359     return ExprError();
13360   }
13361 
13362   FunctionDecl *FD = Best->Function;
13363   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13364                                         nullptr, HadMultipleCandidates,
13365                                         SuffixInfo.getLoc(),
13366                                         SuffixInfo.getInfo());
13367   if (Fn.isInvalid())
13368     return true;
13369 
13370   // Check the argument types. This should almost always be a no-op, except
13371   // that array-to-pointer decay is applied to string literals.
13372   Expr *ConvArgs[2];
13373   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13374     ExprResult InputInit = PerformCopyInitialization(
13375       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13376       SourceLocation(), Args[ArgIdx]);
13377     if (InputInit.isInvalid())
13378       return true;
13379     ConvArgs[ArgIdx] = InputInit.get();
13380   }
13381 
13382   QualType ResultTy = FD->getReturnType();
13383   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13384   ResultTy = ResultTy.getNonLValueExprType(Context);
13385 
13386   UserDefinedLiteral *UDL =
13387     new (Context) UserDefinedLiteral(Context, Fn.get(),
13388                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13389                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13390 
13391   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13392     return ExprError();
13393 
13394   if (CheckFunctionCall(FD, UDL, nullptr))
13395     return ExprError();
13396 
13397   return MaybeBindToTemporary(UDL);
13398 }
13399 
13400 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13401 /// given LookupResult is non-empty, it is assumed to describe a member which
13402 /// will be invoked. Otherwise, the function will be found via argument
13403 /// dependent lookup.
13404 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13405 /// otherwise CallExpr is set to ExprError() and some non-success value
13406 /// is returned.
13407 Sema::ForRangeStatus
13408 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13409                                 SourceLocation RangeLoc,
13410                                 const DeclarationNameInfo &NameInfo,
13411                                 LookupResult &MemberLookup,
13412                                 OverloadCandidateSet *CandidateSet,
13413                                 Expr *Range, ExprResult *CallExpr) {
13414   Scope *S = nullptr;
13415 
13416   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13417   if (!MemberLookup.empty()) {
13418     ExprResult MemberRef =
13419         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13420                                  /*IsPtr=*/false, CXXScopeSpec(),
13421                                  /*TemplateKWLoc=*/SourceLocation(),
13422                                  /*FirstQualifierInScope=*/nullptr,
13423                                  MemberLookup,
13424                                  /*TemplateArgs=*/nullptr, S);
13425     if (MemberRef.isInvalid()) {
13426       *CallExpr = ExprError();
13427       return FRS_DiagnosticIssued;
13428     }
13429     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13430     if (CallExpr->isInvalid()) {
13431       *CallExpr = ExprError();
13432       return FRS_DiagnosticIssued;
13433     }
13434   } else {
13435     UnresolvedSet<0> FoundNames;
13436     UnresolvedLookupExpr *Fn =
13437       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13438                                    NestedNameSpecifierLoc(), NameInfo,
13439                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13440                                    FoundNames.begin(), FoundNames.end());
13441 
13442     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13443                                                     CandidateSet, CallExpr);
13444     if (CandidateSet->empty() || CandidateSetError) {
13445       *CallExpr = ExprError();
13446       return FRS_NoViableFunction;
13447     }
13448     OverloadCandidateSet::iterator Best;
13449     OverloadingResult OverloadResult =
13450         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13451 
13452     if (OverloadResult == OR_No_Viable_Function) {
13453       *CallExpr = ExprError();
13454       return FRS_NoViableFunction;
13455     }
13456     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13457                                          Loc, nullptr, CandidateSet, &Best,
13458                                          OverloadResult,
13459                                          /*AllowTypoCorrection=*/false);
13460     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13461       *CallExpr = ExprError();
13462       return FRS_DiagnosticIssued;
13463     }
13464   }
13465   return FRS_Success;
13466 }
13467 
13468 
13469 /// FixOverloadedFunctionReference - E is an expression that refers to
13470 /// a C++ overloaded function (possibly with some parentheses and
13471 /// perhaps a '&' around it). We have resolved the overloaded function
13472 /// to the function declaration Fn, so patch up the expression E to
13473 /// refer (possibly indirectly) to Fn. Returns the new expr.
13474 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13475                                            FunctionDecl *Fn) {
13476   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13477     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13478                                                    Found, Fn);
13479     if (SubExpr == PE->getSubExpr())
13480       return PE;
13481 
13482     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13483   }
13484 
13485   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13486     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13487                                                    Found, Fn);
13488     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13489                                SubExpr->getType()) &&
13490            "Implicit cast type cannot be determined from overload");
13491     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13492     if (SubExpr == ICE->getSubExpr())
13493       return ICE;
13494 
13495     return ImplicitCastExpr::Create(Context, ICE->getType(),
13496                                     ICE->getCastKind(),
13497                                     SubExpr, nullptr,
13498                                     ICE->getValueKind());
13499   }
13500 
13501   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13502     if (!GSE->isResultDependent()) {
13503       Expr *SubExpr =
13504           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13505       if (SubExpr == GSE->getResultExpr())
13506         return GSE;
13507 
13508       // Replace the resulting type information before rebuilding the generic
13509       // selection expression.
13510       ArrayRef<Expr *> A = GSE->getAssocExprs();
13511       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13512       unsigned ResultIdx = GSE->getResultIndex();
13513       AssocExprs[ResultIdx] = SubExpr;
13514 
13515       return new (Context) GenericSelectionExpr(
13516           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13517           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13518           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13519           ResultIdx);
13520     }
13521     // Rather than fall through to the unreachable, return the original generic
13522     // selection expression.
13523     return GSE;
13524   }
13525 
13526   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13527     assert(UnOp->getOpcode() == UO_AddrOf &&
13528            "Can only take the address of an overloaded function");
13529     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13530       if (Method->isStatic()) {
13531         // Do nothing: static member functions aren't any different
13532         // from non-member functions.
13533       } else {
13534         // Fix the subexpression, which really has to be an
13535         // UnresolvedLookupExpr holding an overloaded member function
13536         // or template.
13537         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13538                                                        Found, Fn);
13539         if (SubExpr == UnOp->getSubExpr())
13540           return UnOp;
13541 
13542         assert(isa<DeclRefExpr>(SubExpr)
13543                && "fixed to something other than a decl ref");
13544         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13545                && "fixed to a member ref with no nested name qualifier");
13546 
13547         // We have taken the address of a pointer to member
13548         // function. Perform the computation here so that we get the
13549         // appropriate pointer to member type.
13550         QualType ClassType
13551           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13552         QualType MemPtrType
13553           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13554         // Under the MS ABI, lock down the inheritance model now.
13555         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13556           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13557 
13558         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13559                                            VK_RValue, OK_Ordinary,
13560                                            UnOp->getOperatorLoc(), false);
13561       }
13562     }
13563     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13564                                                    Found, Fn);
13565     if (SubExpr == UnOp->getSubExpr())
13566       return UnOp;
13567 
13568     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13569                                      Context.getPointerType(SubExpr->getType()),
13570                                        VK_RValue, OK_Ordinary,
13571                                        UnOp->getOperatorLoc(), false);
13572   }
13573 
13574   // C++ [except.spec]p17:
13575   //   An exception-specification is considered to be needed when:
13576   //   - in an expression the function is the unique lookup result or the
13577   //     selected member of a set of overloaded functions
13578   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13579     ResolveExceptionSpec(E->getExprLoc(), FPT);
13580 
13581   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13582     // FIXME: avoid copy.
13583     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13584     if (ULE->hasExplicitTemplateArgs()) {
13585       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13586       TemplateArgs = &TemplateArgsBuffer;
13587     }
13588 
13589     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13590                                            ULE->getQualifierLoc(),
13591                                            ULE->getTemplateKeywordLoc(),
13592                                            Fn,
13593                                            /*enclosing*/ false, // FIXME?
13594                                            ULE->getNameLoc(),
13595                                            Fn->getType(),
13596                                            VK_LValue,
13597                                            Found.getDecl(),
13598                                            TemplateArgs);
13599     MarkDeclRefReferenced(DRE);
13600     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13601     return DRE;
13602   }
13603 
13604   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13605     // FIXME: avoid copy.
13606     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13607     if (MemExpr->hasExplicitTemplateArgs()) {
13608       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13609       TemplateArgs = &TemplateArgsBuffer;
13610     }
13611 
13612     Expr *Base;
13613 
13614     // If we're filling in a static method where we used to have an
13615     // implicit member access, rewrite to a simple decl ref.
13616     if (MemExpr->isImplicitAccess()) {
13617       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13618         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13619                                                MemExpr->getQualifierLoc(),
13620                                                MemExpr->getTemplateKeywordLoc(),
13621                                                Fn,
13622                                                /*enclosing*/ false,
13623                                                MemExpr->getMemberLoc(),
13624                                                Fn->getType(),
13625                                                VK_LValue,
13626                                                Found.getDecl(),
13627                                                TemplateArgs);
13628         MarkDeclRefReferenced(DRE);
13629         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13630         return DRE;
13631       } else {
13632         SourceLocation Loc = MemExpr->getMemberLoc();
13633         if (MemExpr->getQualifier())
13634           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13635         CheckCXXThisCapture(Loc);
13636         Base = new (Context) CXXThisExpr(Loc,
13637                                          MemExpr->getBaseType(),
13638                                          /*isImplicit=*/true);
13639       }
13640     } else
13641       Base = MemExpr->getBase();
13642 
13643     ExprValueKind valueKind;
13644     QualType type;
13645     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13646       valueKind = VK_LValue;
13647       type = Fn->getType();
13648     } else {
13649       valueKind = VK_RValue;
13650       type = Context.BoundMemberTy;
13651     }
13652 
13653     MemberExpr *ME = MemberExpr::Create(
13654         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13655         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13656         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13657         OK_Ordinary);
13658     ME->setHadMultipleCandidates(true);
13659     MarkMemberReferenced(ME);
13660     return ME;
13661   }
13662 
13663   llvm_unreachable("Invalid reference to overloaded function");
13664 }
13665 
13666 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13667                                                 DeclAccessPair Found,
13668                                                 FunctionDecl *Fn) {
13669   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13670 }
13671