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 explicit 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 explicit 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 = 0; Arith < NumArithmeticTypes; ++Arith) {
7800       const auto TypeOfT = ArithmeticTypes[Arith];
7801       if (Op == OO_MinusMinus && TypeOfT == S.Context.BoolTy)
7802         continue;
7803       addPlusPlusMinusMinusStyleOverloads(
7804         TypeOfT,
7805         VisibleTypeConversionsQuals.hasVolatile(),
7806         VisibleTypeConversionsQuals.hasRestrict());
7807     }
7808   }
7809 
7810   // C++ [over.built]p5:
7811   //
7812   //   For every pair (T, VQ), where T is a cv-qualified or
7813   //   cv-unqualified object type, and VQ is either volatile or
7814   //   empty, there exist candidate operator functions of the form
7815   //
7816   //       T*VQ&      operator++(T*VQ&);
7817   //       T*VQ&      operator--(T*VQ&);
7818   //       T*         operator++(T*VQ&, int);
7819   //       T*         operator--(T*VQ&, int);
7820   void addPlusPlusMinusMinusPointerOverloads() {
7821     for (BuiltinCandidateTypeSet::iterator
7822               Ptr = CandidateTypes[0].pointer_begin(),
7823            PtrEnd = CandidateTypes[0].pointer_end();
7824          Ptr != PtrEnd; ++Ptr) {
7825       // Skip pointer types that aren't pointers to object types.
7826       if (!(*Ptr)->getPointeeType()->isObjectType())
7827         continue;
7828 
7829       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7830         (!(*Ptr).isVolatileQualified() &&
7831          VisibleTypeConversionsQuals.hasVolatile()),
7832         (!(*Ptr).isRestrictQualified() &&
7833          VisibleTypeConversionsQuals.hasRestrict()));
7834     }
7835   }
7836 
7837   // C++ [over.built]p6:
7838   //   For every cv-qualified or cv-unqualified object type T, there
7839   //   exist candidate operator functions of the form
7840   //
7841   //       T&         operator*(T*);
7842   //
7843   // C++ [over.built]p7:
7844   //   For every function type T that does not have cv-qualifiers or a
7845   //   ref-qualifier, there exist candidate operator functions of the form
7846   //       T&         operator*(T*);
7847   void addUnaryStarPointerOverloads() {
7848     for (BuiltinCandidateTypeSet::iterator
7849               Ptr = CandidateTypes[0].pointer_begin(),
7850            PtrEnd = CandidateTypes[0].pointer_end();
7851          Ptr != PtrEnd; ++Ptr) {
7852       QualType ParamTy = *Ptr;
7853       QualType PointeeTy = ParamTy->getPointeeType();
7854       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7855         continue;
7856 
7857       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7858         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7859           continue;
7860 
7861       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7862     }
7863   }
7864 
7865   // C++ [over.built]p9:
7866   //  For every promoted arithmetic type T, there exist candidate
7867   //  operator functions of the form
7868   //
7869   //       T         operator+(T);
7870   //       T         operator-(T);
7871   void addUnaryPlusOrMinusArithmeticOverloads() {
7872     if (!HasArithmeticOrEnumeralCandidateType)
7873       return;
7874 
7875     for (unsigned Arith = FirstPromotedArithmeticType;
7876          Arith < LastPromotedArithmeticType; ++Arith) {
7877       QualType ArithTy = ArithmeticTypes[Arith];
7878       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7879     }
7880 
7881     // Extension: We also add these operators for vector types.
7882     for (BuiltinCandidateTypeSet::iterator
7883               Vec = CandidateTypes[0].vector_begin(),
7884            VecEnd = CandidateTypes[0].vector_end();
7885          Vec != VecEnd; ++Vec) {
7886       QualType VecTy = *Vec;
7887       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7888     }
7889   }
7890 
7891   // C++ [over.built]p8:
7892   //   For every type T, there exist candidate operator functions of
7893   //   the form
7894   //
7895   //       T*         operator+(T*);
7896   void addUnaryPlusPointerOverloads() {
7897     for (BuiltinCandidateTypeSet::iterator
7898               Ptr = CandidateTypes[0].pointer_begin(),
7899            PtrEnd = CandidateTypes[0].pointer_end();
7900          Ptr != PtrEnd; ++Ptr) {
7901       QualType ParamTy = *Ptr;
7902       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7903     }
7904   }
7905 
7906   // C++ [over.built]p10:
7907   //   For every promoted integral type T, there exist candidate
7908   //   operator functions of the form
7909   //
7910   //        T         operator~(T);
7911   void addUnaryTildePromotedIntegralOverloads() {
7912     if (!HasArithmeticOrEnumeralCandidateType)
7913       return;
7914 
7915     for (unsigned Int = FirstPromotedIntegralType;
7916          Int < LastPromotedIntegralType; ++Int) {
7917       QualType IntTy = ArithmeticTypes[Int];
7918       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7919     }
7920 
7921     // Extension: We also add this operator for vector types.
7922     for (BuiltinCandidateTypeSet::iterator
7923               Vec = CandidateTypes[0].vector_begin(),
7924            VecEnd = CandidateTypes[0].vector_end();
7925          Vec != VecEnd; ++Vec) {
7926       QualType VecTy = *Vec;
7927       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7928     }
7929   }
7930 
7931   // C++ [over.match.oper]p16:
7932   //   For every pointer to member type T or type std::nullptr_t, there
7933   //   exist candidate operator functions of the form
7934   //
7935   //        bool operator==(T,T);
7936   //        bool operator!=(T,T);
7937   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7938     /// Set of (canonical) types that we've already handled.
7939     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7940 
7941     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7942       for (BuiltinCandidateTypeSet::iterator
7943                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7944              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7945            MemPtr != MemPtrEnd;
7946            ++MemPtr) {
7947         // Don't add the same builtin candidate twice.
7948         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7949           continue;
7950 
7951         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7952         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7953       }
7954 
7955       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7956         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7957         if (AddedTypes.insert(NullPtrTy).second) {
7958           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7959           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7960         }
7961       }
7962     }
7963   }
7964 
7965   // C++ [over.built]p15:
7966   //
7967   //   For every T, where T is an enumeration type or a pointer type,
7968   //   there exist candidate operator functions of the form
7969   //
7970   //        bool       operator<(T, T);
7971   //        bool       operator>(T, T);
7972   //        bool       operator<=(T, T);
7973   //        bool       operator>=(T, T);
7974   //        bool       operator==(T, T);
7975   //        bool       operator!=(T, T);
7976   void addRelationalPointerOrEnumeralOverloads() {
7977     // C++ [over.match.oper]p3:
7978     //   [...]the built-in candidates include all of the candidate operator
7979     //   functions defined in 13.6 that, compared to the given operator, [...]
7980     //   do not have the same parameter-type-list as any non-template non-member
7981     //   candidate.
7982     //
7983     // Note that in practice, this only affects enumeration types because there
7984     // aren't any built-in candidates of record type, and a user-defined operator
7985     // must have an operand of record or enumeration type. Also, the only other
7986     // overloaded operator with enumeration arguments, operator=,
7987     // cannot be overloaded for enumeration types, so this is the only place
7988     // where we must suppress candidates like this.
7989     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7990       UserDefinedBinaryOperators;
7991 
7992     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7993       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7994           CandidateTypes[ArgIdx].enumeration_end()) {
7995         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7996                                          CEnd = CandidateSet.end();
7997              C != CEnd; ++C) {
7998           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7999             continue;
8000 
8001           if (C->Function->isFunctionTemplateSpecialization())
8002             continue;
8003 
8004           QualType FirstParamType =
8005             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8006           QualType SecondParamType =
8007             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8008 
8009           // Skip if either parameter isn't of enumeral type.
8010           if (!FirstParamType->isEnumeralType() ||
8011               !SecondParamType->isEnumeralType())
8012             continue;
8013 
8014           // Add this operator to the set of known user-defined operators.
8015           UserDefinedBinaryOperators.insert(
8016             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8017                            S.Context.getCanonicalType(SecondParamType)));
8018         }
8019       }
8020     }
8021 
8022     /// Set of (canonical) types that we've already handled.
8023     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8024 
8025     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8026       for (BuiltinCandidateTypeSet::iterator
8027                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8028              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8029            Ptr != PtrEnd; ++Ptr) {
8030         // Don't add the same builtin candidate twice.
8031         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8032           continue;
8033 
8034         QualType ParamTypes[2] = { *Ptr, *Ptr };
8035         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8036       }
8037       for (BuiltinCandidateTypeSet::iterator
8038                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8039              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8040            Enum != EnumEnd; ++Enum) {
8041         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8042 
8043         // Don't add the same builtin candidate twice, or if a user defined
8044         // candidate exists.
8045         if (!AddedTypes.insert(CanonType).second ||
8046             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8047                                                             CanonType)))
8048           continue;
8049 
8050         QualType ParamTypes[2] = { *Enum, *Enum };
8051         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8052       }
8053     }
8054   }
8055 
8056   // C++ [over.built]p13:
8057   //
8058   //   For every cv-qualified or cv-unqualified object type T
8059   //   there exist candidate operator functions of the form
8060   //
8061   //      T*         operator+(T*, ptrdiff_t);
8062   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8063   //      T*         operator-(T*, ptrdiff_t);
8064   //      T*         operator+(ptrdiff_t, T*);
8065   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8066   //
8067   // C++ [over.built]p14:
8068   //
8069   //   For every T, where T is a pointer to object type, there
8070   //   exist candidate operator functions of the form
8071   //
8072   //      ptrdiff_t  operator-(T, T);
8073   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8074     /// Set of (canonical) types that we've already handled.
8075     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8076 
8077     for (int Arg = 0; Arg < 2; ++Arg) {
8078       QualType AsymmetricParamTypes[2] = {
8079         S.Context.getPointerDiffType(),
8080         S.Context.getPointerDiffType(),
8081       };
8082       for (BuiltinCandidateTypeSet::iterator
8083                 Ptr = CandidateTypes[Arg].pointer_begin(),
8084              PtrEnd = CandidateTypes[Arg].pointer_end();
8085            Ptr != PtrEnd; ++Ptr) {
8086         QualType PointeeTy = (*Ptr)->getPointeeType();
8087         if (!PointeeTy->isObjectType())
8088           continue;
8089 
8090         AsymmetricParamTypes[Arg] = *Ptr;
8091         if (Arg == 0 || Op == OO_Plus) {
8092           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8093           // T* operator+(ptrdiff_t, T*);
8094           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8095         }
8096         if (Op == OO_Minus) {
8097           // ptrdiff_t operator-(T, T);
8098           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8099             continue;
8100 
8101           QualType ParamTypes[2] = { *Ptr, *Ptr };
8102           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8103         }
8104       }
8105     }
8106   }
8107 
8108   // C++ [over.built]p12:
8109   //
8110   //   For every pair of promoted arithmetic types L and R, there
8111   //   exist candidate operator functions of the form
8112   //
8113   //        LR         operator*(L, R);
8114   //        LR         operator/(L, R);
8115   //        LR         operator+(L, R);
8116   //        LR         operator-(L, R);
8117   //        bool       operator<(L, R);
8118   //        bool       operator>(L, R);
8119   //        bool       operator<=(L, R);
8120   //        bool       operator>=(L, R);
8121   //        bool       operator==(L, R);
8122   //        bool       operator!=(L, R);
8123   //
8124   //   where LR is the result of the usual arithmetic conversions
8125   //   between types L and R.
8126   //
8127   // C++ [over.built]p24:
8128   //
8129   //   For every pair of promoted arithmetic types L and R, there exist
8130   //   candidate operator functions of the form
8131   //
8132   //        LR       operator?(bool, L, R);
8133   //
8134   //   where LR is the result of the usual arithmetic conversions
8135   //   between types L and R.
8136   // Our candidates ignore the first parameter.
8137   void addGenericBinaryArithmeticOverloads() {
8138     if (!HasArithmeticOrEnumeralCandidateType)
8139       return;
8140 
8141     for (unsigned Left = FirstPromotedArithmeticType;
8142          Left < LastPromotedArithmeticType; ++Left) {
8143       for (unsigned Right = FirstPromotedArithmeticType;
8144            Right < LastPromotedArithmeticType; ++Right) {
8145         QualType LandR[2] = { ArithmeticTypes[Left],
8146                               ArithmeticTypes[Right] };
8147         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8148       }
8149     }
8150 
8151     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8152     // conditional operator for vector types.
8153     for (BuiltinCandidateTypeSet::iterator
8154               Vec1 = CandidateTypes[0].vector_begin(),
8155            Vec1End = CandidateTypes[0].vector_end();
8156          Vec1 != Vec1End; ++Vec1) {
8157       for (BuiltinCandidateTypeSet::iterator
8158                 Vec2 = CandidateTypes[1].vector_begin(),
8159              Vec2End = CandidateTypes[1].vector_end();
8160            Vec2 != Vec2End; ++Vec2) {
8161         QualType LandR[2] = { *Vec1, *Vec2 };
8162         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8163       }
8164     }
8165   }
8166 
8167   // C++ [over.built]p17:
8168   //
8169   //   For every pair of promoted integral types L and R, there
8170   //   exist candidate operator functions of the form
8171   //
8172   //      LR         operator%(L, R);
8173   //      LR         operator&(L, R);
8174   //      LR         operator^(L, R);
8175   //      LR         operator|(L, R);
8176   //      L          operator<<(L, R);
8177   //      L          operator>>(L, R);
8178   //
8179   //   where LR is the result of the usual arithmetic conversions
8180   //   between types L and R.
8181   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8182     if (!HasArithmeticOrEnumeralCandidateType)
8183       return;
8184 
8185     for (unsigned Left = FirstPromotedIntegralType;
8186          Left < LastPromotedIntegralType; ++Left) {
8187       for (unsigned Right = FirstPromotedIntegralType;
8188            Right < LastPromotedIntegralType; ++Right) {
8189         QualType LandR[2] = { ArithmeticTypes[Left],
8190                               ArithmeticTypes[Right] };
8191         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8192       }
8193     }
8194   }
8195 
8196   // C++ [over.built]p20:
8197   //
8198   //   For every pair (T, VQ), where T is an enumeration or
8199   //   pointer to member type and VQ is either volatile or
8200   //   empty, there exist candidate operator functions of the form
8201   //
8202   //        VQ T&      operator=(VQ T&, T);
8203   void addAssignmentMemberPointerOrEnumeralOverloads() {
8204     /// Set of (canonical) types that we've already handled.
8205     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8206 
8207     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8208       for (BuiltinCandidateTypeSet::iterator
8209                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8210              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8211            Enum != EnumEnd; ++Enum) {
8212         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8213           continue;
8214 
8215         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8216       }
8217 
8218       for (BuiltinCandidateTypeSet::iterator
8219                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8220              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8221            MemPtr != MemPtrEnd; ++MemPtr) {
8222         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8223           continue;
8224 
8225         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8226       }
8227     }
8228   }
8229 
8230   // C++ [over.built]p19:
8231   //
8232   //   For every pair (T, VQ), where T is any type and VQ is either
8233   //   volatile or empty, there exist candidate operator functions
8234   //   of the form
8235   //
8236   //        T*VQ&      operator=(T*VQ&, T*);
8237   //
8238   // C++ [over.built]p21:
8239   //
8240   //   For every pair (T, VQ), where T is a cv-qualified or
8241   //   cv-unqualified object type and VQ is either volatile or
8242   //   empty, there exist candidate operator functions of the form
8243   //
8244   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8245   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8246   void addAssignmentPointerOverloads(bool isEqualOp) {
8247     /// Set of (canonical) types that we've already handled.
8248     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8249 
8250     for (BuiltinCandidateTypeSet::iterator
8251               Ptr = CandidateTypes[0].pointer_begin(),
8252            PtrEnd = CandidateTypes[0].pointer_end();
8253          Ptr != PtrEnd; ++Ptr) {
8254       // If this is operator=, keep track of the builtin candidates we added.
8255       if (isEqualOp)
8256         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8257       else if (!(*Ptr)->getPointeeType()->isObjectType())
8258         continue;
8259 
8260       // non-volatile version
8261       QualType ParamTypes[2] = {
8262         S.Context.getLValueReferenceType(*Ptr),
8263         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8264       };
8265       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8266                             /*IsAssigmentOperator=*/ isEqualOp);
8267 
8268       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8269                           VisibleTypeConversionsQuals.hasVolatile();
8270       if (NeedVolatile) {
8271         // volatile version
8272         ParamTypes[0] =
8273           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8274         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8275                               /*IsAssigmentOperator=*/isEqualOp);
8276       }
8277 
8278       if (!(*Ptr).isRestrictQualified() &&
8279           VisibleTypeConversionsQuals.hasRestrict()) {
8280         // restrict version
8281         ParamTypes[0]
8282           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8283         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8284                               /*IsAssigmentOperator=*/isEqualOp);
8285 
8286         if (NeedVolatile) {
8287           // volatile restrict version
8288           ParamTypes[0]
8289             = S.Context.getLValueReferenceType(
8290                 S.Context.getCVRQualifiedType(*Ptr,
8291                                               (Qualifiers::Volatile |
8292                                                Qualifiers::Restrict)));
8293           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8294                                 /*IsAssigmentOperator=*/isEqualOp);
8295         }
8296       }
8297     }
8298 
8299     if (isEqualOp) {
8300       for (BuiltinCandidateTypeSet::iterator
8301                 Ptr = CandidateTypes[1].pointer_begin(),
8302              PtrEnd = CandidateTypes[1].pointer_end();
8303            Ptr != PtrEnd; ++Ptr) {
8304         // Make sure we don't add the same candidate twice.
8305         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8306           continue;
8307 
8308         QualType ParamTypes[2] = {
8309           S.Context.getLValueReferenceType(*Ptr),
8310           *Ptr,
8311         };
8312 
8313         // non-volatile version
8314         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8315                               /*IsAssigmentOperator=*/true);
8316 
8317         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8318                            VisibleTypeConversionsQuals.hasVolatile();
8319         if (NeedVolatile) {
8320           // volatile version
8321           ParamTypes[0] =
8322             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8323           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8324                                 /*IsAssigmentOperator=*/true);
8325         }
8326 
8327         if (!(*Ptr).isRestrictQualified() &&
8328             VisibleTypeConversionsQuals.hasRestrict()) {
8329           // restrict version
8330           ParamTypes[0]
8331             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8332           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8333                                 /*IsAssigmentOperator=*/true);
8334 
8335           if (NeedVolatile) {
8336             // volatile restrict version
8337             ParamTypes[0]
8338               = S.Context.getLValueReferenceType(
8339                   S.Context.getCVRQualifiedType(*Ptr,
8340                                                 (Qualifiers::Volatile |
8341                                                  Qualifiers::Restrict)));
8342             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8343                                   /*IsAssigmentOperator=*/true);
8344           }
8345         }
8346       }
8347     }
8348   }
8349 
8350   // C++ [over.built]p18:
8351   //
8352   //   For every triple (L, VQ, R), where L is an arithmetic type,
8353   //   VQ is either volatile or empty, and R is a promoted
8354   //   arithmetic type, there exist candidate operator functions of
8355   //   the form
8356   //
8357   //        VQ L&      operator=(VQ L&, R);
8358   //        VQ L&      operator*=(VQ L&, R);
8359   //        VQ L&      operator/=(VQ L&, R);
8360   //        VQ L&      operator+=(VQ L&, R);
8361   //        VQ L&      operator-=(VQ L&, R);
8362   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8363     if (!HasArithmeticOrEnumeralCandidateType)
8364       return;
8365 
8366     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8367       for (unsigned Right = FirstPromotedArithmeticType;
8368            Right < LastPromotedArithmeticType; ++Right) {
8369         QualType ParamTypes[2];
8370         ParamTypes[1] = ArithmeticTypes[Right];
8371 
8372         // Add this built-in operator as a candidate (VQ is empty).
8373         ParamTypes[0] =
8374           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8375         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8376                               /*IsAssigmentOperator=*/isEqualOp);
8377 
8378         // Add this built-in operator as a candidate (VQ is 'volatile').
8379         if (VisibleTypeConversionsQuals.hasVolatile()) {
8380           ParamTypes[0] =
8381             S.Context.getVolatileType(ArithmeticTypes[Left]);
8382           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8383           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8384                                 /*IsAssigmentOperator=*/isEqualOp);
8385         }
8386       }
8387     }
8388 
8389     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8390     for (BuiltinCandidateTypeSet::iterator
8391               Vec1 = CandidateTypes[0].vector_begin(),
8392            Vec1End = CandidateTypes[0].vector_end();
8393          Vec1 != Vec1End; ++Vec1) {
8394       for (BuiltinCandidateTypeSet::iterator
8395                 Vec2 = CandidateTypes[1].vector_begin(),
8396              Vec2End = CandidateTypes[1].vector_end();
8397            Vec2 != Vec2End; ++Vec2) {
8398         QualType ParamTypes[2];
8399         ParamTypes[1] = *Vec2;
8400         // Add this built-in operator as a candidate (VQ is empty).
8401         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8402         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8403                               /*IsAssigmentOperator=*/isEqualOp);
8404 
8405         // Add this built-in operator as a candidate (VQ is 'volatile').
8406         if (VisibleTypeConversionsQuals.hasVolatile()) {
8407           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8408           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8409           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8410                                 /*IsAssigmentOperator=*/isEqualOp);
8411         }
8412       }
8413     }
8414   }
8415 
8416   // C++ [over.built]p22:
8417   //
8418   //   For every triple (L, VQ, R), where L is an integral type, VQ
8419   //   is either volatile or empty, and R is a promoted integral
8420   //   type, there exist candidate operator functions of the form
8421   //
8422   //        VQ L&       operator%=(VQ L&, R);
8423   //        VQ L&       operator<<=(VQ L&, R);
8424   //        VQ L&       operator>>=(VQ L&, R);
8425   //        VQ L&       operator&=(VQ L&, R);
8426   //        VQ L&       operator^=(VQ L&, R);
8427   //        VQ L&       operator|=(VQ L&, R);
8428   void addAssignmentIntegralOverloads() {
8429     if (!HasArithmeticOrEnumeralCandidateType)
8430       return;
8431 
8432     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8433       for (unsigned Right = FirstPromotedIntegralType;
8434            Right < LastPromotedIntegralType; ++Right) {
8435         QualType ParamTypes[2];
8436         ParamTypes[1] = ArithmeticTypes[Right];
8437 
8438         // Add this built-in operator as a candidate (VQ is empty).
8439         ParamTypes[0] =
8440           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8441         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8442         if (VisibleTypeConversionsQuals.hasVolatile()) {
8443           // Add this built-in operator as a candidate (VQ is 'volatile').
8444           ParamTypes[0] = ArithmeticTypes[Left];
8445           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8446           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8447           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8448         }
8449       }
8450     }
8451   }
8452 
8453   // C++ [over.operator]p23:
8454   //
8455   //   There also exist candidate operator functions of the form
8456   //
8457   //        bool        operator!(bool);
8458   //        bool        operator&&(bool, bool);
8459   //        bool        operator||(bool, bool);
8460   void addExclaimOverload() {
8461     QualType ParamTy = S.Context.BoolTy;
8462     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8463                           /*IsAssignmentOperator=*/false,
8464                           /*NumContextualBoolArguments=*/1);
8465   }
8466   void addAmpAmpOrPipePipeOverload() {
8467     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8468     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8469                           /*IsAssignmentOperator=*/false,
8470                           /*NumContextualBoolArguments=*/2);
8471   }
8472 
8473   // C++ [over.built]p13:
8474   //
8475   //   For every cv-qualified or cv-unqualified object type T there
8476   //   exist candidate operator functions of the form
8477   //
8478   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8479   //        T&         operator[](T*, ptrdiff_t);
8480   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8481   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8482   //        T&         operator[](ptrdiff_t, T*);
8483   void addSubscriptOverloads() {
8484     for (BuiltinCandidateTypeSet::iterator
8485               Ptr = CandidateTypes[0].pointer_begin(),
8486            PtrEnd = CandidateTypes[0].pointer_end();
8487          Ptr != PtrEnd; ++Ptr) {
8488       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8489       QualType PointeeType = (*Ptr)->getPointeeType();
8490       if (!PointeeType->isObjectType())
8491         continue;
8492 
8493       // T& operator[](T*, ptrdiff_t)
8494       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8495     }
8496 
8497     for (BuiltinCandidateTypeSet::iterator
8498               Ptr = CandidateTypes[1].pointer_begin(),
8499            PtrEnd = CandidateTypes[1].pointer_end();
8500          Ptr != PtrEnd; ++Ptr) {
8501       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8502       QualType PointeeType = (*Ptr)->getPointeeType();
8503       if (!PointeeType->isObjectType())
8504         continue;
8505 
8506       // T& operator[](ptrdiff_t, T*)
8507       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8508     }
8509   }
8510 
8511   // C++ [over.built]p11:
8512   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8513   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8514   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8515   //    there exist candidate operator functions of the form
8516   //
8517   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8518   //
8519   //    where CV12 is the union of CV1 and CV2.
8520   void addArrowStarOverloads() {
8521     for (BuiltinCandidateTypeSet::iterator
8522              Ptr = CandidateTypes[0].pointer_begin(),
8523            PtrEnd = CandidateTypes[0].pointer_end();
8524          Ptr != PtrEnd; ++Ptr) {
8525       QualType C1Ty = (*Ptr);
8526       QualType C1;
8527       QualifierCollector Q1;
8528       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8529       if (!isa<RecordType>(C1))
8530         continue;
8531       // heuristic to reduce number of builtin candidates in the set.
8532       // Add volatile/restrict version only if there are conversions to a
8533       // volatile/restrict type.
8534       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8535         continue;
8536       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8537         continue;
8538       for (BuiltinCandidateTypeSet::iterator
8539                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8540              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8541            MemPtr != MemPtrEnd; ++MemPtr) {
8542         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8543         QualType C2 = QualType(mptr->getClass(), 0);
8544         C2 = C2.getUnqualifiedType();
8545         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8546           break;
8547         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8548         // build CV12 T&
8549         QualType T = mptr->getPointeeType();
8550         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8551             T.isVolatileQualified())
8552           continue;
8553         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8554             T.isRestrictQualified())
8555           continue;
8556         T = Q1.apply(S.Context, T);
8557         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8558       }
8559     }
8560   }
8561 
8562   // Note that we don't consider the first argument, since it has been
8563   // contextually converted to bool long ago. The candidates below are
8564   // therefore added as binary.
8565   //
8566   // C++ [over.built]p25:
8567   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8568   //   enumeration type, there exist candidate operator functions of the form
8569   //
8570   //        T        operator?(bool, T, T);
8571   //
8572   void addConditionalOperatorOverloads() {
8573     /// Set of (canonical) types that we've already handled.
8574     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8575 
8576     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8577       for (BuiltinCandidateTypeSet::iterator
8578                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8579              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8580            Ptr != PtrEnd; ++Ptr) {
8581         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8582           continue;
8583 
8584         QualType ParamTypes[2] = { *Ptr, *Ptr };
8585         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8586       }
8587 
8588       for (BuiltinCandidateTypeSet::iterator
8589                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8590              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8591            MemPtr != MemPtrEnd; ++MemPtr) {
8592         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8593           continue;
8594 
8595         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8596         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8597       }
8598 
8599       if (S.getLangOpts().CPlusPlus11) {
8600         for (BuiltinCandidateTypeSet::iterator
8601                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8602                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8603              Enum != EnumEnd; ++Enum) {
8604           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8605             continue;
8606 
8607           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8608             continue;
8609 
8610           QualType ParamTypes[2] = { *Enum, *Enum };
8611           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8612         }
8613       }
8614     }
8615   }
8616 };
8617 
8618 } // end anonymous namespace
8619 
8620 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8621 /// operator overloads to the candidate set (C++ [over.built]), based
8622 /// on the operator @p Op and the arguments given. For example, if the
8623 /// operator is a binary '+', this routine might add "int
8624 /// operator+(int, int)" to cover integer addition.
8625 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8626                                         SourceLocation OpLoc,
8627                                         ArrayRef<Expr *> Args,
8628                                         OverloadCandidateSet &CandidateSet) {
8629   // Find all of the types that the arguments can convert to, but only
8630   // if the operator we're looking at has built-in operator candidates
8631   // that make use of these types. Also record whether we encounter non-record
8632   // candidate types or either arithmetic or enumeral candidate types.
8633   Qualifiers VisibleTypeConversionsQuals;
8634   VisibleTypeConversionsQuals.addConst();
8635   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8636     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8637 
8638   bool HasNonRecordCandidateType = false;
8639   bool HasArithmeticOrEnumeralCandidateType = false;
8640   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8641   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8642     CandidateTypes.emplace_back(*this);
8643     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8644                                                  OpLoc,
8645                                                  true,
8646                                                  (Op == OO_Exclaim ||
8647                                                   Op == OO_AmpAmp ||
8648                                                   Op == OO_PipePipe),
8649                                                  VisibleTypeConversionsQuals);
8650     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8651         CandidateTypes[ArgIdx].hasNonRecordTypes();
8652     HasArithmeticOrEnumeralCandidateType =
8653         HasArithmeticOrEnumeralCandidateType ||
8654         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8655   }
8656 
8657   // Exit early when no non-record types have been added to the candidate set
8658   // for any of the arguments to the operator.
8659   //
8660   // We can't exit early for !, ||, or &&, since there we have always have
8661   // 'bool' overloads.
8662   if (!HasNonRecordCandidateType &&
8663       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8664     return;
8665 
8666   // Setup an object to manage the common state for building overloads.
8667   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8668                                            VisibleTypeConversionsQuals,
8669                                            HasArithmeticOrEnumeralCandidateType,
8670                                            CandidateTypes, CandidateSet);
8671 
8672   // Dispatch over the operation to add in only those overloads which apply.
8673   switch (Op) {
8674   case OO_None:
8675   case NUM_OVERLOADED_OPERATORS:
8676     llvm_unreachable("Expected an overloaded operator");
8677 
8678   case OO_New:
8679   case OO_Delete:
8680   case OO_Array_New:
8681   case OO_Array_Delete:
8682   case OO_Call:
8683     llvm_unreachable(
8684                     "Special operators don't use AddBuiltinOperatorCandidates");
8685 
8686   case OO_Comma:
8687   case OO_Arrow:
8688   case OO_Coawait:
8689     // C++ [over.match.oper]p3:
8690     //   -- For the operator ',', the unary operator '&', the
8691     //      operator '->', or the operator 'co_await', the
8692     //      built-in candidates set is empty.
8693     break;
8694 
8695   case OO_Plus: // '+' is either unary or binary
8696     if (Args.size() == 1)
8697       OpBuilder.addUnaryPlusPointerOverloads();
8698     LLVM_FALLTHROUGH;
8699 
8700   case OO_Minus: // '-' is either unary or binary
8701     if (Args.size() == 1) {
8702       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8703     } else {
8704       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8705       OpBuilder.addGenericBinaryArithmeticOverloads();
8706     }
8707     break;
8708 
8709   case OO_Star: // '*' is either unary or binary
8710     if (Args.size() == 1)
8711       OpBuilder.addUnaryStarPointerOverloads();
8712     else
8713       OpBuilder.addGenericBinaryArithmeticOverloads();
8714     break;
8715 
8716   case OO_Slash:
8717     OpBuilder.addGenericBinaryArithmeticOverloads();
8718     break;
8719 
8720   case OO_PlusPlus:
8721   case OO_MinusMinus:
8722     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8723     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8724     break;
8725 
8726   case OO_EqualEqual:
8727   case OO_ExclaimEqual:
8728     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8729     LLVM_FALLTHROUGH;
8730 
8731   case OO_Less:
8732   case OO_Greater:
8733   case OO_LessEqual:
8734   case OO_GreaterEqual:
8735     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8736     OpBuilder.addGenericBinaryArithmeticOverloads();
8737     break;
8738 
8739   case OO_Spaceship:
8740     llvm_unreachable("<=> expressions not supported yet");
8741 
8742   case OO_Percent:
8743   case OO_Caret:
8744   case OO_Pipe:
8745   case OO_LessLess:
8746   case OO_GreaterGreater:
8747     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8748     break;
8749 
8750   case OO_Amp: // '&' is either unary or binary
8751     if (Args.size() == 1)
8752       // C++ [over.match.oper]p3:
8753       //   -- For the operator ',', the unary operator '&', or the
8754       //      operator '->', the built-in candidates set is empty.
8755       break;
8756 
8757     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8758     break;
8759 
8760   case OO_Tilde:
8761     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8762     break;
8763 
8764   case OO_Equal:
8765     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8766     LLVM_FALLTHROUGH;
8767 
8768   case OO_PlusEqual:
8769   case OO_MinusEqual:
8770     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8771     LLVM_FALLTHROUGH;
8772 
8773   case OO_StarEqual:
8774   case OO_SlashEqual:
8775     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8776     break;
8777 
8778   case OO_PercentEqual:
8779   case OO_LessLessEqual:
8780   case OO_GreaterGreaterEqual:
8781   case OO_AmpEqual:
8782   case OO_CaretEqual:
8783   case OO_PipeEqual:
8784     OpBuilder.addAssignmentIntegralOverloads();
8785     break;
8786 
8787   case OO_Exclaim:
8788     OpBuilder.addExclaimOverload();
8789     break;
8790 
8791   case OO_AmpAmp:
8792   case OO_PipePipe:
8793     OpBuilder.addAmpAmpOrPipePipeOverload();
8794     break;
8795 
8796   case OO_Subscript:
8797     OpBuilder.addSubscriptOverloads();
8798     break;
8799 
8800   case OO_ArrowStar:
8801     OpBuilder.addArrowStarOverloads();
8802     break;
8803 
8804   case OO_Conditional:
8805     OpBuilder.addConditionalOperatorOverloads();
8806     OpBuilder.addGenericBinaryArithmeticOverloads();
8807     break;
8808   }
8809 }
8810 
8811 /// \brief Add function candidates found via argument-dependent lookup
8812 /// to the set of overloading candidates.
8813 ///
8814 /// This routine performs argument-dependent name lookup based on the
8815 /// given function name (which may also be an operator name) and adds
8816 /// all of the overload candidates found by ADL to the overload
8817 /// candidate set (C++ [basic.lookup.argdep]).
8818 void
8819 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8820                                            SourceLocation Loc,
8821                                            ArrayRef<Expr *> Args,
8822                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8823                                            OverloadCandidateSet& CandidateSet,
8824                                            bool PartialOverloading) {
8825   ADLResult Fns;
8826 
8827   // FIXME: This approach for uniquing ADL results (and removing
8828   // redundant candidates from the set) relies on pointer-equality,
8829   // which means we need to key off the canonical decl.  However,
8830   // always going back to the canonical decl might not get us the
8831   // right set of default arguments.  What default arguments are
8832   // we supposed to consider on ADL candidates, anyway?
8833 
8834   // FIXME: Pass in the explicit template arguments?
8835   ArgumentDependentLookup(Name, Loc, Args, Fns);
8836 
8837   // Erase all of the candidates we already knew about.
8838   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8839                                    CandEnd = CandidateSet.end();
8840        Cand != CandEnd; ++Cand)
8841     if (Cand->Function) {
8842       Fns.erase(Cand->Function);
8843       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8844         Fns.erase(FunTmpl);
8845     }
8846 
8847   // For each of the ADL candidates we found, add it to the overload
8848   // set.
8849   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8850     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8851     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8852       if (ExplicitTemplateArgs)
8853         continue;
8854 
8855       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8856                            PartialOverloading);
8857     } else
8858       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8859                                    FoundDecl, ExplicitTemplateArgs,
8860                                    Args, CandidateSet, PartialOverloading);
8861   }
8862 }
8863 
8864 namespace {
8865 enum class Comparison { Equal, Better, Worse };
8866 }
8867 
8868 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8869 /// overload resolution.
8870 ///
8871 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8872 /// Cand1's first N enable_if attributes have precisely the same conditions as
8873 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8874 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8875 ///
8876 /// Note that you can have a pair of candidates such that Cand1's enable_if
8877 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8878 /// worse than Cand1's.
8879 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8880                                        const FunctionDecl *Cand2) {
8881   // Common case: One (or both) decls don't have enable_if attrs.
8882   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8883   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8884   if (!Cand1Attr || !Cand2Attr) {
8885     if (Cand1Attr == Cand2Attr)
8886       return Comparison::Equal;
8887     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8888   }
8889 
8890   // FIXME: The next several lines are just
8891   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8892   // instead of reverse order which is how they're stored in the AST.
8893   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8894   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8895 
8896   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8897   // has fewer enable_if attributes than Cand2.
8898   if (Cand1Attrs.size() < Cand2Attrs.size())
8899     return Comparison::Worse;
8900 
8901   auto Cand1I = Cand1Attrs.begin();
8902   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8903   for (auto &Cand2A : Cand2Attrs) {
8904     Cand1ID.clear();
8905     Cand2ID.clear();
8906 
8907     auto &Cand1A = *Cand1I++;
8908     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8909     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8910     if (Cand1ID != Cand2ID)
8911       return Comparison::Worse;
8912   }
8913 
8914   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8915 }
8916 
8917 /// isBetterOverloadCandidate - Determines whether the first overload
8918 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8919 bool clang::isBetterOverloadCandidate(
8920     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8921     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8922   // Define viable functions to be better candidates than non-viable
8923   // functions.
8924   if (!Cand2.Viable)
8925     return Cand1.Viable;
8926   else if (!Cand1.Viable)
8927     return false;
8928 
8929   // C++ [over.match.best]p1:
8930   //
8931   //   -- if F is a static member function, ICS1(F) is defined such
8932   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8933   //      any function G, and, symmetrically, ICS1(G) is neither
8934   //      better nor worse than ICS1(F).
8935   unsigned StartArg = 0;
8936   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8937     StartArg = 1;
8938 
8939   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8940     // We don't allow incompatible pointer conversions in C++.
8941     if (!S.getLangOpts().CPlusPlus)
8942       return ICS.isStandard() &&
8943              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8944 
8945     // The only ill-formed conversion we allow in C++ is the string literal to
8946     // char* conversion, which is only considered ill-formed after C++11.
8947     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8948            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8949   };
8950 
8951   // Define functions that don't require ill-formed conversions for a given
8952   // argument to be better candidates than functions that do.
8953   unsigned NumArgs = Cand1.Conversions.size();
8954   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8955   bool HasBetterConversion = false;
8956   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8957     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8958     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8959     if (Cand1Bad != Cand2Bad) {
8960       if (Cand1Bad)
8961         return false;
8962       HasBetterConversion = true;
8963     }
8964   }
8965 
8966   if (HasBetterConversion)
8967     return true;
8968 
8969   // C++ [over.match.best]p1:
8970   //   A viable function F1 is defined to be a better function than another
8971   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8972   //   conversion sequence than ICSi(F2), and then...
8973   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8974     switch (CompareImplicitConversionSequences(S, Loc,
8975                                                Cand1.Conversions[ArgIdx],
8976                                                Cand2.Conversions[ArgIdx])) {
8977     case ImplicitConversionSequence::Better:
8978       // Cand1 has a better conversion sequence.
8979       HasBetterConversion = true;
8980       break;
8981 
8982     case ImplicitConversionSequence::Worse:
8983       // Cand1 can't be better than Cand2.
8984       return false;
8985 
8986     case ImplicitConversionSequence::Indistinguishable:
8987       // Do nothing.
8988       break;
8989     }
8990   }
8991 
8992   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8993   //       ICSj(F2), or, if not that,
8994   if (HasBetterConversion)
8995     return true;
8996 
8997   //   -- the context is an initialization by user-defined conversion
8998   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8999   //      from the return type of F1 to the destination type (i.e.,
9000   //      the type of the entity being initialized) is a better
9001   //      conversion sequence than the standard conversion sequence
9002   //      from the return type of F2 to the destination type.
9003   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9004       Cand1.Function && Cand2.Function &&
9005       isa<CXXConversionDecl>(Cand1.Function) &&
9006       isa<CXXConversionDecl>(Cand2.Function)) {
9007     // First check whether we prefer one of the conversion functions over the
9008     // other. This only distinguishes the results in non-standard, extension
9009     // cases such as the conversion from a lambda closure type to a function
9010     // pointer or block.
9011     ImplicitConversionSequence::CompareKind Result =
9012         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9013     if (Result == ImplicitConversionSequence::Indistinguishable)
9014       Result = CompareStandardConversionSequences(S, Loc,
9015                                                   Cand1.FinalConversion,
9016                                                   Cand2.FinalConversion);
9017 
9018     if (Result != ImplicitConversionSequence::Indistinguishable)
9019       return Result == ImplicitConversionSequence::Better;
9020 
9021     // FIXME: Compare kind of reference binding if conversion functions
9022     // convert to a reference type used in direct reference binding, per
9023     // C++14 [over.match.best]p1 section 2 bullet 3.
9024   }
9025 
9026   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9027   // as combined with the resolution to CWG issue 243.
9028   //
9029   // When the context is initialization by constructor ([over.match.ctor] or
9030   // either phase of [over.match.list]), a constructor is preferred over
9031   // a conversion function.
9032   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9033       Cand1.Function && Cand2.Function &&
9034       isa<CXXConstructorDecl>(Cand1.Function) !=
9035           isa<CXXConstructorDecl>(Cand2.Function))
9036     return isa<CXXConstructorDecl>(Cand1.Function);
9037 
9038   //    -- F1 is a non-template function and F2 is a function template
9039   //       specialization, or, if not that,
9040   bool Cand1IsSpecialization = Cand1.Function &&
9041                                Cand1.Function->getPrimaryTemplate();
9042   bool Cand2IsSpecialization = Cand2.Function &&
9043                                Cand2.Function->getPrimaryTemplate();
9044   if (Cand1IsSpecialization != Cand2IsSpecialization)
9045     return Cand2IsSpecialization;
9046 
9047   //   -- F1 and F2 are function template specializations, and the function
9048   //      template for F1 is more specialized than the template for F2
9049   //      according to the partial ordering rules described in 14.5.5.2, or,
9050   //      if not that,
9051   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9052     if (FunctionTemplateDecl *BetterTemplate
9053           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9054                                          Cand2.Function->getPrimaryTemplate(),
9055                                          Loc,
9056                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9057                                                              : TPOC_Call,
9058                                          Cand1.ExplicitCallArguments,
9059                                          Cand2.ExplicitCallArguments))
9060       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9061   }
9062 
9063   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9064   // A derived-class constructor beats an (inherited) base class constructor.
9065   bool Cand1IsInherited =
9066       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9067   bool Cand2IsInherited =
9068       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9069   if (Cand1IsInherited != Cand2IsInherited)
9070     return Cand2IsInherited;
9071   else if (Cand1IsInherited) {
9072     assert(Cand2IsInherited);
9073     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9074     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9075     if (Cand1Class->isDerivedFrom(Cand2Class))
9076       return true;
9077     if (Cand2Class->isDerivedFrom(Cand1Class))
9078       return false;
9079     // Inherited from sibling base classes: still ambiguous.
9080   }
9081 
9082   // Check C++17 tie-breakers for deduction guides.
9083   {
9084     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9085     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9086     if (Guide1 && Guide2) {
9087       //  -- F1 is generated from a deduction-guide and F2 is not
9088       if (Guide1->isImplicit() != Guide2->isImplicit())
9089         return Guide2->isImplicit();
9090 
9091       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9092       if (Guide1->isCopyDeductionCandidate())
9093         return true;
9094     }
9095   }
9096 
9097   // Check for enable_if value-based overload resolution.
9098   if (Cand1.Function && Cand2.Function) {
9099     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9100     if (Cmp != Comparison::Equal)
9101       return Cmp == Comparison::Better;
9102   }
9103 
9104   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9105     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9106     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9107            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9108   }
9109 
9110   bool HasPS1 = Cand1.Function != nullptr &&
9111                 functionHasPassObjectSizeParams(Cand1.Function);
9112   bool HasPS2 = Cand2.Function != nullptr &&
9113                 functionHasPassObjectSizeParams(Cand2.Function);
9114   return HasPS1 != HasPS2 && HasPS1;
9115 }
9116 
9117 /// Determine whether two declarations are "equivalent" for the purposes of
9118 /// name lookup and overload resolution. This applies when the same internal/no
9119 /// linkage entity is defined by two modules (probably by textually including
9120 /// the same header). In such a case, we don't consider the declarations to
9121 /// declare the same entity, but we also don't want lookups with both
9122 /// declarations visible to be ambiguous in some cases (this happens when using
9123 /// a modularized libstdc++).
9124 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9125                                                   const NamedDecl *B) {
9126   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9127   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9128   if (!VA || !VB)
9129     return false;
9130 
9131   // The declarations must be declaring the same name as an internal linkage
9132   // entity in different modules.
9133   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9134           VB->getDeclContext()->getRedeclContext()) ||
9135       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9136           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9137       VA->isExternallyVisible() || VB->isExternallyVisible())
9138     return false;
9139 
9140   // Check that the declarations appear to be equivalent.
9141   //
9142   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9143   // For constants and functions, we should check the initializer or body is
9144   // the same. For non-constant variables, we shouldn't allow it at all.
9145   if (Context.hasSameType(VA->getType(), VB->getType()))
9146     return true;
9147 
9148   // Enum constants within unnamed enumerations will have different types, but
9149   // may still be similar enough to be interchangeable for our purposes.
9150   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9151     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9152       // Only handle anonymous enums. If the enumerations were named and
9153       // equivalent, they would have been merged to the same type.
9154       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9155       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9156       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9157           !Context.hasSameType(EnumA->getIntegerType(),
9158                                EnumB->getIntegerType()))
9159         return false;
9160       // Allow this only if the value is the same for both enumerators.
9161       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9162     }
9163   }
9164 
9165   // Nothing else is sufficiently similar.
9166   return false;
9167 }
9168 
9169 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9170     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9171   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9172 
9173   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9174   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9175       << !M << (M ? M->getFullModuleName() : "");
9176 
9177   for (auto *E : Equiv) {
9178     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9179     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9180         << !M << (M ? M->getFullModuleName() : "");
9181   }
9182 }
9183 
9184 /// \brief Computes the best viable function (C++ 13.3.3)
9185 /// within an overload candidate set.
9186 ///
9187 /// \param Loc The location of the function name (or operator symbol) for
9188 /// which overload resolution occurs.
9189 ///
9190 /// \param Best If overload resolution was successful or found a deleted
9191 /// function, \p Best points to the candidate function found.
9192 ///
9193 /// \returns The result of overload resolution.
9194 OverloadingResult
9195 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9196                                          iterator &Best) {
9197   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9198   std::transform(begin(), end(), std::back_inserter(Candidates),
9199                  [](OverloadCandidate &Cand) { return &Cand; });
9200 
9201   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9202   // are accepted by both clang and NVCC. However, during a particular
9203   // compilation mode only one call variant is viable. We need to
9204   // exclude non-viable overload candidates from consideration based
9205   // only on their host/device attributes. Specifically, if one
9206   // candidate call is WrongSide and the other is SameSide, we ignore
9207   // the WrongSide candidate.
9208   if (S.getLangOpts().CUDA) {
9209     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9210     bool ContainsSameSideCandidate =
9211         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9212           return Cand->Function &&
9213                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9214                      Sema::CFP_SameSide;
9215         });
9216     if (ContainsSameSideCandidate) {
9217       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9218         return Cand->Function &&
9219                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9220                    Sema::CFP_WrongSide;
9221       };
9222       llvm::erase_if(Candidates, IsWrongSideCandidate);
9223     }
9224   }
9225 
9226   // Find the best viable function.
9227   Best = end();
9228   for (auto *Cand : Candidates)
9229     if (Cand->Viable)
9230       if (Best == end() ||
9231           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9232         Best = Cand;
9233 
9234   // If we didn't find any viable functions, abort.
9235   if (Best == end())
9236     return OR_No_Viable_Function;
9237 
9238   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9239 
9240   // Make sure that this function is better than every other viable
9241   // function. If not, we have an ambiguity.
9242   for (auto *Cand : Candidates) {
9243     if (Cand->Viable && Cand != Best &&
9244         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9245       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9246                                                    Cand->Function)) {
9247         EquivalentCands.push_back(Cand->Function);
9248         continue;
9249       }
9250 
9251       Best = end();
9252       return OR_Ambiguous;
9253     }
9254   }
9255 
9256   // Best is the best viable function.
9257   if (Best->Function &&
9258       (Best->Function->isDeleted() ||
9259        S.isFunctionConsideredUnavailable(Best->Function)))
9260     return OR_Deleted;
9261 
9262   if (!EquivalentCands.empty())
9263     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9264                                                     EquivalentCands);
9265 
9266   return OR_Success;
9267 }
9268 
9269 namespace {
9270 
9271 enum OverloadCandidateKind {
9272   oc_function,
9273   oc_method,
9274   oc_constructor,
9275   oc_function_template,
9276   oc_method_template,
9277   oc_constructor_template,
9278   oc_implicit_default_constructor,
9279   oc_implicit_copy_constructor,
9280   oc_implicit_move_constructor,
9281   oc_implicit_copy_assignment,
9282   oc_implicit_move_assignment,
9283   oc_inherited_constructor,
9284   oc_inherited_constructor_template
9285 };
9286 
9287 static OverloadCandidateKind
9288 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9289                           std::string &Description) {
9290   bool isTemplate = false;
9291 
9292   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9293     isTemplate = true;
9294     Description = S.getTemplateArgumentBindingsText(
9295       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9296   }
9297 
9298   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9299     if (!Ctor->isImplicit()) {
9300       if (isa<ConstructorUsingShadowDecl>(Found))
9301         return isTemplate ? oc_inherited_constructor_template
9302                           : oc_inherited_constructor;
9303       else
9304         return isTemplate ? oc_constructor_template : oc_constructor;
9305     }
9306 
9307     if (Ctor->isDefaultConstructor())
9308       return oc_implicit_default_constructor;
9309 
9310     if (Ctor->isMoveConstructor())
9311       return oc_implicit_move_constructor;
9312 
9313     assert(Ctor->isCopyConstructor() &&
9314            "unexpected sort of implicit constructor");
9315     return oc_implicit_copy_constructor;
9316   }
9317 
9318   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9319     // This actually gets spelled 'candidate function' for now, but
9320     // it doesn't hurt to split it out.
9321     if (!Meth->isImplicit())
9322       return isTemplate ? oc_method_template : oc_method;
9323 
9324     if (Meth->isMoveAssignmentOperator())
9325       return oc_implicit_move_assignment;
9326 
9327     if (Meth->isCopyAssignmentOperator())
9328       return oc_implicit_copy_assignment;
9329 
9330     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9331     return oc_method;
9332   }
9333 
9334   return isTemplate ? oc_function_template : oc_function;
9335 }
9336 
9337 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9338   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9339   // set.
9340   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9341     S.Diag(FoundDecl->getLocation(),
9342            diag::note_ovl_candidate_inherited_constructor)
9343       << Shadow->getNominatedBaseClass();
9344 }
9345 
9346 } // end anonymous namespace
9347 
9348 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9349                                     const FunctionDecl *FD) {
9350   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9351     bool AlwaysTrue;
9352     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9353       return false;
9354     if (!AlwaysTrue)
9355       return false;
9356   }
9357   return true;
9358 }
9359 
9360 /// \brief Returns true if we can take the address of the function.
9361 ///
9362 /// \param Complain - If true, we'll emit a diagnostic
9363 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9364 ///   we in overload resolution?
9365 /// \param Loc - The location of the statement we're complaining about. Ignored
9366 ///   if we're not complaining, or if we're in overload resolution.
9367 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9368                                               bool Complain,
9369                                               bool InOverloadResolution,
9370                                               SourceLocation Loc) {
9371   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9372     if (Complain) {
9373       if (InOverloadResolution)
9374         S.Diag(FD->getLocStart(),
9375                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9376       else
9377         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9378     }
9379     return false;
9380   }
9381 
9382   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9383     return P->hasAttr<PassObjectSizeAttr>();
9384   });
9385   if (I == FD->param_end())
9386     return true;
9387 
9388   if (Complain) {
9389     // Add one to ParamNo because it's user-facing
9390     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9391     if (InOverloadResolution)
9392       S.Diag(FD->getLocation(),
9393              diag::note_ovl_candidate_has_pass_object_size_params)
9394           << ParamNo;
9395     else
9396       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9397           << FD << ParamNo;
9398   }
9399   return false;
9400 }
9401 
9402 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9403                                                const FunctionDecl *FD) {
9404   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9405                                            /*InOverloadResolution=*/true,
9406                                            /*Loc=*/SourceLocation());
9407 }
9408 
9409 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9410                                              bool Complain,
9411                                              SourceLocation Loc) {
9412   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9413                                              /*InOverloadResolution=*/false,
9414                                              Loc);
9415 }
9416 
9417 // Notes the location of an overload candidate.
9418 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9419                                  QualType DestType, bool TakingAddress) {
9420   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9421     return;
9422   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9423     return;
9424 
9425   std::string FnDesc;
9426   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9427   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9428                              << (unsigned) K << Fn << FnDesc;
9429 
9430   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9431   Diag(Fn->getLocation(), PD);
9432   MaybeEmitInheritedConstructorNote(*this, Found);
9433 }
9434 
9435 // Notes the location of all overload candidates designated through
9436 // OverloadedExpr
9437 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9438                                      bool TakingAddress) {
9439   assert(OverloadedExpr->getType() == Context.OverloadTy);
9440 
9441   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9442   OverloadExpr *OvlExpr = Ovl.Expression;
9443 
9444   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9445                             IEnd = OvlExpr->decls_end();
9446        I != IEnd; ++I) {
9447     if (FunctionTemplateDecl *FunTmpl =
9448                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9449       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9450                             TakingAddress);
9451     } else if (FunctionDecl *Fun
9452                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9453       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9454     }
9455   }
9456 }
9457 
9458 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9459 /// "lead" diagnostic; it will be given two arguments, the source and
9460 /// target types of the conversion.
9461 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9462                                  Sema &S,
9463                                  SourceLocation CaretLoc,
9464                                  const PartialDiagnostic &PDiag) const {
9465   S.Diag(CaretLoc, PDiag)
9466     << Ambiguous.getFromType() << Ambiguous.getToType();
9467   // FIXME: The note limiting machinery is borrowed from
9468   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9469   // refactoring here.
9470   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9471   unsigned CandsShown = 0;
9472   AmbiguousConversionSequence::const_iterator I, E;
9473   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9474     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9475       break;
9476     ++CandsShown;
9477     S.NoteOverloadCandidate(I->first, I->second);
9478   }
9479   if (I != E)
9480     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9481 }
9482 
9483 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9484                                   unsigned I, bool TakingCandidateAddress) {
9485   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9486   assert(Conv.isBad());
9487   assert(Cand->Function && "for now, candidate must be a function");
9488   FunctionDecl *Fn = Cand->Function;
9489 
9490   // There's a conversion slot for the object argument if this is a
9491   // non-constructor method.  Note that 'I' corresponds the
9492   // conversion-slot index.
9493   bool isObjectArgument = false;
9494   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9495     if (I == 0)
9496       isObjectArgument = true;
9497     else
9498       I--;
9499   }
9500 
9501   std::string FnDesc;
9502   OverloadCandidateKind FnKind =
9503       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9504 
9505   Expr *FromExpr = Conv.Bad.FromExpr;
9506   QualType FromTy = Conv.Bad.getFromType();
9507   QualType ToTy = Conv.Bad.getToType();
9508 
9509   if (FromTy == S.Context.OverloadTy) {
9510     assert(FromExpr && "overload set argument came from implicit argument?");
9511     Expr *E = FromExpr->IgnoreParens();
9512     if (isa<UnaryOperator>(E))
9513       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9514     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9515 
9516     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9517       << (unsigned) FnKind << FnDesc
9518       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9519       << ToTy << Name << I+1;
9520     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9521     return;
9522   }
9523 
9524   // Do some hand-waving analysis to see if the non-viability is due
9525   // to a qualifier mismatch.
9526   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9527   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9528   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9529     CToTy = RT->getPointeeType();
9530   else {
9531     // TODO: detect and diagnose the full richness of const mismatches.
9532     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9533       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9534         CFromTy = FromPT->getPointeeType();
9535         CToTy = ToPT->getPointeeType();
9536       }
9537   }
9538 
9539   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9540       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9541     Qualifiers FromQs = CFromTy.getQualifiers();
9542     Qualifiers ToQs = CToTy.getQualifiers();
9543 
9544     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9545       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9546         << (unsigned) FnKind << FnDesc
9547         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9548         << FromTy
9549         << FromQs.getAddressSpaceAttributePrintValue()
9550         << ToQs.getAddressSpaceAttributePrintValue()
9551         << (unsigned) isObjectArgument << I+1;
9552       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9553       return;
9554     }
9555 
9556     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9557       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9558         << (unsigned) FnKind << FnDesc
9559         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9560         << FromTy
9561         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9562         << (unsigned) isObjectArgument << I+1;
9563       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9564       return;
9565     }
9566 
9567     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9568       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9569       << (unsigned) FnKind << FnDesc
9570       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9571       << FromTy
9572       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9573       << (unsigned) isObjectArgument << I+1;
9574       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9575       return;
9576     }
9577 
9578     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9579       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9580         << (unsigned) FnKind << FnDesc
9581         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9582         << FromTy << FromQs.hasUnaligned() << I+1;
9583       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9584       return;
9585     }
9586 
9587     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9588     assert(CVR && "unexpected qualifiers mismatch");
9589 
9590     if (isObjectArgument) {
9591       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9592         << (unsigned) FnKind << FnDesc
9593         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9594         << FromTy << (CVR - 1);
9595     } else {
9596       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9597         << (unsigned) FnKind << FnDesc
9598         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9599         << FromTy << (CVR - 1) << I+1;
9600     }
9601     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9602     return;
9603   }
9604 
9605   // Special diagnostic for failure to convert an initializer list, since
9606   // telling the user that it has type void is not useful.
9607   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9608     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9609       << (unsigned) FnKind << FnDesc
9610       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9611       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9612     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9613     return;
9614   }
9615 
9616   // Diagnose references or pointers to incomplete types differently,
9617   // since it's far from impossible that the incompleteness triggered
9618   // the failure.
9619   QualType TempFromTy = FromTy.getNonReferenceType();
9620   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9621     TempFromTy = PTy->getPointeeType();
9622   if (TempFromTy->isIncompleteType()) {
9623     // Emit the generic diagnostic and, optionally, add the hints to it.
9624     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9625       << (unsigned) FnKind << FnDesc
9626       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9627       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9628       << (unsigned) (Cand->Fix.Kind);
9629 
9630     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9631     return;
9632   }
9633 
9634   // Diagnose base -> derived pointer conversions.
9635   unsigned BaseToDerivedConversion = 0;
9636   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9637     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9638       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9639                                                FromPtrTy->getPointeeType()) &&
9640           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9641           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9642           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9643                           FromPtrTy->getPointeeType()))
9644         BaseToDerivedConversion = 1;
9645     }
9646   } else if (const ObjCObjectPointerType *FromPtrTy
9647                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9648     if (const ObjCObjectPointerType *ToPtrTy
9649                                         = ToTy->getAs<ObjCObjectPointerType>())
9650       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9651         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9652           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9653                                                 FromPtrTy->getPointeeType()) &&
9654               FromIface->isSuperClassOf(ToIface))
9655             BaseToDerivedConversion = 2;
9656   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9657     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9658         !FromTy->isIncompleteType() &&
9659         !ToRefTy->getPointeeType()->isIncompleteType() &&
9660         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9661       BaseToDerivedConversion = 3;
9662     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9663                ToTy.getNonReferenceType().getCanonicalType() ==
9664                FromTy.getNonReferenceType().getCanonicalType()) {
9665       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9666         << (unsigned) FnKind << FnDesc
9667         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9668         << (unsigned) isObjectArgument << I + 1;
9669       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9670       return;
9671     }
9672   }
9673 
9674   if (BaseToDerivedConversion) {
9675     S.Diag(Fn->getLocation(),
9676            diag::note_ovl_candidate_bad_base_to_derived_conv)
9677       << (unsigned) FnKind << FnDesc
9678       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9679       << (BaseToDerivedConversion - 1)
9680       << FromTy << ToTy << I+1;
9681     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9682     return;
9683   }
9684 
9685   if (isa<ObjCObjectPointerType>(CFromTy) &&
9686       isa<PointerType>(CToTy)) {
9687       Qualifiers FromQs = CFromTy.getQualifiers();
9688       Qualifiers ToQs = CToTy.getQualifiers();
9689       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9690         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9691         << (unsigned) FnKind << FnDesc
9692         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9693         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9694         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9695         return;
9696       }
9697   }
9698 
9699   if (TakingCandidateAddress &&
9700       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9701     return;
9702 
9703   // Emit the generic diagnostic and, optionally, add the hints to it.
9704   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9705   FDiag << (unsigned) FnKind << FnDesc
9706     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9707     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9708     << (unsigned) (Cand->Fix.Kind);
9709 
9710   // If we can fix the conversion, suggest the FixIts.
9711   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9712        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9713     FDiag << *HI;
9714   S.Diag(Fn->getLocation(), FDiag);
9715 
9716   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9717 }
9718 
9719 /// Additional arity mismatch diagnosis specific to a function overload
9720 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9721 /// over a candidate in any candidate set.
9722 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9723                                unsigned NumArgs) {
9724   FunctionDecl *Fn = Cand->Function;
9725   unsigned MinParams = Fn->getMinRequiredArguments();
9726 
9727   // With invalid overloaded operators, it's possible that we think we
9728   // have an arity mismatch when in fact it looks like we have the
9729   // right number of arguments, because only overloaded operators have
9730   // the weird behavior of overloading member and non-member functions.
9731   // Just don't report anything.
9732   if (Fn->isInvalidDecl() &&
9733       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9734     return true;
9735 
9736   if (NumArgs < MinParams) {
9737     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9738            (Cand->FailureKind == ovl_fail_bad_deduction &&
9739             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9740   } else {
9741     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9742            (Cand->FailureKind == ovl_fail_bad_deduction &&
9743             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9744   }
9745 
9746   return false;
9747 }
9748 
9749 /// General arity mismatch diagnosis over a candidate in a candidate set.
9750 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9751                                   unsigned NumFormalArgs) {
9752   assert(isa<FunctionDecl>(D) &&
9753       "The templated declaration should at least be a function"
9754       " when diagnosing bad template argument deduction due to too many"
9755       " or too few arguments");
9756 
9757   FunctionDecl *Fn = cast<FunctionDecl>(D);
9758 
9759   // TODO: treat calls to a missing default constructor as a special case
9760   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9761   unsigned MinParams = Fn->getMinRequiredArguments();
9762 
9763   // at least / at most / exactly
9764   unsigned mode, modeCount;
9765   if (NumFormalArgs < MinParams) {
9766     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9767         FnTy->isTemplateVariadic())
9768       mode = 0; // "at least"
9769     else
9770       mode = 2; // "exactly"
9771     modeCount = MinParams;
9772   } else {
9773     if (MinParams != FnTy->getNumParams())
9774       mode = 1; // "at most"
9775     else
9776       mode = 2; // "exactly"
9777     modeCount = FnTy->getNumParams();
9778   }
9779 
9780   std::string Description;
9781   OverloadCandidateKind FnKind =
9782       ClassifyOverloadCandidate(S, Found, Fn, Description);
9783 
9784   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9785     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9786       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9787       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9788   else
9789     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9790       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9791       << mode << modeCount << NumFormalArgs;
9792   MaybeEmitInheritedConstructorNote(S, Found);
9793 }
9794 
9795 /// Arity mismatch diagnosis specific to a function overload candidate.
9796 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9797                                   unsigned NumFormalArgs) {
9798   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9799     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9800 }
9801 
9802 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9803   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9804     return TD;
9805   llvm_unreachable("Unsupported: Getting the described template declaration"
9806                    " for bad deduction diagnosis");
9807 }
9808 
9809 /// Diagnose a failed template-argument deduction.
9810 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9811                                  DeductionFailureInfo &DeductionFailure,
9812                                  unsigned NumArgs,
9813                                  bool TakingCandidateAddress) {
9814   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9815   NamedDecl *ParamD;
9816   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9817   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9818   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9819   switch (DeductionFailure.Result) {
9820   case Sema::TDK_Success:
9821     llvm_unreachable("TDK_success while diagnosing bad deduction");
9822 
9823   case Sema::TDK_Incomplete: {
9824     assert(ParamD && "no parameter found for incomplete deduction result");
9825     S.Diag(Templated->getLocation(),
9826            diag::note_ovl_candidate_incomplete_deduction)
9827         << ParamD->getDeclName();
9828     MaybeEmitInheritedConstructorNote(S, Found);
9829     return;
9830   }
9831 
9832   case Sema::TDK_Underqualified: {
9833     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9834     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9835 
9836     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9837 
9838     // Param will have been canonicalized, but it should just be a
9839     // qualified version of ParamD, so move the qualifiers to that.
9840     QualifierCollector Qs;
9841     Qs.strip(Param);
9842     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9843     assert(S.Context.hasSameType(Param, NonCanonParam));
9844 
9845     // Arg has also been canonicalized, but there's nothing we can do
9846     // about that.  It also doesn't matter as much, because it won't
9847     // have any template parameters in it (because deduction isn't
9848     // done on dependent types).
9849     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9850 
9851     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9852         << ParamD->getDeclName() << Arg << NonCanonParam;
9853     MaybeEmitInheritedConstructorNote(S, Found);
9854     return;
9855   }
9856 
9857   case Sema::TDK_Inconsistent: {
9858     assert(ParamD && "no parameter found for inconsistent deduction result");
9859     int which = 0;
9860     if (isa<TemplateTypeParmDecl>(ParamD))
9861       which = 0;
9862     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9863       // Deduction might have failed because we deduced arguments of two
9864       // different types for a non-type template parameter.
9865       // FIXME: Use a different TDK value for this.
9866       QualType T1 =
9867           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9868       QualType T2 =
9869           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9870       if (!S.Context.hasSameType(T1, T2)) {
9871         S.Diag(Templated->getLocation(),
9872                diag::note_ovl_candidate_inconsistent_deduction_types)
9873           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9874           << *DeductionFailure.getSecondArg() << T2;
9875         MaybeEmitInheritedConstructorNote(S, Found);
9876         return;
9877       }
9878 
9879       which = 1;
9880     } else {
9881       which = 2;
9882     }
9883 
9884     S.Diag(Templated->getLocation(),
9885            diag::note_ovl_candidate_inconsistent_deduction)
9886         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9887         << *DeductionFailure.getSecondArg();
9888     MaybeEmitInheritedConstructorNote(S, Found);
9889     return;
9890   }
9891 
9892   case Sema::TDK_InvalidExplicitArguments:
9893     assert(ParamD && "no parameter found for invalid explicit arguments");
9894     if (ParamD->getDeclName())
9895       S.Diag(Templated->getLocation(),
9896              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9897           << ParamD->getDeclName();
9898     else {
9899       int index = 0;
9900       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9901         index = TTP->getIndex();
9902       else if (NonTypeTemplateParmDecl *NTTP
9903                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9904         index = NTTP->getIndex();
9905       else
9906         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9907       S.Diag(Templated->getLocation(),
9908              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9909           << (index + 1);
9910     }
9911     MaybeEmitInheritedConstructorNote(S, Found);
9912     return;
9913 
9914   case Sema::TDK_TooManyArguments:
9915   case Sema::TDK_TooFewArguments:
9916     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9917     return;
9918 
9919   case Sema::TDK_InstantiationDepth:
9920     S.Diag(Templated->getLocation(),
9921            diag::note_ovl_candidate_instantiation_depth);
9922     MaybeEmitInheritedConstructorNote(S, Found);
9923     return;
9924 
9925   case Sema::TDK_SubstitutionFailure: {
9926     // Format the template argument list into the argument string.
9927     SmallString<128> TemplateArgString;
9928     if (TemplateArgumentList *Args =
9929             DeductionFailure.getTemplateArgumentList()) {
9930       TemplateArgString = " ";
9931       TemplateArgString += S.getTemplateArgumentBindingsText(
9932           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9933     }
9934 
9935     // If this candidate was disabled by enable_if, say so.
9936     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9937     if (PDiag && PDiag->second.getDiagID() ==
9938           diag::err_typename_nested_not_found_enable_if) {
9939       // FIXME: Use the source range of the condition, and the fully-qualified
9940       //        name of the enable_if template. These are both present in PDiag.
9941       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9942         << "'enable_if'" << TemplateArgString;
9943       return;
9944     }
9945 
9946     // We found a specific requirement that disabled the enable_if.
9947     if (PDiag && PDiag->second.getDiagID() ==
9948         diag::err_typename_nested_not_found_requirement) {
9949       S.Diag(Templated->getLocation(),
9950              diag::note_ovl_candidate_disabled_by_requirement)
9951         << PDiag->second.getStringArg(0) << TemplateArgString;
9952       return;
9953     }
9954 
9955     // Format the SFINAE diagnostic into the argument string.
9956     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9957     //        formatted message in another diagnostic.
9958     SmallString<128> SFINAEArgString;
9959     SourceRange R;
9960     if (PDiag) {
9961       SFINAEArgString = ": ";
9962       R = SourceRange(PDiag->first, PDiag->first);
9963       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9964     }
9965 
9966     S.Diag(Templated->getLocation(),
9967            diag::note_ovl_candidate_substitution_failure)
9968         << TemplateArgString << SFINAEArgString << R;
9969     MaybeEmitInheritedConstructorNote(S, Found);
9970     return;
9971   }
9972 
9973   case Sema::TDK_DeducedMismatch:
9974   case Sema::TDK_DeducedMismatchNested: {
9975     // Format the template argument list into the argument string.
9976     SmallString<128> TemplateArgString;
9977     if (TemplateArgumentList *Args =
9978             DeductionFailure.getTemplateArgumentList()) {
9979       TemplateArgString = " ";
9980       TemplateArgString += S.getTemplateArgumentBindingsText(
9981           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9982     }
9983 
9984     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9985         << (*DeductionFailure.getCallArgIndex() + 1)
9986         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9987         << TemplateArgString
9988         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9989     break;
9990   }
9991 
9992   case Sema::TDK_NonDeducedMismatch: {
9993     // FIXME: Provide a source location to indicate what we couldn't match.
9994     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9995     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9996     if (FirstTA.getKind() == TemplateArgument::Template &&
9997         SecondTA.getKind() == TemplateArgument::Template) {
9998       TemplateName FirstTN = FirstTA.getAsTemplate();
9999       TemplateName SecondTN = SecondTA.getAsTemplate();
10000       if (FirstTN.getKind() == TemplateName::Template &&
10001           SecondTN.getKind() == TemplateName::Template) {
10002         if (FirstTN.getAsTemplateDecl()->getName() ==
10003             SecondTN.getAsTemplateDecl()->getName()) {
10004           // FIXME: This fixes a bad diagnostic where both templates are named
10005           // the same.  This particular case is a bit difficult since:
10006           // 1) It is passed as a string to the diagnostic printer.
10007           // 2) The diagnostic printer only attempts to find a better
10008           //    name for types, not decls.
10009           // Ideally, this should folded into the diagnostic printer.
10010           S.Diag(Templated->getLocation(),
10011                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10012               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10013           return;
10014         }
10015       }
10016     }
10017 
10018     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10019         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10020       return;
10021 
10022     // FIXME: For generic lambda parameters, check if the function is a lambda
10023     // call operator, and if so, emit a prettier and more informative
10024     // diagnostic that mentions 'auto' and lambda in addition to
10025     // (or instead of?) the canonical template type parameters.
10026     S.Diag(Templated->getLocation(),
10027            diag::note_ovl_candidate_non_deduced_mismatch)
10028         << FirstTA << SecondTA;
10029     return;
10030   }
10031   // TODO: diagnose these individually, then kill off
10032   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10033   case Sema::TDK_MiscellaneousDeductionFailure:
10034     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10035     MaybeEmitInheritedConstructorNote(S, Found);
10036     return;
10037   case Sema::TDK_CUDATargetMismatch:
10038     S.Diag(Templated->getLocation(),
10039            diag::note_cuda_ovl_candidate_target_mismatch);
10040     return;
10041   }
10042 }
10043 
10044 /// Diagnose a failed template-argument deduction, for function calls.
10045 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10046                                  unsigned NumArgs,
10047                                  bool TakingCandidateAddress) {
10048   unsigned TDK = Cand->DeductionFailure.Result;
10049   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10050     if (CheckArityMismatch(S, Cand, NumArgs))
10051       return;
10052   }
10053   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10054                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10055 }
10056 
10057 /// CUDA: diagnose an invalid call across targets.
10058 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10059   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10060   FunctionDecl *Callee = Cand->Function;
10061 
10062   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10063                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10064 
10065   std::string FnDesc;
10066   OverloadCandidateKind FnKind =
10067       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10068 
10069   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10070       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10071 
10072   // This could be an implicit constructor for which we could not infer the
10073   // target due to a collsion. Diagnose that case.
10074   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10075   if (Meth != nullptr && Meth->isImplicit()) {
10076     CXXRecordDecl *ParentClass = Meth->getParent();
10077     Sema::CXXSpecialMember CSM;
10078 
10079     switch (FnKind) {
10080     default:
10081       return;
10082     case oc_implicit_default_constructor:
10083       CSM = Sema::CXXDefaultConstructor;
10084       break;
10085     case oc_implicit_copy_constructor:
10086       CSM = Sema::CXXCopyConstructor;
10087       break;
10088     case oc_implicit_move_constructor:
10089       CSM = Sema::CXXMoveConstructor;
10090       break;
10091     case oc_implicit_copy_assignment:
10092       CSM = Sema::CXXCopyAssignment;
10093       break;
10094     case oc_implicit_move_assignment:
10095       CSM = Sema::CXXMoveAssignment;
10096       break;
10097     };
10098 
10099     bool ConstRHS = false;
10100     if (Meth->getNumParams()) {
10101       if (const ReferenceType *RT =
10102               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10103         ConstRHS = RT->getPointeeType().isConstQualified();
10104       }
10105     }
10106 
10107     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10108                                               /* ConstRHS */ ConstRHS,
10109                                               /* Diagnose */ true);
10110   }
10111 }
10112 
10113 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10114   FunctionDecl *Callee = Cand->Function;
10115   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10116 
10117   S.Diag(Callee->getLocation(),
10118          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10119       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10120 }
10121 
10122 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10123   FunctionDecl *Callee = Cand->Function;
10124 
10125   S.Diag(Callee->getLocation(),
10126          diag::note_ovl_candidate_disabled_by_extension);
10127 }
10128 
10129 /// Generates a 'note' diagnostic for an overload candidate.  We've
10130 /// already generated a primary error at the call site.
10131 ///
10132 /// It really does need to be a single diagnostic with its caret
10133 /// pointed at the candidate declaration.  Yes, this creates some
10134 /// major challenges of technical writing.  Yes, this makes pointing
10135 /// out problems with specific arguments quite awkward.  It's still
10136 /// better than generating twenty screens of text for every failed
10137 /// overload.
10138 ///
10139 /// It would be great to be able to express per-candidate problems
10140 /// more richly for those diagnostic clients that cared, but we'd
10141 /// still have to be just as careful with the default diagnostics.
10142 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10143                                   unsigned NumArgs,
10144                                   bool TakingCandidateAddress) {
10145   FunctionDecl *Fn = Cand->Function;
10146 
10147   // Note deleted candidates, but only if they're viable.
10148   if (Cand->Viable) {
10149     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10150       std::string FnDesc;
10151       OverloadCandidateKind FnKind =
10152         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10153 
10154       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10155         << FnKind << FnDesc
10156         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10157       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10158       return;
10159     }
10160 
10161     // We don't really have anything else to say about viable candidates.
10162     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10163     return;
10164   }
10165 
10166   switch (Cand->FailureKind) {
10167   case ovl_fail_too_many_arguments:
10168   case ovl_fail_too_few_arguments:
10169     return DiagnoseArityMismatch(S, Cand, NumArgs);
10170 
10171   case ovl_fail_bad_deduction:
10172     return DiagnoseBadDeduction(S, Cand, NumArgs,
10173                                 TakingCandidateAddress);
10174 
10175   case ovl_fail_illegal_constructor: {
10176     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10177       << (Fn->getPrimaryTemplate() ? 1 : 0);
10178     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10179     return;
10180   }
10181 
10182   case ovl_fail_trivial_conversion:
10183   case ovl_fail_bad_final_conversion:
10184   case ovl_fail_final_conversion_not_exact:
10185     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10186 
10187   case ovl_fail_bad_conversion: {
10188     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10189     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10190       if (Cand->Conversions[I].isBad())
10191         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10192 
10193     // FIXME: this currently happens when we're called from SemaInit
10194     // when user-conversion overload fails.  Figure out how to handle
10195     // those conditions and diagnose them well.
10196     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10197   }
10198 
10199   case ovl_fail_bad_target:
10200     return DiagnoseBadTarget(S, Cand);
10201 
10202   case ovl_fail_enable_if:
10203     return DiagnoseFailedEnableIfAttr(S, Cand);
10204 
10205   case ovl_fail_ext_disabled:
10206     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10207 
10208   case ovl_fail_inhctor_slice:
10209     // It's generally not interesting to note copy/move constructors here.
10210     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10211       return;
10212     S.Diag(Fn->getLocation(),
10213            diag::note_ovl_candidate_inherited_constructor_slice)
10214       << (Fn->getPrimaryTemplate() ? 1 : 0)
10215       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10216     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10217     return;
10218 
10219   case ovl_fail_addr_not_available: {
10220     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10221     (void)Available;
10222     assert(!Available);
10223     break;
10224   }
10225   case ovl_non_default_multiversion_function:
10226     // Do nothing, these should simply be ignored.
10227     break;
10228   }
10229 }
10230 
10231 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10232   // Desugar the type of the surrogate down to a function type,
10233   // retaining as many typedefs as possible while still showing
10234   // the function type (and, therefore, its parameter types).
10235   QualType FnType = Cand->Surrogate->getConversionType();
10236   bool isLValueReference = false;
10237   bool isRValueReference = false;
10238   bool isPointer = false;
10239   if (const LValueReferenceType *FnTypeRef =
10240         FnType->getAs<LValueReferenceType>()) {
10241     FnType = FnTypeRef->getPointeeType();
10242     isLValueReference = true;
10243   } else if (const RValueReferenceType *FnTypeRef =
10244                FnType->getAs<RValueReferenceType>()) {
10245     FnType = FnTypeRef->getPointeeType();
10246     isRValueReference = true;
10247   }
10248   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10249     FnType = FnTypePtr->getPointeeType();
10250     isPointer = true;
10251   }
10252   // Desugar down to a function type.
10253   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10254   // Reconstruct the pointer/reference as appropriate.
10255   if (isPointer) FnType = S.Context.getPointerType(FnType);
10256   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10257   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10258 
10259   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10260     << FnType;
10261 }
10262 
10263 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10264                                          SourceLocation OpLoc,
10265                                          OverloadCandidate *Cand) {
10266   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10267   std::string TypeStr("operator");
10268   TypeStr += Opc;
10269   TypeStr += "(";
10270   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10271   if (Cand->Conversions.size() == 1) {
10272     TypeStr += ")";
10273     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10274   } else {
10275     TypeStr += ", ";
10276     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10277     TypeStr += ")";
10278     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10279   }
10280 }
10281 
10282 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10283                                          OverloadCandidate *Cand) {
10284   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10285     if (ICS.isBad()) break; // all meaningless after first invalid
10286     if (!ICS.isAmbiguous()) continue;
10287 
10288     ICS.DiagnoseAmbiguousConversion(
10289         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10290   }
10291 }
10292 
10293 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10294   if (Cand->Function)
10295     return Cand->Function->getLocation();
10296   if (Cand->IsSurrogate)
10297     return Cand->Surrogate->getLocation();
10298   return SourceLocation();
10299 }
10300 
10301 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10302   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10303   case Sema::TDK_Success:
10304   case Sema::TDK_NonDependentConversionFailure:
10305     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10306 
10307   case Sema::TDK_Invalid:
10308   case Sema::TDK_Incomplete:
10309     return 1;
10310 
10311   case Sema::TDK_Underqualified:
10312   case Sema::TDK_Inconsistent:
10313     return 2;
10314 
10315   case Sema::TDK_SubstitutionFailure:
10316   case Sema::TDK_DeducedMismatch:
10317   case Sema::TDK_DeducedMismatchNested:
10318   case Sema::TDK_NonDeducedMismatch:
10319   case Sema::TDK_MiscellaneousDeductionFailure:
10320   case Sema::TDK_CUDATargetMismatch:
10321     return 3;
10322 
10323   case Sema::TDK_InstantiationDepth:
10324     return 4;
10325 
10326   case Sema::TDK_InvalidExplicitArguments:
10327     return 5;
10328 
10329   case Sema::TDK_TooManyArguments:
10330   case Sema::TDK_TooFewArguments:
10331     return 6;
10332   }
10333   llvm_unreachable("Unhandled deduction result");
10334 }
10335 
10336 namespace {
10337 struct CompareOverloadCandidatesForDisplay {
10338   Sema &S;
10339   SourceLocation Loc;
10340   size_t NumArgs;
10341   OverloadCandidateSet::CandidateSetKind CSK;
10342 
10343   CompareOverloadCandidatesForDisplay(
10344       Sema &S, SourceLocation Loc, size_t NArgs,
10345       OverloadCandidateSet::CandidateSetKind CSK)
10346       : S(S), NumArgs(NArgs), CSK(CSK) {}
10347 
10348   bool operator()(const OverloadCandidate *L,
10349                   const OverloadCandidate *R) {
10350     // Fast-path this check.
10351     if (L == R) return false;
10352 
10353     // Order first by viability.
10354     if (L->Viable) {
10355       if (!R->Viable) return true;
10356 
10357       // TODO: introduce a tri-valued comparison for overload
10358       // candidates.  Would be more worthwhile if we had a sort
10359       // that could exploit it.
10360       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10361         return true;
10362       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10363         return false;
10364     } else if (R->Viable)
10365       return false;
10366 
10367     assert(L->Viable == R->Viable);
10368 
10369     // Criteria by which we can sort non-viable candidates:
10370     if (!L->Viable) {
10371       // 1. Arity mismatches come after other candidates.
10372       if (L->FailureKind == ovl_fail_too_many_arguments ||
10373           L->FailureKind == ovl_fail_too_few_arguments) {
10374         if (R->FailureKind == ovl_fail_too_many_arguments ||
10375             R->FailureKind == ovl_fail_too_few_arguments) {
10376           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10377           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10378           if (LDist == RDist) {
10379             if (L->FailureKind == R->FailureKind)
10380               // Sort non-surrogates before surrogates.
10381               return !L->IsSurrogate && R->IsSurrogate;
10382             // Sort candidates requiring fewer parameters than there were
10383             // arguments given after candidates requiring more parameters
10384             // than there were arguments given.
10385             return L->FailureKind == ovl_fail_too_many_arguments;
10386           }
10387           return LDist < RDist;
10388         }
10389         return false;
10390       }
10391       if (R->FailureKind == ovl_fail_too_many_arguments ||
10392           R->FailureKind == ovl_fail_too_few_arguments)
10393         return true;
10394 
10395       // 2. Bad conversions come first and are ordered by the number
10396       // of bad conversions and quality of good conversions.
10397       if (L->FailureKind == ovl_fail_bad_conversion) {
10398         if (R->FailureKind != ovl_fail_bad_conversion)
10399           return true;
10400 
10401         // The conversion that can be fixed with a smaller number of changes,
10402         // comes first.
10403         unsigned numLFixes = L->Fix.NumConversionsFixed;
10404         unsigned numRFixes = R->Fix.NumConversionsFixed;
10405         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10406         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10407         if (numLFixes != numRFixes) {
10408           return numLFixes < numRFixes;
10409         }
10410 
10411         // If there's any ordering between the defined conversions...
10412         // FIXME: this might not be transitive.
10413         assert(L->Conversions.size() == R->Conversions.size());
10414 
10415         int leftBetter = 0;
10416         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10417         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10418           switch (CompareImplicitConversionSequences(S, Loc,
10419                                                      L->Conversions[I],
10420                                                      R->Conversions[I])) {
10421           case ImplicitConversionSequence::Better:
10422             leftBetter++;
10423             break;
10424 
10425           case ImplicitConversionSequence::Worse:
10426             leftBetter--;
10427             break;
10428 
10429           case ImplicitConversionSequence::Indistinguishable:
10430             break;
10431           }
10432         }
10433         if (leftBetter > 0) return true;
10434         if (leftBetter < 0) return false;
10435 
10436       } else if (R->FailureKind == ovl_fail_bad_conversion)
10437         return false;
10438 
10439       if (L->FailureKind == ovl_fail_bad_deduction) {
10440         if (R->FailureKind != ovl_fail_bad_deduction)
10441           return true;
10442 
10443         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10444           return RankDeductionFailure(L->DeductionFailure)
10445                < RankDeductionFailure(R->DeductionFailure);
10446       } else if (R->FailureKind == ovl_fail_bad_deduction)
10447         return false;
10448 
10449       // TODO: others?
10450     }
10451 
10452     // Sort everything else by location.
10453     SourceLocation LLoc = GetLocationForCandidate(L);
10454     SourceLocation RLoc = GetLocationForCandidate(R);
10455 
10456     // Put candidates without locations (e.g. builtins) at the end.
10457     if (LLoc.isInvalid()) return false;
10458     if (RLoc.isInvalid()) return true;
10459 
10460     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10461   }
10462 };
10463 }
10464 
10465 /// CompleteNonViableCandidate - Normally, overload resolution only
10466 /// computes up to the first bad conversion. Produces the FixIt set if
10467 /// possible.
10468 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10469                                        ArrayRef<Expr *> Args) {
10470   assert(!Cand->Viable);
10471 
10472   // Don't do anything on failures other than bad conversion.
10473   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10474 
10475   // We only want the FixIts if all the arguments can be corrected.
10476   bool Unfixable = false;
10477   // Use a implicit copy initialization to check conversion fixes.
10478   Cand->Fix.setConversionChecker(TryCopyInitialization);
10479 
10480   // Attempt to fix the bad conversion.
10481   unsigned ConvCount = Cand->Conversions.size();
10482   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10483        ++ConvIdx) {
10484     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10485     if (Cand->Conversions[ConvIdx].isInitialized() &&
10486         Cand->Conversions[ConvIdx].isBad()) {
10487       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10488       break;
10489     }
10490   }
10491 
10492   // FIXME: this should probably be preserved from the overload
10493   // operation somehow.
10494   bool SuppressUserConversions = false;
10495 
10496   unsigned ConvIdx = 0;
10497   ArrayRef<QualType> ParamTypes;
10498 
10499   if (Cand->IsSurrogate) {
10500     QualType ConvType
10501       = Cand->Surrogate->getConversionType().getNonReferenceType();
10502     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10503       ConvType = ConvPtrType->getPointeeType();
10504     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10505     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10506     ConvIdx = 1;
10507   } else if (Cand->Function) {
10508     ParamTypes =
10509         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10510     if (isa<CXXMethodDecl>(Cand->Function) &&
10511         !isa<CXXConstructorDecl>(Cand->Function)) {
10512       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10513       ConvIdx = 1;
10514     }
10515   } else {
10516     // Builtin operator.
10517     assert(ConvCount <= 3);
10518     ParamTypes = Cand->BuiltinParamTypes;
10519   }
10520 
10521   // Fill in the rest of the conversions.
10522   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10523     if (Cand->Conversions[ConvIdx].isInitialized()) {
10524       // We've already checked this conversion.
10525     } else if (ArgIdx < ParamTypes.size()) {
10526       if (ParamTypes[ArgIdx]->isDependentType())
10527         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10528             Args[ArgIdx]->getType());
10529       else {
10530         Cand->Conversions[ConvIdx] =
10531             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10532                                   SuppressUserConversions,
10533                                   /*InOverloadResolution=*/true,
10534                                   /*AllowObjCWritebackConversion=*/
10535                                   S.getLangOpts().ObjCAutoRefCount);
10536         // Store the FixIt in the candidate if it exists.
10537         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10538           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10539       }
10540     } else
10541       Cand->Conversions[ConvIdx].setEllipsis();
10542   }
10543 }
10544 
10545 /// When overload resolution fails, prints diagnostic messages containing the
10546 /// candidates in the candidate set.
10547 void OverloadCandidateSet::NoteCandidates(
10548     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10549     StringRef Opc, SourceLocation OpLoc,
10550     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10551   // Sort the candidates by viability and position.  Sorting directly would
10552   // be prohibitive, so we make a set of pointers and sort those.
10553   SmallVector<OverloadCandidate*, 32> Cands;
10554   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10555   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10556     if (!Filter(*Cand))
10557       continue;
10558     if (Cand->Viable)
10559       Cands.push_back(Cand);
10560     else if (OCD == OCD_AllCandidates) {
10561       CompleteNonViableCandidate(S, Cand, Args);
10562       if (Cand->Function || Cand->IsSurrogate)
10563         Cands.push_back(Cand);
10564       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10565       // want to list every possible builtin candidate.
10566     }
10567   }
10568 
10569   std::stable_sort(Cands.begin(), Cands.end(),
10570             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10571 
10572   bool ReportedAmbiguousConversions = false;
10573 
10574   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10575   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10576   unsigned CandsShown = 0;
10577   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10578     OverloadCandidate *Cand = *I;
10579 
10580     // Set an arbitrary limit on the number of candidate functions we'll spam
10581     // the user with.  FIXME: This limit should depend on details of the
10582     // candidate list.
10583     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10584       break;
10585     }
10586     ++CandsShown;
10587 
10588     if (Cand->Function)
10589       NoteFunctionCandidate(S, Cand, Args.size(),
10590                             /*TakingCandidateAddress=*/false);
10591     else if (Cand->IsSurrogate)
10592       NoteSurrogateCandidate(S, Cand);
10593     else {
10594       assert(Cand->Viable &&
10595              "Non-viable built-in candidates are not added to Cands.");
10596       // Generally we only see ambiguities including viable builtin
10597       // operators if overload resolution got screwed up by an
10598       // ambiguous user-defined conversion.
10599       //
10600       // FIXME: It's quite possible for different conversions to see
10601       // different ambiguities, though.
10602       if (!ReportedAmbiguousConversions) {
10603         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10604         ReportedAmbiguousConversions = true;
10605       }
10606 
10607       // If this is a viable builtin, print it.
10608       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10609     }
10610   }
10611 
10612   if (I != E)
10613     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10614 }
10615 
10616 static SourceLocation
10617 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10618   return Cand->Specialization ? Cand->Specialization->getLocation()
10619                               : SourceLocation();
10620 }
10621 
10622 namespace {
10623 struct CompareTemplateSpecCandidatesForDisplay {
10624   Sema &S;
10625   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10626 
10627   bool operator()(const TemplateSpecCandidate *L,
10628                   const TemplateSpecCandidate *R) {
10629     // Fast-path this check.
10630     if (L == R)
10631       return false;
10632 
10633     // Assuming that both candidates are not matches...
10634 
10635     // Sort by the ranking of deduction failures.
10636     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10637       return RankDeductionFailure(L->DeductionFailure) <
10638              RankDeductionFailure(R->DeductionFailure);
10639 
10640     // Sort everything else by location.
10641     SourceLocation LLoc = GetLocationForCandidate(L);
10642     SourceLocation RLoc = GetLocationForCandidate(R);
10643 
10644     // Put candidates without locations (e.g. builtins) at the end.
10645     if (LLoc.isInvalid())
10646       return false;
10647     if (RLoc.isInvalid())
10648       return true;
10649 
10650     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10651   }
10652 };
10653 }
10654 
10655 /// Diagnose a template argument deduction failure.
10656 /// We are treating these failures as overload failures due to bad
10657 /// deductions.
10658 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10659                                                  bool ForTakingAddress) {
10660   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10661                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10662 }
10663 
10664 void TemplateSpecCandidateSet::destroyCandidates() {
10665   for (iterator i = begin(), e = end(); i != e; ++i) {
10666     i->DeductionFailure.Destroy();
10667   }
10668 }
10669 
10670 void TemplateSpecCandidateSet::clear() {
10671   destroyCandidates();
10672   Candidates.clear();
10673 }
10674 
10675 /// NoteCandidates - When no template specialization match is found, prints
10676 /// diagnostic messages containing the non-matching specializations that form
10677 /// the candidate set.
10678 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10679 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10680 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10681   // Sort the candidates by position (assuming no candidate is a match).
10682   // Sorting directly would be prohibitive, so we make a set of pointers
10683   // and sort those.
10684   SmallVector<TemplateSpecCandidate *, 32> Cands;
10685   Cands.reserve(size());
10686   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10687     if (Cand->Specialization)
10688       Cands.push_back(Cand);
10689     // Otherwise, this is a non-matching builtin candidate.  We do not,
10690     // in general, want to list every possible builtin candidate.
10691   }
10692 
10693   llvm::sort(Cands.begin(), Cands.end(),
10694              CompareTemplateSpecCandidatesForDisplay(S));
10695 
10696   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10697   // for generalization purposes (?).
10698   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10699 
10700   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10701   unsigned CandsShown = 0;
10702   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10703     TemplateSpecCandidate *Cand = *I;
10704 
10705     // Set an arbitrary limit on the number of candidates we'll spam
10706     // the user with.  FIXME: This limit should depend on details of the
10707     // candidate list.
10708     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10709       break;
10710     ++CandsShown;
10711 
10712     assert(Cand->Specialization &&
10713            "Non-matching built-in candidates are not added to Cands.");
10714     Cand->NoteDeductionFailure(S, ForTakingAddress);
10715   }
10716 
10717   if (I != E)
10718     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10719 }
10720 
10721 // [PossiblyAFunctionType]  -->   [Return]
10722 // NonFunctionType --> NonFunctionType
10723 // R (A) --> R(A)
10724 // R (*)(A) --> R (A)
10725 // R (&)(A) --> R (A)
10726 // R (S::*)(A) --> R (A)
10727 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10728   QualType Ret = PossiblyAFunctionType;
10729   if (const PointerType *ToTypePtr =
10730     PossiblyAFunctionType->getAs<PointerType>())
10731     Ret = ToTypePtr->getPointeeType();
10732   else if (const ReferenceType *ToTypeRef =
10733     PossiblyAFunctionType->getAs<ReferenceType>())
10734     Ret = ToTypeRef->getPointeeType();
10735   else if (const MemberPointerType *MemTypePtr =
10736     PossiblyAFunctionType->getAs<MemberPointerType>())
10737     Ret = MemTypePtr->getPointeeType();
10738   Ret =
10739     Context.getCanonicalType(Ret).getUnqualifiedType();
10740   return Ret;
10741 }
10742 
10743 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10744                                  bool Complain = true) {
10745   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10746       S.DeduceReturnType(FD, Loc, Complain))
10747     return true;
10748 
10749   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10750   if (S.getLangOpts().CPlusPlus17 &&
10751       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10752       !S.ResolveExceptionSpec(Loc, FPT))
10753     return true;
10754 
10755   return false;
10756 }
10757 
10758 namespace {
10759 // A helper class to help with address of function resolution
10760 // - allows us to avoid passing around all those ugly parameters
10761 class AddressOfFunctionResolver {
10762   Sema& S;
10763   Expr* SourceExpr;
10764   const QualType& TargetType;
10765   QualType TargetFunctionType; // Extracted function type from target type
10766 
10767   bool Complain;
10768   //DeclAccessPair& ResultFunctionAccessPair;
10769   ASTContext& Context;
10770 
10771   bool TargetTypeIsNonStaticMemberFunction;
10772   bool FoundNonTemplateFunction;
10773   bool StaticMemberFunctionFromBoundPointer;
10774   bool HasComplained;
10775 
10776   OverloadExpr::FindResult OvlExprInfo;
10777   OverloadExpr *OvlExpr;
10778   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10779   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10780   TemplateSpecCandidateSet FailedCandidates;
10781 
10782 public:
10783   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10784                             const QualType &TargetType, bool Complain)
10785       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10786         Complain(Complain), Context(S.getASTContext()),
10787         TargetTypeIsNonStaticMemberFunction(
10788             !!TargetType->getAs<MemberPointerType>()),
10789         FoundNonTemplateFunction(false),
10790         StaticMemberFunctionFromBoundPointer(false),
10791         HasComplained(false),
10792         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10793         OvlExpr(OvlExprInfo.Expression),
10794         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10795     ExtractUnqualifiedFunctionTypeFromTargetType();
10796 
10797     if (TargetFunctionType->isFunctionType()) {
10798       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10799         if (!UME->isImplicitAccess() &&
10800             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10801           StaticMemberFunctionFromBoundPointer = true;
10802     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10803       DeclAccessPair dap;
10804       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10805               OvlExpr, false, &dap)) {
10806         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10807           if (!Method->isStatic()) {
10808             // If the target type is a non-function type and the function found
10809             // is a non-static member function, pretend as if that was the
10810             // target, it's the only possible type to end up with.
10811             TargetTypeIsNonStaticMemberFunction = true;
10812 
10813             // And skip adding the function if its not in the proper form.
10814             // We'll diagnose this due to an empty set of functions.
10815             if (!OvlExprInfo.HasFormOfMemberPointer)
10816               return;
10817           }
10818 
10819         Matches.push_back(std::make_pair(dap, Fn));
10820       }
10821       return;
10822     }
10823 
10824     if (OvlExpr->hasExplicitTemplateArgs())
10825       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10826 
10827     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10828       // C++ [over.over]p4:
10829       //   If more than one function is selected, [...]
10830       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10831         if (FoundNonTemplateFunction)
10832           EliminateAllTemplateMatches();
10833         else
10834           EliminateAllExceptMostSpecializedTemplate();
10835       }
10836     }
10837 
10838     if (S.getLangOpts().CUDA && Matches.size() > 1)
10839       EliminateSuboptimalCudaMatches();
10840   }
10841 
10842   bool hasComplained() const { return HasComplained; }
10843 
10844 private:
10845   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10846     QualType Discard;
10847     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10848            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10849   }
10850 
10851   /// \return true if A is considered a better overload candidate for the
10852   /// desired type than B.
10853   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10854     // If A doesn't have exactly the correct type, we don't want to classify it
10855     // as "better" than anything else. This way, the user is required to
10856     // disambiguate for us if there are multiple candidates and no exact match.
10857     return candidateHasExactlyCorrectType(A) &&
10858            (!candidateHasExactlyCorrectType(B) ||
10859             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10860   }
10861 
10862   /// \return true if we were able to eliminate all but one overload candidate,
10863   /// false otherwise.
10864   bool eliminiateSuboptimalOverloadCandidates() {
10865     // Same algorithm as overload resolution -- one pass to pick the "best",
10866     // another pass to be sure that nothing is better than the best.
10867     auto Best = Matches.begin();
10868     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10869       if (isBetterCandidate(I->second, Best->second))
10870         Best = I;
10871 
10872     const FunctionDecl *BestFn = Best->second;
10873     auto IsBestOrInferiorToBest = [this, BestFn](
10874         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10875       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10876     };
10877 
10878     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10879     // option, so we can potentially give the user a better error
10880     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10881       return false;
10882     Matches[0] = *Best;
10883     Matches.resize(1);
10884     return true;
10885   }
10886 
10887   bool isTargetTypeAFunction() const {
10888     return TargetFunctionType->isFunctionType();
10889   }
10890 
10891   // [ToType]     [Return]
10892 
10893   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10894   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10895   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10896   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10897     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10898   }
10899 
10900   // return true if any matching specializations were found
10901   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10902                                    const DeclAccessPair& CurAccessFunPair) {
10903     if (CXXMethodDecl *Method
10904               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10905       // Skip non-static function templates when converting to pointer, and
10906       // static when converting to member pointer.
10907       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10908         return false;
10909     }
10910     else if (TargetTypeIsNonStaticMemberFunction)
10911       return false;
10912 
10913     // C++ [over.over]p2:
10914     //   If the name is a function template, template argument deduction is
10915     //   done (14.8.2.2), and if the argument deduction succeeds, the
10916     //   resulting template argument list is used to generate a single
10917     //   function template specialization, which is added to the set of
10918     //   overloaded functions considered.
10919     FunctionDecl *Specialization = nullptr;
10920     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10921     if (Sema::TemplateDeductionResult Result
10922           = S.DeduceTemplateArguments(FunctionTemplate,
10923                                       &OvlExplicitTemplateArgs,
10924                                       TargetFunctionType, Specialization,
10925                                       Info, /*IsAddressOfFunction*/true)) {
10926       // Make a note of the failed deduction for diagnostics.
10927       FailedCandidates.addCandidate()
10928           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10929                MakeDeductionFailureInfo(Context, Result, Info));
10930       return false;
10931     }
10932 
10933     // Template argument deduction ensures that we have an exact match or
10934     // compatible pointer-to-function arguments that would be adjusted by ICS.
10935     // This function template specicalization works.
10936     assert(S.isSameOrCompatibleFunctionType(
10937               Context.getCanonicalType(Specialization->getType()),
10938               Context.getCanonicalType(TargetFunctionType)));
10939 
10940     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10941       return false;
10942 
10943     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10944     return true;
10945   }
10946 
10947   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10948                                       const DeclAccessPair& CurAccessFunPair) {
10949     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10950       // Skip non-static functions when converting to pointer, and static
10951       // when converting to member pointer.
10952       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10953         return false;
10954     }
10955     else if (TargetTypeIsNonStaticMemberFunction)
10956       return false;
10957 
10958     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10959       if (S.getLangOpts().CUDA)
10960         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10961           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10962             return false;
10963       if (FunDecl->isMultiVersion()) {
10964         const auto *TA = FunDecl->getAttr<TargetAttr>();
10965         assert(TA && "Multiversioned functions require a target attribute");
10966         if (!TA->isDefaultVersion())
10967           return false;
10968       }
10969 
10970       // If any candidate has a placeholder return type, trigger its deduction
10971       // now.
10972       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10973                                Complain)) {
10974         HasComplained |= Complain;
10975         return false;
10976       }
10977 
10978       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10979         return false;
10980 
10981       // If we're in C, we need to support types that aren't exactly identical.
10982       if (!S.getLangOpts().CPlusPlus ||
10983           candidateHasExactlyCorrectType(FunDecl)) {
10984         Matches.push_back(std::make_pair(
10985             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10986         FoundNonTemplateFunction = true;
10987         return true;
10988       }
10989     }
10990 
10991     return false;
10992   }
10993 
10994   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10995     bool Ret = false;
10996 
10997     // If the overload expression doesn't have the form of a pointer to
10998     // member, don't try to convert it to a pointer-to-member type.
10999     if (IsInvalidFormOfPointerToMemberFunction())
11000       return false;
11001 
11002     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11003                                E = OvlExpr->decls_end();
11004          I != E; ++I) {
11005       // Look through any using declarations to find the underlying function.
11006       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11007 
11008       // C++ [over.over]p3:
11009       //   Non-member functions and static member functions match
11010       //   targets of type "pointer-to-function" or "reference-to-function."
11011       //   Nonstatic member functions match targets of
11012       //   type "pointer-to-member-function."
11013       // Note that according to DR 247, the containing class does not matter.
11014       if (FunctionTemplateDecl *FunctionTemplate
11015                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11016         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11017           Ret = true;
11018       }
11019       // If we have explicit template arguments supplied, skip non-templates.
11020       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11021                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11022         Ret = true;
11023     }
11024     assert(Ret || Matches.empty());
11025     return Ret;
11026   }
11027 
11028   void EliminateAllExceptMostSpecializedTemplate() {
11029     //   [...] and any given function template specialization F1 is
11030     //   eliminated if the set contains a second function template
11031     //   specialization whose function template is more specialized
11032     //   than the function template of F1 according to the partial
11033     //   ordering rules of 14.5.5.2.
11034 
11035     // The algorithm specified above is quadratic. We instead use a
11036     // two-pass algorithm (similar to the one used to identify the
11037     // best viable function in an overload set) that identifies the
11038     // best function template (if it exists).
11039 
11040     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11041     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11042       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11043 
11044     // TODO: It looks like FailedCandidates does not serve much purpose
11045     // here, since the no_viable diagnostic has index 0.
11046     UnresolvedSetIterator Result = S.getMostSpecialized(
11047         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11048         SourceExpr->getLocStart(), S.PDiag(),
11049         S.PDiag(diag::err_addr_ovl_ambiguous)
11050           << Matches[0].second->getDeclName(),
11051         S.PDiag(diag::note_ovl_candidate)
11052           << (unsigned)oc_function_template,
11053         Complain, TargetFunctionType);
11054 
11055     if (Result != MatchesCopy.end()) {
11056       // Make it the first and only element
11057       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11058       Matches[0].second = cast<FunctionDecl>(*Result);
11059       Matches.resize(1);
11060     } else
11061       HasComplained |= Complain;
11062   }
11063 
11064   void EliminateAllTemplateMatches() {
11065     //   [...] any function template specializations in the set are
11066     //   eliminated if the set also contains a non-template function, [...]
11067     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11068       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11069         ++I;
11070       else {
11071         Matches[I] = Matches[--N];
11072         Matches.resize(N);
11073       }
11074     }
11075   }
11076 
11077   void EliminateSuboptimalCudaMatches() {
11078     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11079   }
11080 
11081 public:
11082   void ComplainNoMatchesFound() const {
11083     assert(Matches.empty());
11084     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11085         << OvlExpr->getName() << TargetFunctionType
11086         << OvlExpr->getSourceRange();
11087     if (FailedCandidates.empty())
11088       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11089                                   /*TakingAddress=*/true);
11090     else {
11091       // We have some deduction failure messages. Use them to diagnose
11092       // the function templates, and diagnose the non-template candidates
11093       // normally.
11094       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11095                                  IEnd = OvlExpr->decls_end();
11096            I != IEnd; ++I)
11097         if (FunctionDecl *Fun =
11098                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11099           if (!functionHasPassObjectSizeParams(Fun))
11100             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11101                                     /*TakingAddress=*/true);
11102       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11103     }
11104   }
11105 
11106   bool IsInvalidFormOfPointerToMemberFunction() const {
11107     return TargetTypeIsNonStaticMemberFunction &&
11108       !OvlExprInfo.HasFormOfMemberPointer;
11109   }
11110 
11111   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11112       // TODO: Should we condition this on whether any functions might
11113       // have matched, or is it more appropriate to do that in callers?
11114       // TODO: a fixit wouldn't hurt.
11115       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11116         << TargetType << OvlExpr->getSourceRange();
11117   }
11118 
11119   bool IsStaticMemberFunctionFromBoundPointer() const {
11120     return StaticMemberFunctionFromBoundPointer;
11121   }
11122 
11123   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11124     S.Diag(OvlExpr->getLocStart(),
11125            diag::err_invalid_form_pointer_member_function)
11126       << OvlExpr->getSourceRange();
11127   }
11128 
11129   void ComplainOfInvalidConversion() const {
11130     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11131       << OvlExpr->getName() << TargetType;
11132   }
11133 
11134   void ComplainMultipleMatchesFound() const {
11135     assert(Matches.size() > 1);
11136     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11137       << OvlExpr->getName()
11138       << OvlExpr->getSourceRange();
11139     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11140                                 /*TakingAddress=*/true);
11141   }
11142 
11143   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11144 
11145   int getNumMatches() const { return Matches.size(); }
11146 
11147   FunctionDecl* getMatchingFunctionDecl() const {
11148     if (Matches.size() != 1) return nullptr;
11149     return Matches[0].second;
11150   }
11151 
11152   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11153     if (Matches.size() != 1) return nullptr;
11154     return &Matches[0].first;
11155   }
11156 };
11157 }
11158 
11159 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11160 /// an overloaded function (C++ [over.over]), where @p From is an
11161 /// expression with overloaded function type and @p ToType is the type
11162 /// we're trying to resolve to. For example:
11163 ///
11164 /// @code
11165 /// int f(double);
11166 /// int f(int);
11167 ///
11168 /// int (*pfd)(double) = f; // selects f(double)
11169 /// @endcode
11170 ///
11171 /// This routine returns the resulting FunctionDecl if it could be
11172 /// resolved, and NULL otherwise. When @p Complain is true, this
11173 /// routine will emit diagnostics if there is an error.
11174 FunctionDecl *
11175 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11176                                          QualType TargetType,
11177                                          bool Complain,
11178                                          DeclAccessPair &FoundResult,
11179                                          bool *pHadMultipleCandidates) {
11180   assert(AddressOfExpr->getType() == Context.OverloadTy);
11181 
11182   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11183                                      Complain);
11184   int NumMatches = Resolver.getNumMatches();
11185   FunctionDecl *Fn = nullptr;
11186   bool ShouldComplain = Complain && !Resolver.hasComplained();
11187   if (NumMatches == 0 && ShouldComplain) {
11188     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11189       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11190     else
11191       Resolver.ComplainNoMatchesFound();
11192   }
11193   else if (NumMatches > 1 && ShouldComplain)
11194     Resolver.ComplainMultipleMatchesFound();
11195   else if (NumMatches == 1) {
11196     Fn = Resolver.getMatchingFunctionDecl();
11197     assert(Fn);
11198     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11199       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11200     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11201     if (Complain) {
11202       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11203         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11204       else
11205         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11206     }
11207   }
11208 
11209   if (pHadMultipleCandidates)
11210     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11211   return Fn;
11212 }
11213 
11214 /// \brief Given an expression that refers to an overloaded function, try to
11215 /// resolve that function to a single function that can have its address taken.
11216 /// This will modify `Pair` iff it returns non-null.
11217 ///
11218 /// This routine can only realistically succeed if all but one candidates in the
11219 /// overload set for SrcExpr cannot have their addresses taken.
11220 FunctionDecl *
11221 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11222                                                   DeclAccessPair &Pair) {
11223   OverloadExpr::FindResult R = OverloadExpr::find(E);
11224   OverloadExpr *Ovl = R.Expression;
11225   FunctionDecl *Result = nullptr;
11226   DeclAccessPair DAP;
11227   // Don't use the AddressOfResolver because we're specifically looking for
11228   // cases where we have one overload candidate that lacks
11229   // enable_if/pass_object_size/...
11230   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11231     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11232     if (!FD)
11233       return nullptr;
11234 
11235     if (!checkAddressOfFunctionIsAvailable(FD))
11236       continue;
11237 
11238     // We have more than one result; quit.
11239     if (Result)
11240       return nullptr;
11241     DAP = I.getPair();
11242     Result = FD;
11243   }
11244 
11245   if (Result)
11246     Pair = DAP;
11247   return Result;
11248 }
11249 
11250 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11251 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11252 /// will perform access checks, diagnose the use of the resultant decl, and, if
11253 /// requested, potentially perform a function-to-pointer decay.
11254 ///
11255 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11256 /// Otherwise, returns true. This may emit diagnostics and return true.
11257 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11258     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11259   Expr *E = SrcExpr.get();
11260   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11261 
11262   DeclAccessPair DAP;
11263   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11264   if (!Found)
11265     return false;
11266 
11267   // Emitting multiple diagnostics for a function that is both inaccessible and
11268   // unavailable is consistent with our behavior elsewhere. So, always check
11269   // for both.
11270   DiagnoseUseOfDecl(Found, E->getExprLoc());
11271   CheckAddressOfMemberAccess(E, DAP);
11272   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11273   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11274     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11275   else
11276     SrcExpr = Fixed;
11277   return true;
11278 }
11279 
11280 /// \brief Given an expression that refers to an overloaded function, try to
11281 /// resolve that overloaded function expression down to a single function.
11282 ///
11283 /// This routine can only resolve template-ids that refer to a single function
11284 /// template, where that template-id refers to a single template whose template
11285 /// arguments are either provided by the template-id or have defaults,
11286 /// as described in C++0x [temp.arg.explicit]p3.
11287 ///
11288 /// If no template-ids are found, no diagnostics are emitted and NULL is
11289 /// returned.
11290 FunctionDecl *
11291 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11292                                                   bool Complain,
11293                                                   DeclAccessPair *FoundResult) {
11294   // C++ [over.over]p1:
11295   //   [...] [Note: any redundant set of parentheses surrounding the
11296   //   overloaded function name is ignored (5.1). ]
11297   // C++ [over.over]p1:
11298   //   [...] The overloaded function name can be preceded by the &
11299   //   operator.
11300 
11301   // If we didn't actually find any template-ids, we're done.
11302   if (!ovl->hasExplicitTemplateArgs())
11303     return nullptr;
11304 
11305   TemplateArgumentListInfo ExplicitTemplateArgs;
11306   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11307   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11308 
11309   // Look through all of the overloaded functions, searching for one
11310   // whose type matches exactly.
11311   FunctionDecl *Matched = nullptr;
11312   for (UnresolvedSetIterator I = ovl->decls_begin(),
11313          E = ovl->decls_end(); I != E; ++I) {
11314     // C++0x [temp.arg.explicit]p3:
11315     //   [...] In contexts where deduction is done and fails, or in contexts
11316     //   where deduction is not done, if a template argument list is
11317     //   specified and it, along with any default template arguments,
11318     //   identifies a single function template specialization, then the
11319     //   template-id is an lvalue for the function template specialization.
11320     FunctionTemplateDecl *FunctionTemplate
11321       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11322 
11323     // C++ [over.over]p2:
11324     //   If the name is a function template, template argument deduction is
11325     //   done (14.8.2.2), and if the argument deduction succeeds, the
11326     //   resulting template argument list is used to generate a single
11327     //   function template specialization, which is added to the set of
11328     //   overloaded functions considered.
11329     FunctionDecl *Specialization = nullptr;
11330     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11331     if (TemplateDeductionResult Result
11332           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11333                                     Specialization, Info,
11334                                     /*IsAddressOfFunction*/true)) {
11335       // Make a note of the failed deduction for diagnostics.
11336       // TODO: Actually use the failed-deduction info?
11337       FailedCandidates.addCandidate()
11338           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11339                MakeDeductionFailureInfo(Context, Result, Info));
11340       continue;
11341     }
11342 
11343     assert(Specialization && "no specialization and no error?");
11344 
11345     // Multiple matches; we can't resolve to a single declaration.
11346     if (Matched) {
11347       if (Complain) {
11348         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11349           << ovl->getName();
11350         NoteAllOverloadCandidates(ovl);
11351       }
11352       return nullptr;
11353     }
11354 
11355     Matched = Specialization;
11356     if (FoundResult) *FoundResult = I.getPair();
11357   }
11358 
11359   if (Matched &&
11360       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11361     return nullptr;
11362 
11363   return Matched;
11364 }
11365 
11366 // Resolve and fix an overloaded expression that can be resolved
11367 // because it identifies a single function template specialization.
11368 //
11369 // Last three arguments should only be supplied if Complain = true
11370 //
11371 // Return true if it was logically possible to so resolve the
11372 // expression, regardless of whether or not it succeeded.  Always
11373 // returns true if 'complain' is set.
11374 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11375                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11376                       bool complain, SourceRange OpRangeForComplaining,
11377                                            QualType DestTypeForComplaining,
11378                                             unsigned DiagIDForComplaining) {
11379   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11380 
11381   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11382 
11383   DeclAccessPair found;
11384   ExprResult SingleFunctionExpression;
11385   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11386                            ovl.Expression, /*complain*/ false, &found)) {
11387     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11388       SrcExpr = ExprError();
11389       return true;
11390     }
11391 
11392     // It is only correct to resolve to an instance method if we're
11393     // resolving a form that's permitted to be a pointer to member.
11394     // Otherwise we'll end up making a bound member expression, which
11395     // is illegal in all the contexts we resolve like this.
11396     if (!ovl.HasFormOfMemberPointer &&
11397         isa<CXXMethodDecl>(fn) &&
11398         cast<CXXMethodDecl>(fn)->isInstance()) {
11399       if (!complain) return false;
11400 
11401       Diag(ovl.Expression->getExprLoc(),
11402            diag::err_bound_member_function)
11403         << 0 << ovl.Expression->getSourceRange();
11404 
11405       // TODO: I believe we only end up here if there's a mix of
11406       // static and non-static candidates (otherwise the expression
11407       // would have 'bound member' type, not 'overload' type).
11408       // Ideally we would note which candidate was chosen and why
11409       // the static candidates were rejected.
11410       SrcExpr = ExprError();
11411       return true;
11412     }
11413 
11414     // Fix the expression to refer to 'fn'.
11415     SingleFunctionExpression =
11416         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11417 
11418     // If desired, do function-to-pointer decay.
11419     if (doFunctionPointerConverion) {
11420       SingleFunctionExpression =
11421         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11422       if (SingleFunctionExpression.isInvalid()) {
11423         SrcExpr = ExprError();
11424         return true;
11425       }
11426     }
11427   }
11428 
11429   if (!SingleFunctionExpression.isUsable()) {
11430     if (complain) {
11431       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11432         << ovl.Expression->getName()
11433         << DestTypeForComplaining
11434         << OpRangeForComplaining
11435         << ovl.Expression->getQualifierLoc().getSourceRange();
11436       NoteAllOverloadCandidates(SrcExpr.get());
11437 
11438       SrcExpr = ExprError();
11439       return true;
11440     }
11441 
11442     return false;
11443   }
11444 
11445   SrcExpr = SingleFunctionExpression;
11446   return true;
11447 }
11448 
11449 /// \brief Add a single candidate to the overload set.
11450 static void AddOverloadedCallCandidate(Sema &S,
11451                                        DeclAccessPair FoundDecl,
11452                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11453                                        ArrayRef<Expr *> Args,
11454                                        OverloadCandidateSet &CandidateSet,
11455                                        bool PartialOverloading,
11456                                        bool KnownValid) {
11457   NamedDecl *Callee = FoundDecl.getDecl();
11458   if (isa<UsingShadowDecl>(Callee))
11459     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11460 
11461   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11462     if (ExplicitTemplateArgs) {
11463       assert(!KnownValid && "Explicit template arguments?");
11464       return;
11465     }
11466     // Prevent ill-formed function decls to be added as overload candidates.
11467     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11468       return;
11469 
11470     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11471                            /*SuppressUsedConversions=*/false,
11472                            PartialOverloading);
11473     return;
11474   }
11475 
11476   if (FunctionTemplateDecl *FuncTemplate
11477       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11478     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11479                                    ExplicitTemplateArgs, Args, CandidateSet,
11480                                    /*SuppressUsedConversions=*/false,
11481                                    PartialOverloading);
11482     return;
11483   }
11484 
11485   assert(!KnownValid && "unhandled case in overloaded call candidate");
11486 }
11487 
11488 /// \brief Add the overload candidates named by callee and/or found by argument
11489 /// dependent lookup to the given overload set.
11490 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11491                                        ArrayRef<Expr *> Args,
11492                                        OverloadCandidateSet &CandidateSet,
11493                                        bool PartialOverloading) {
11494 
11495 #ifndef NDEBUG
11496   // Verify that ArgumentDependentLookup is consistent with the rules
11497   // in C++0x [basic.lookup.argdep]p3:
11498   //
11499   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11500   //   and let Y be the lookup set produced by argument dependent
11501   //   lookup (defined as follows). If X contains
11502   //
11503   //     -- a declaration of a class member, or
11504   //
11505   //     -- a block-scope function declaration that is not a
11506   //        using-declaration, or
11507   //
11508   //     -- a declaration that is neither a function or a function
11509   //        template
11510   //
11511   //   then Y is empty.
11512 
11513   if (ULE->requiresADL()) {
11514     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11515            E = ULE->decls_end(); I != E; ++I) {
11516       assert(!(*I)->getDeclContext()->isRecord());
11517       assert(isa<UsingShadowDecl>(*I) ||
11518              !(*I)->getDeclContext()->isFunctionOrMethod());
11519       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11520     }
11521   }
11522 #endif
11523 
11524   // It would be nice to avoid this copy.
11525   TemplateArgumentListInfo TABuffer;
11526   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11527   if (ULE->hasExplicitTemplateArgs()) {
11528     ULE->copyTemplateArgumentsInto(TABuffer);
11529     ExplicitTemplateArgs = &TABuffer;
11530   }
11531 
11532   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11533          E = ULE->decls_end(); I != E; ++I)
11534     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11535                                CandidateSet, PartialOverloading,
11536                                /*KnownValid*/ true);
11537 
11538   if (ULE->requiresADL())
11539     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11540                                          Args, ExplicitTemplateArgs,
11541                                          CandidateSet, PartialOverloading);
11542 }
11543 
11544 /// Determine whether a declaration with the specified name could be moved into
11545 /// a different namespace.
11546 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11547   switch (Name.getCXXOverloadedOperator()) {
11548   case OO_New: case OO_Array_New:
11549   case OO_Delete: case OO_Array_Delete:
11550     return false;
11551 
11552   default:
11553     return true;
11554   }
11555 }
11556 
11557 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11558 /// template, where the non-dependent name was declared after the template
11559 /// was defined. This is common in code written for a compilers which do not
11560 /// correctly implement two-stage name lookup.
11561 ///
11562 /// Returns true if a viable candidate was found and a diagnostic was issued.
11563 static bool
11564 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11565                        const CXXScopeSpec &SS, LookupResult &R,
11566                        OverloadCandidateSet::CandidateSetKind CSK,
11567                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11568                        ArrayRef<Expr *> Args,
11569                        bool *DoDiagnoseEmptyLookup = nullptr) {
11570   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11571     return false;
11572 
11573   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11574     if (DC->isTransparentContext())
11575       continue;
11576 
11577     SemaRef.LookupQualifiedName(R, DC);
11578 
11579     if (!R.empty()) {
11580       R.suppressDiagnostics();
11581 
11582       if (isa<CXXRecordDecl>(DC)) {
11583         // Don't diagnose names we find in classes; we get much better
11584         // diagnostics for these from DiagnoseEmptyLookup.
11585         R.clear();
11586         if (DoDiagnoseEmptyLookup)
11587           *DoDiagnoseEmptyLookup = true;
11588         return false;
11589       }
11590 
11591       OverloadCandidateSet Candidates(FnLoc, CSK);
11592       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11593         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11594                                    ExplicitTemplateArgs, Args,
11595                                    Candidates, false, /*KnownValid*/ false);
11596 
11597       OverloadCandidateSet::iterator Best;
11598       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11599         // No viable functions. Don't bother the user with notes for functions
11600         // which don't work and shouldn't be found anyway.
11601         R.clear();
11602         return false;
11603       }
11604 
11605       // Find the namespaces where ADL would have looked, and suggest
11606       // declaring the function there instead.
11607       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11608       Sema::AssociatedClassSet AssociatedClasses;
11609       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11610                                                  AssociatedNamespaces,
11611                                                  AssociatedClasses);
11612       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11613       if (canBeDeclaredInNamespace(R.getLookupName())) {
11614         DeclContext *Std = SemaRef.getStdNamespace();
11615         for (Sema::AssociatedNamespaceSet::iterator
11616                it = AssociatedNamespaces.begin(),
11617                end = AssociatedNamespaces.end(); it != end; ++it) {
11618           // Never suggest declaring a function within namespace 'std'.
11619           if (Std && Std->Encloses(*it))
11620             continue;
11621 
11622           // Never suggest declaring a function within a namespace with a
11623           // reserved name, like __gnu_cxx.
11624           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11625           if (NS &&
11626               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11627             continue;
11628 
11629           SuggestedNamespaces.insert(*it);
11630         }
11631       }
11632 
11633       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11634         << R.getLookupName();
11635       if (SuggestedNamespaces.empty()) {
11636         SemaRef.Diag(Best->Function->getLocation(),
11637                      diag::note_not_found_by_two_phase_lookup)
11638           << R.getLookupName() << 0;
11639       } else if (SuggestedNamespaces.size() == 1) {
11640         SemaRef.Diag(Best->Function->getLocation(),
11641                      diag::note_not_found_by_two_phase_lookup)
11642           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11643       } else {
11644         // FIXME: It would be useful to list the associated namespaces here,
11645         // but the diagnostics infrastructure doesn't provide a way to produce
11646         // a localized representation of a list of items.
11647         SemaRef.Diag(Best->Function->getLocation(),
11648                      diag::note_not_found_by_two_phase_lookup)
11649           << R.getLookupName() << 2;
11650       }
11651 
11652       // Try to recover by calling this function.
11653       return true;
11654     }
11655 
11656     R.clear();
11657   }
11658 
11659   return false;
11660 }
11661 
11662 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11663 /// template, where the non-dependent operator was declared after the template
11664 /// was defined.
11665 ///
11666 /// Returns true if a viable candidate was found and a diagnostic was issued.
11667 static bool
11668 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11669                                SourceLocation OpLoc,
11670                                ArrayRef<Expr *> Args) {
11671   DeclarationName OpName =
11672     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11673   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11674   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11675                                 OverloadCandidateSet::CSK_Operator,
11676                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11677 }
11678 
11679 namespace {
11680 class BuildRecoveryCallExprRAII {
11681   Sema &SemaRef;
11682 public:
11683   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11684     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11685     SemaRef.IsBuildingRecoveryCallExpr = true;
11686   }
11687 
11688   ~BuildRecoveryCallExprRAII() {
11689     SemaRef.IsBuildingRecoveryCallExpr = false;
11690   }
11691 };
11692 
11693 }
11694 
11695 static std::unique_ptr<CorrectionCandidateCallback>
11696 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11697               bool HasTemplateArgs, bool AllowTypoCorrection) {
11698   if (!AllowTypoCorrection)
11699     return llvm::make_unique<NoTypoCorrectionCCC>();
11700   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11701                                                   HasTemplateArgs, ME);
11702 }
11703 
11704 /// Attempts to recover from a call where no functions were found.
11705 ///
11706 /// Returns true if new candidates were found.
11707 static ExprResult
11708 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11709                       UnresolvedLookupExpr *ULE,
11710                       SourceLocation LParenLoc,
11711                       MutableArrayRef<Expr *> Args,
11712                       SourceLocation RParenLoc,
11713                       bool EmptyLookup, bool AllowTypoCorrection) {
11714   // Do not try to recover if it is already building a recovery call.
11715   // This stops infinite loops for template instantiations like
11716   //
11717   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11718   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11719   //
11720   if (SemaRef.IsBuildingRecoveryCallExpr)
11721     return ExprError();
11722   BuildRecoveryCallExprRAII RCE(SemaRef);
11723 
11724   CXXScopeSpec SS;
11725   SS.Adopt(ULE->getQualifierLoc());
11726   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11727 
11728   TemplateArgumentListInfo TABuffer;
11729   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11730   if (ULE->hasExplicitTemplateArgs()) {
11731     ULE->copyTemplateArgumentsInto(TABuffer);
11732     ExplicitTemplateArgs = &TABuffer;
11733   }
11734 
11735   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11736                  Sema::LookupOrdinaryName);
11737   bool DoDiagnoseEmptyLookup = EmptyLookup;
11738   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11739                               OverloadCandidateSet::CSK_Normal,
11740                               ExplicitTemplateArgs, Args,
11741                               &DoDiagnoseEmptyLookup) &&
11742     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11743         S, SS, R,
11744         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11745                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11746         ExplicitTemplateArgs, Args)))
11747     return ExprError();
11748 
11749   assert(!R.empty() && "lookup results empty despite recovery");
11750 
11751   // If recovery created an ambiguity, just bail out.
11752   if (R.isAmbiguous()) {
11753     R.suppressDiagnostics();
11754     return ExprError();
11755   }
11756 
11757   // Build an implicit member call if appropriate.  Just drop the
11758   // casts and such from the call, we don't really care.
11759   ExprResult NewFn = ExprError();
11760   if ((*R.begin())->isCXXClassMember())
11761     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11762                                                     ExplicitTemplateArgs, S);
11763   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11764     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11765                                         ExplicitTemplateArgs);
11766   else
11767     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11768 
11769   if (NewFn.isInvalid())
11770     return ExprError();
11771 
11772   // This shouldn't cause an infinite loop because we're giving it
11773   // an expression with viable lookup results, which should never
11774   // end up here.
11775   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11776                                MultiExprArg(Args.data(), Args.size()),
11777                                RParenLoc);
11778 }
11779 
11780 /// \brief Constructs and populates an OverloadedCandidateSet from
11781 /// the given function.
11782 /// \returns true when an the ExprResult output parameter has been set.
11783 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11784                                   UnresolvedLookupExpr *ULE,
11785                                   MultiExprArg Args,
11786                                   SourceLocation RParenLoc,
11787                                   OverloadCandidateSet *CandidateSet,
11788                                   ExprResult *Result) {
11789 #ifndef NDEBUG
11790   if (ULE->requiresADL()) {
11791     // To do ADL, we must have found an unqualified name.
11792     assert(!ULE->getQualifier() && "qualified name with ADL");
11793 
11794     // We don't perform ADL for implicit declarations of builtins.
11795     // Verify that this was correctly set up.
11796     FunctionDecl *F;
11797     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11798         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11799         F->getBuiltinID() && F->isImplicit())
11800       llvm_unreachable("performing ADL for builtin");
11801 
11802     // We don't perform ADL in C.
11803     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11804   }
11805 #endif
11806 
11807   UnbridgedCastsSet UnbridgedCasts;
11808   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11809     *Result = ExprError();
11810     return true;
11811   }
11812 
11813   // Add the functions denoted by the callee to the set of candidate
11814   // functions, including those from argument-dependent lookup.
11815   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11816 
11817   if (getLangOpts().MSVCCompat &&
11818       CurContext->isDependentContext() && !isSFINAEContext() &&
11819       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11820 
11821     OverloadCandidateSet::iterator Best;
11822     if (CandidateSet->empty() ||
11823         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11824             OR_No_Viable_Function) {
11825       // In Microsoft mode, if we are inside a template class member function then
11826       // create a type dependent CallExpr. The goal is to postpone name lookup
11827       // to instantiation time to be able to search into type dependent base
11828       // classes.
11829       CallExpr *CE = new (Context) CallExpr(
11830           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11831       CE->setTypeDependent(true);
11832       CE->setValueDependent(true);
11833       CE->setInstantiationDependent(true);
11834       *Result = CE;
11835       return true;
11836     }
11837   }
11838 
11839   if (CandidateSet->empty())
11840     return false;
11841 
11842   UnbridgedCasts.restore();
11843   return false;
11844 }
11845 
11846 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11847 /// the completed call expression. If overload resolution fails, emits
11848 /// diagnostics and returns ExprError()
11849 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11850                                            UnresolvedLookupExpr *ULE,
11851                                            SourceLocation LParenLoc,
11852                                            MultiExprArg Args,
11853                                            SourceLocation RParenLoc,
11854                                            Expr *ExecConfig,
11855                                            OverloadCandidateSet *CandidateSet,
11856                                            OverloadCandidateSet::iterator *Best,
11857                                            OverloadingResult OverloadResult,
11858                                            bool AllowTypoCorrection) {
11859   if (CandidateSet->empty())
11860     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11861                                  RParenLoc, /*EmptyLookup=*/true,
11862                                  AllowTypoCorrection);
11863 
11864   switch (OverloadResult) {
11865   case OR_Success: {
11866     FunctionDecl *FDecl = (*Best)->Function;
11867     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11868     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11869       return ExprError();
11870     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11871     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11872                                          ExecConfig);
11873   }
11874 
11875   case OR_No_Viable_Function: {
11876     // Try to recover by looking for viable functions which the user might
11877     // have meant to call.
11878     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11879                                                 Args, RParenLoc,
11880                                                 /*EmptyLookup=*/false,
11881                                                 AllowTypoCorrection);
11882     if (!Recovery.isInvalid())
11883       return Recovery;
11884 
11885     // If the user passes in a function that we can't take the address of, we
11886     // generally end up emitting really bad error messages. Here, we attempt to
11887     // emit better ones.
11888     for (const Expr *Arg : Args) {
11889       if (!Arg->getType()->isFunctionType())
11890         continue;
11891       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11892         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11893         if (FD &&
11894             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11895                                                        Arg->getExprLoc()))
11896           return ExprError();
11897       }
11898     }
11899 
11900     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11901         << ULE->getName() << Fn->getSourceRange();
11902     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11903     break;
11904   }
11905 
11906   case OR_Ambiguous:
11907     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11908       << ULE->getName() << Fn->getSourceRange();
11909     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11910     break;
11911 
11912   case OR_Deleted: {
11913     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11914       << (*Best)->Function->isDeleted()
11915       << ULE->getName()
11916       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11917       << Fn->getSourceRange();
11918     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11919 
11920     // We emitted an error for the unavailable/deleted function call but keep
11921     // the call in the AST.
11922     FunctionDecl *FDecl = (*Best)->Function;
11923     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11924     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11925                                          ExecConfig);
11926   }
11927   }
11928 
11929   // Overload resolution failed.
11930   return ExprError();
11931 }
11932 
11933 static void markUnaddressableCandidatesUnviable(Sema &S,
11934                                                 OverloadCandidateSet &CS) {
11935   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11936     if (I->Viable &&
11937         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11938       I->Viable = false;
11939       I->FailureKind = ovl_fail_addr_not_available;
11940     }
11941   }
11942 }
11943 
11944 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11945 /// (which eventually refers to the declaration Func) and the call
11946 /// arguments Args/NumArgs, attempt to resolve the function call down
11947 /// to a specific function. If overload resolution succeeds, returns
11948 /// the call expression produced by overload resolution.
11949 /// Otherwise, emits diagnostics and returns ExprError.
11950 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11951                                          UnresolvedLookupExpr *ULE,
11952                                          SourceLocation LParenLoc,
11953                                          MultiExprArg Args,
11954                                          SourceLocation RParenLoc,
11955                                          Expr *ExecConfig,
11956                                          bool AllowTypoCorrection,
11957                                          bool CalleesAddressIsTaken) {
11958   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11959                                     OverloadCandidateSet::CSK_Normal);
11960   ExprResult result;
11961 
11962   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11963                              &result))
11964     return result;
11965 
11966   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11967   // functions that aren't addressible are considered unviable.
11968   if (CalleesAddressIsTaken)
11969     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11970 
11971   OverloadCandidateSet::iterator Best;
11972   OverloadingResult OverloadResult =
11973       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11974 
11975   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11976                                   RParenLoc, ExecConfig, &CandidateSet,
11977                                   &Best, OverloadResult,
11978                                   AllowTypoCorrection);
11979 }
11980 
11981 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11982   return Functions.size() > 1 ||
11983     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11984 }
11985 
11986 /// \brief Create a unary operation that may resolve to an overloaded
11987 /// operator.
11988 ///
11989 /// \param OpLoc The location of the operator itself (e.g., '*').
11990 ///
11991 /// \param Opc The UnaryOperatorKind that describes this operator.
11992 ///
11993 /// \param Fns The set of non-member functions that will be
11994 /// considered by overload resolution. The caller needs to build this
11995 /// set based on the context using, e.g.,
11996 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11997 /// set should not contain any member functions; those will be added
11998 /// by CreateOverloadedUnaryOp().
11999 ///
12000 /// \param Input The input argument.
12001 ExprResult
12002 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12003                               const UnresolvedSetImpl &Fns,
12004                               Expr *Input, bool PerformADL) {
12005   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12006   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12007   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12008   // TODO: provide better source location info.
12009   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12010 
12011   if (checkPlaceholderForOverload(*this, Input))
12012     return ExprError();
12013 
12014   Expr *Args[2] = { Input, nullptr };
12015   unsigned NumArgs = 1;
12016 
12017   // For post-increment and post-decrement, add the implicit '0' as
12018   // the second argument, so that we know this is a post-increment or
12019   // post-decrement.
12020   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12021     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12022     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12023                                      SourceLocation());
12024     NumArgs = 2;
12025   }
12026 
12027   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12028 
12029   if (Input->isTypeDependent()) {
12030     if (Fns.empty())
12031       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12032                                          VK_RValue, OK_Ordinary, OpLoc, false);
12033 
12034     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12035     UnresolvedLookupExpr *Fn
12036       = UnresolvedLookupExpr::Create(Context, NamingClass,
12037                                      NestedNameSpecifierLoc(), OpNameInfo,
12038                                      /*ADL*/ true, IsOverloaded(Fns),
12039                                      Fns.begin(), Fns.end());
12040     return new (Context)
12041         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12042                             VK_RValue, OpLoc, FPOptions());
12043   }
12044 
12045   // Build an empty overload set.
12046   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12047 
12048   // Add the candidates from the given function set.
12049   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12050 
12051   // Add operator candidates that are member functions.
12052   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12053 
12054   // Add candidates from ADL.
12055   if (PerformADL) {
12056     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12057                                          /*ExplicitTemplateArgs*/nullptr,
12058                                          CandidateSet);
12059   }
12060 
12061   // Add builtin operator candidates.
12062   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12063 
12064   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12065 
12066   // Perform overload resolution.
12067   OverloadCandidateSet::iterator Best;
12068   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12069   case OR_Success: {
12070     // We found a built-in operator or an overloaded operator.
12071     FunctionDecl *FnDecl = Best->Function;
12072 
12073     if (FnDecl) {
12074       Expr *Base = nullptr;
12075       // We matched an overloaded operator. Build a call to that
12076       // operator.
12077 
12078       // Convert the arguments.
12079       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12080         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12081 
12082         ExprResult InputRes =
12083           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12084                                               Best->FoundDecl, Method);
12085         if (InputRes.isInvalid())
12086           return ExprError();
12087         Base = Input = InputRes.get();
12088       } else {
12089         // Convert the arguments.
12090         ExprResult InputInit
12091           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12092                                                       Context,
12093                                                       FnDecl->getParamDecl(0)),
12094                                       SourceLocation(),
12095                                       Input);
12096         if (InputInit.isInvalid())
12097           return ExprError();
12098         Input = InputInit.get();
12099       }
12100 
12101       // Build the actual expression node.
12102       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12103                                                 Base, HadMultipleCandidates,
12104                                                 OpLoc);
12105       if (FnExpr.isInvalid())
12106         return ExprError();
12107 
12108       // Determine the result type.
12109       QualType ResultTy = FnDecl->getReturnType();
12110       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12111       ResultTy = ResultTy.getNonLValueExprType(Context);
12112 
12113       Args[0] = Input;
12114       CallExpr *TheCall =
12115         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12116                                           ResultTy, VK, OpLoc, FPOptions());
12117 
12118       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12119         return ExprError();
12120 
12121       if (CheckFunctionCall(FnDecl, TheCall,
12122                             FnDecl->getType()->castAs<FunctionProtoType>()))
12123         return ExprError();
12124 
12125       return MaybeBindToTemporary(TheCall);
12126     } else {
12127       // We matched a built-in operator. Convert the arguments, then
12128       // break out so that we will build the appropriate built-in
12129       // operator node.
12130       ExprResult InputRes = PerformImplicitConversion(
12131           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12132       if (InputRes.isInvalid())
12133         return ExprError();
12134       Input = InputRes.get();
12135       break;
12136     }
12137   }
12138 
12139   case OR_No_Viable_Function:
12140     // This is an erroneous use of an operator which can be overloaded by
12141     // a non-member function. Check for non-member operators which were
12142     // defined too late to be candidates.
12143     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12144       // FIXME: Recover by calling the found function.
12145       return ExprError();
12146 
12147     // No viable function; fall through to handling this as a
12148     // built-in operator, which will produce an error message for us.
12149     break;
12150 
12151   case OR_Ambiguous:
12152     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12153         << UnaryOperator::getOpcodeStr(Opc)
12154         << Input->getType()
12155         << Input->getSourceRange();
12156     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12157                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12158     return ExprError();
12159 
12160   case OR_Deleted:
12161     Diag(OpLoc, diag::err_ovl_deleted_oper)
12162       << Best->Function->isDeleted()
12163       << UnaryOperator::getOpcodeStr(Opc)
12164       << getDeletedOrUnavailableSuffix(Best->Function)
12165       << Input->getSourceRange();
12166     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12167                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12168     return ExprError();
12169   }
12170 
12171   // Either we found no viable overloaded operator or we matched a
12172   // built-in operator. In either case, fall through to trying to
12173   // build a built-in operation.
12174   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12175 }
12176 
12177 /// \brief Create a binary operation that may resolve to an overloaded
12178 /// operator.
12179 ///
12180 /// \param OpLoc The location of the operator itself (e.g., '+').
12181 ///
12182 /// \param Opc The BinaryOperatorKind that describes this operator.
12183 ///
12184 /// \param Fns The set of non-member functions that will be
12185 /// considered by overload resolution. The caller needs to build this
12186 /// set based on the context using, e.g.,
12187 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12188 /// set should not contain any member functions; those will be added
12189 /// by CreateOverloadedBinOp().
12190 ///
12191 /// \param LHS Left-hand argument.
12192 /// \param RHS Right-hand argument.
12193 ExprResult
12194 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12195                             BinaryOperatorKind Opc,
12196                             const UnresolvedSetImpl &Fns,
12197                             Expr *LHS, Expr *RHS, bool PerformADL) {
12198   Expr *Args[2] = { LHS, RHS };
12199   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12200 
12201   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12202   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12203 
12204   // If either side is type-dependent, create an appropriate dependent
12205   // expression.
12206   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12207     if (Fns.empty()) {
12208       // If there are no functions to store, just build a dependent
12209       // BinaryOperator or CompoundAssignment.
12210       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12211         return new (Context) BinaryOperator(
12212             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12213             OpLoc, FPFeatures);
12214 
12215       return new (Context) CompoundAssignOperator(
12216           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12217           Context.DependentTy, Context.DependentTy, OpLoc,
12218           FPFeatures);
12219     }
12220 
12221     // FIXME: save results of ADL from here?
12222     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12223     // TODO: provide better source location info in DNLoc component.
12224     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12225     UnresolvedLookupExpr *Fn
12226       = UnresolvedLookupExpr::Create(Context, NamingClass,
12227                                      NestedNameSpecifierLoc(), OpNameInfo,
12228                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12229                                      Fns.begin(), Fns.end());
12230     return new (Context)
12231         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12232                             VK_RValue, OpLoc, FPFeatures);
12233   }
12234 
12235   // Always do placeholder-like conversions on the RHS.
12236   if (checkPlaceholderForOverload(*this, Args[1]))
12237     return ExprError();
12238 
12239   // Do placeholder-like conversion on the LHS; note that we should
12240   // not get here with a PseudoObject LHS.
12241   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12242   if (checkPlaceholderForOverload(*this, Args[0]))
12243     return ExprError();
12244 
12245   // If this is the assignment operator, we only perform overload resolution
12246   // if the left-hand side is a class or enumeration type. This is actually
12247   // a hack. The standard requires that we do overload resolution between the
12248   // various built-in candidates, but as DR507 points out, this can lead to
12249   // problems. So we do it this way, which pretty much follows what GCC does.
12250   // Note that we go the traditional code path for compound assignment forms.
12251   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12252     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12253 
12254   // If this is the .* operator, which is not overloadable, just
12255   // create a built-in binary operator.
12256   if (Opc == BO_PtrMemD)
12257     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12258 
12259   // Build an empty overload set.
12260   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12261 
12262   // Add the candidates from the given function set.
12263   AddFunctionCandidates(Fns, Args, CandidateSet);
12264 
12265   // Add operator candidates that are member functions.
12266   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12267 
12268   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12269   // performed for an assignment operator (nor for operator[] nor operator->,
12270   // which don't get here).
12271   if (Opc != BO_Assign && PerformADL)
12272     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12273                                          /*ExplicitTemplateArgs*/ nullptr,
12274                                          CandidateSet);
12275 
12276   // Add builtin operator candidates.
12277   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12278 
12279   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12280 
12281   // Perform overload resolution.
12282   OverloadCandidateSet::iterator Best;
12283   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12284     case OR_Success: {
12285       // We found a built-in operator or an overloaded operator.
12286       FunctionDecl *FnDecl = Best->Function;
12287 
12288       if (FnDecl) {
12289         Expr *Base = nullptr;
12290         // We matched an overloaded operator. Build a call to that
12291         // operator.
12292 
12293         // Convert the arguments.
12294         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12295           // Best->Access is only meaningful for class members.
12296           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12297 
12298           ExprResult Arg1 =
12299             PerformCopyInitialization(
12300               InitializedEntity::InitializeParameter(Context,
12301                                                      FnDecl->getParamDecl(0)),
12302               SourceLocation(), Args[1]);
12303           if (Arg1.isInvalid())
12304             return ExprError();
12305 
12306           ExprResult Arg0 =
12307             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12308                                                 Best->FoundDecl, Method);
12309           if (Arg0.isInvalid())
12310             return ExprError();
12311           Base = Args[0] = Arg0.getAs<Expr>();
12312           Args[1] = RHS = Arg1.getAs<Expr>();
12313         } else {
12314           // Convert the arguments.
12315           ExprResult Arg0 = PerformCopyInitialization(
12316             InitializedEntity::InitializeParameter(Context,
12317                                                    FnDecl->getParamDecl(0)),
12318             SourceLocation(), Args[0]);
12319           if (Arg0.isInvalid())
12320             return ExprError();
12321 
12322           ExprResult Arg1 =
12323             PerformCopyInitialization(
12324               InitializedEntity::InitializeParameter(Context,
12325                                                      FnDecl->getParamDecl(1)),
12326               SourceLocation(), Args[1]);
12327           if (Arg1.isInvalid())
12328             return ExprError();
12329           Args[0] = LHS = Arg0.getAs<Expr>();
12330           Args[1] = RHS = Arg1.getAs<Expr>();
12331         }
12332 
12333         // Build the actual expression node.
12334         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12335                                                   Best->FoundDecl, Base,
12336                                                   HadMultipleCandidates, OpLoc);
12337         if (FnExpr.isInvalid())
12338           return ExprError();
12339 
12340         // Determine the result type.
12341         QualType ResultTy = FnDecl->getReturnType();
12342         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12343         ResultTy = ResultTy.getNonLValueExprType(Context);
12344 
12345         CXXOperatorCallExpr *TheCall =
12346           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12347                                             Args, ResultTy, VK, OpLoc,
12348                                             FPFeatures);
12349 
12350         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12351                                 FnDecl))
12352           return ExprError();
12353 
12354         ArrayRef<const Expr *> ArgsArray(Args, 2);
12355         const Expr *ImplicitThis = nullptr;
12356         // Cut off the implicit 'this'.
12357         if (isa<CXXMethodDecl>(FnDecl)) {
12358           ImplicitThis = ArgsArray[0];
12359           ArgsArray = ArgsArray.slice(1);
12360         }
12361 
12362         // Check for a self move.
12363         if (Op == OO_Equal)
12364           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12365 
12366         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12367                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12368                   VariadicDoesNotApply);
12369 
12370         return MaybeBindToTemporary(TheCall);
12371       } else {
12372         // We matched a built-in operator. Convert the arguments, then
12373         // break out so that we will build the appropriate built-in
12374         // operator node.
12375         ExprResult ArgsRes0 =
12376             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12377                                       Best->Conversions[0], AA_Passing);
12378         if (ArgsRes0.isInvalid())
12379           return ExprError();
12380         Args[0] = ArgsRes0.get();
12381 
12382         ExprResult ArgsRes1 =
12383             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12384                                       Best->Conversions[1], AA_Passing);
12385         if (ArgsRes1.isInvalid())
12386           return ExprError();
12387         Args[1] = ArgsRes1.get();
12388         break;
12389       }
12390     }
12391 
12392     case OR_No_Viable_Function: {
12393       // C++ [over.match.oper]p9:
12394       //   If the operator is the operator , [...] and there are no
12395       //   viable functions, then the operator is assumed to be the
12396       //   built-in operator and interpreted according to clause 5.
12397       if (Opc == BO_Comma)
12398         break;
12399 
12400       // For class as left operand for assignment or compound assignment
12401       // operator do not fall through to handling in built-in, but report that
12402       // no overloaded assignment operator found
12403       ExprResult Result = ExprError();
12404       if (Args[0]->getType()->isRecordType() &&
12405           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12406         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12407              << BinaryOperator::getOpcodeStr(Opc)
12408              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12409         if (Args[0]->getType()->isIncompleteType()) {
12410           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12411             << Args[0]->getType()
12412             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12413         }
12414       } else {
12415         // This is an erroneous use of an operator which can be overloaded by
12416         // a non-member function. Check for non-member operators which were
12417         // defined too late to be candidates.
12418         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12419           // FIXME: Recover by calling the found function.
12420           return ExprError();
12421 
12422         // No viable function; try to create a built-in operation, which will
12423         // produce an error. Then, show the non-viable candidates.
12424         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12425       }
12426       assert(Result.isInvalid() &&
12427              "C++ binary operator overloading is missing candidates!");
12428       if (Result.isInvalid())
12429         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12430                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12431       return Result;
12432     }
12433 
12434     case OR_Ambiguous:
12435       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12436           << BinaryOperator::getOpcodeStr(Opc)
12437           << Args[0]->getType() << Args[1]->getType()
12438           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12439       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12440                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12441       return ExprError();
12442 
12443     case OR_Deleted:
12444       if (isImplicitlyDeleted(Best->Function)) {
12445         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12446         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12447           << Context.getRecordType(Method->getParent())
12448           << getSpecialMember(Method);
12449 
12450         // The user probably meant to call this special member. Just
12451         // explain why it's deleted.
12452         NoteDeletedFunction(Method);
12453         return ExprError();
12454       } else {
12455         Diag(OpLoc, diag::err_ovl_deleted_oper)
12456           << Best->Function->isDeleted()
12457           << BinaryOperator::getOpcodeStr(Opc)
12458           << getDeletedOrUnavailableSuffix(Best->Function)
12459           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12460       }
12461       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12462                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12463       return ExprError();
12464   }
12465 
12466   // We matched a built-in operator; build it.
12467   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12468 }
12469 
12470 ExprResult
12471 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12472                                          SourceLocation RLoc,
12473                                          Expr *Base, Expr *Idx) {
12474   Expr *Args[2] = { Base, Idx };
12475   DeclarationName OpName =
12476       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12477 
12478   // If either side is type-dependent, create an appropriate dependent
12479   // expression.
12480   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12481 
12482     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12483     // CHECKME: no 'operator' keyword?
12484     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12485     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12486     UnresolvedLookupExpr *Fn
12487       = UnresolvedLookupExpr::Create(Context, NamingClass,
12488                                      NestedNameSpecifierLoc(), OpNameInfo,
12489                                      /*ADL*/ true, /*Overloaded*/ false,
12490                                      UnresolvedSetIterator(),
12491                                      UnresolvedSetIterator());
12492     // Can't add any actual overloads yet
12493 
12494     return new (Context)
12495         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12496                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12497   }
12498 
12499   // Handle placeholders on both operands.
12500   if (checkPlaceholderForOverload(*this, Args[0]))
12501     return ExprError();
12502   if (checkPlaceholderForOverload(*this, Args[1]))
12503     return ExprError();
12504 
12505   // Build an empty overload set.
12506   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12507 
12508   // Subscript can only be overloaded as a member function.
12509 
12510   // Add operator candidates that are member functions.
12511   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12512 
12513   // Add builtin operator candidates.
12514   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12515 
12516   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12517 
12518   // Perform overload resolution.
12519   OverloadCandidateSet::iterator Best;
12520   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12521     case OR_Success: {
12522       // We found a built-in operator or an overloaded operator.
12523       FunctionDecl *FnDecl = Best->Function;
12524 
12525       if (FnDecl) {
12526         // We matched an overloaded operator. Build a call to that
12527         // operator.
12528 
12529         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12530 
12531         // Convert the arguments.
12532         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12533         ExprResult Arg0 =
12534           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12535                                               Best->FoundDecl, Method);
12536         if (Arg0.isInvalid())
12537           return ExprError();
12538         Args[0] = Arg0.get();
12539 
12540         // Convert the arguments.
12541         ExprResult InputInit
12542           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12543                                                       Context,
12544                                                       FnDecl->getParamDecl(0)),
12545                                       SourceLocation(),
12546                                       Args[1]);
12547         if (InputInit.isInvalid())
12548           return ExprError();
12549 
12550         Args[1] = InputInit.getAs<Expr>();
12551 
12552         // Build the actual expression node.
12553         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12554         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12555         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12556                                                   Best->FoundDecl,
12557                                                   Base,
12558                                                   HadMultipleCandidates,
12559                                                   OpLocInfo.getLoc(),
12560                                                   OpLocInfo.getInfo());
12561         if (FnExpr.isInvalid())
12562           return ExprError();
12563 
12564         // Determine the result type
12565         QualType ResultTy = FnDecl->getReturnType();
12566         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12567         ResultTy = ResultTy.getNonLValueExprType(Context);
12568 
12569         CXXOperatorCallExpr *TheCall =
12570           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12571                                             FnExpr.get(), Args,
12572                                             ResultTy, VK, RLoc,
12573                                             FPOptions());
12574 
12575         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12576           return ExprError();
12577 
12578         if (CheckFunctionCall(Method, TheCall,
12579                               Method->getType()->castAs<FunctionProtoType>()))
12580           return ExprError();
12581 
12582         return MaybeBindToTemporary(TheCall);
12583       } else {
12584         // We matched a built-in operator. Convert the arguments, then
12585         // break out so that we will build the appropriate built-in
12586         // operator node.
12587         ExprResult ArgsRes0 =
12588             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12589                                       Best->Conversions[0], AA_Passing);
12590         if (ArgsRes0.isInvalid())
12591           return ExprError();
12592         Args[0] = ArgsRes0.get();
12593 
12594         ExprResult ArgsRes1 =
12595             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12596                                       Best->Conversions[1], AA_Passing);
12597         if (ArgsRes1.isInvalid())
12598           return ExprError();
12599         Args[1] = ArgsRes1.get();
12600 
12601         break;
12602       }
12603     }
12604 
12605     case OR_No_Viable_Function: {
12606       if (CandidateSet.empty())
12607         Diag(LLoc, diag::err_ovl_no_oper)
12608           << Args[0]->getType() << /*subscript*/ 0
12609           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12610       else
12611         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12612           << Args[0]->getType()
12613           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12614       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12615                                   "[]", LLoc);
12616       return ExprError();
12617     }
12618 
12619     case OR_Ambiguous:
12620       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12621           << "[]"
12622           << Args[0]->getType() << Args[1]->getType()
12623           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12624       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12625                                   "[]", LLoc);
12626       return ExprError();
12627 
12628     case OR_Deleted:
12629       Diag(LLoc, diag::err_ovl_deleted_oper)
12630         << Best->Function->isDeleted() << "[]"
12631         << getDeletedOrUnavailableSuffix(Best->Function)
12632         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12633       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12634                                   "[]", LLoc);
12635       return ExprError();
12636     }
12637 
12638   // We matched a built-in operator; build it.
12639   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12640 }
12641 
12642 /// BuildCallToMemberFunction - Build a call to a member
12643 /// function. MemExpr is the expression that refers to the member
12644 /// function (and includes the object parameter), Args/NumArgs are the
12645 /// arguments to the function call (not including the object
12646 /// parameter). The caller needs to validate that the member
12647 /// expression refers to a non-static member function or an overloaded
12648 /// member function.
12649 ExprResult
12650 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12651                                 SourceLocation LParenLoc,
12652                                 MultiExprArg Args,
12653                                 SourceLocation RParenLoc) {
12654   assert(MemExprE->getType() == Context.BoundMemberTy ||
12655          MemExprE->getType() == Context.OverloadTy);
12656 
12657   // Dig out the member expression. This holds both the object
12658   // argument and the member function we're referring to.
12659   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12660 
12661   // Determine whether this is a call to a pointer-to-member function.
12662   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12663     assert(op->getType() == Context.BoundMemberTy);
12664     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12665 
12666     QualType fnType =
12667       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12668 
12669     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12670     QualType resultType = proto->getCallResultType(Context);
12671     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12672 
12673     // Check that the object type isn't more qualified than the
12674     // member function we're calling.
12675     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12676 
12677     QualType objectType = op->getLHS()->getType();
12678     if (op->getOpcode() == BO_PtrMemI)
12679       objectType = objectType->castAs<PointerType>()->getPointeeType();
12680     Qualifiers objectQuals = objectType.getQualifiers();
12681 
12682     Qualifiers difference = objectQuals - funcQuals;
12683     difference.removeObjCGCAttr();
12684     difference.removeAddressSpace();
12685     if (difference) {
12686       std::string qualsString = difference.getAsString();
12687       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12688         << fnType.getUnqualifiedType()
12689         << qualsString
12690         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12691     }
12692 
12693     CXXMemberCallExpr *call
12694       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12695                                         resultType, valueKind, RParenLoc);
12696 
12697     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12698                             call, nullptr))
12699       return ExprError();
12700 
12701     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12702       return ExprError();
12703 
12704     if (CheckOtherCall(call, proto))
12705       return ExprError();
12706 
12707     return MaybeBindToTemporary(call);
12708   }
12709 
12710   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12711     return new (Context)
12712         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12713 
12714   UnbridgedCastsSet UnbridgedCasts;
12715   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12716     return ExprError();
12717 
12718   MemberExpr *MemExpr;
12719   CXXMethodDecl *Method = nullptr;
12720   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12721   NestedNameSpecifier *Qualifier = nullptr;
12722   if (isa<MemberExpr>(NakedMemExpr)) {
12723     MemExpr = cast<MemberExpr>(NakedMemExpr);
12724     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12725     FoundDecl = MemExpr->getFoundDecl();
12726     Qualifier = MemExpr->getQualifier();
12727     UnbridgedCasts.restore();
12728   } else {
12729     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12730     Qualifier = UnresExpr->getQualifier();
12731 
12732     QualType ObjectType = UnresExpr->getBaseType();
12733     Expr::Classification ObjectClassification
12734       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12735                             : UnresExpr->getBase()->Classify(Context);
12736 
12737     // Add overload candidates
12738     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12739                                       OverloadCandidateSet::CSK_Normal);
12740 
12741     // FIXME: avoid copy.
12742     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12743     if (UnresExpr->hasExplicitTemplateArgs()) {
12744       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12745       TemplateArgs = &TemplateArgsBuffer;
12746     }
12747 
12748     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12749            E = UnresExpr->decls_end(); I != E; ++I) {
12750 
12751       NamedDecl *Func = *I;
12752       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12753       if (isa<UsingShadowDecl>(Func))
12754         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12755 
12756 
12757       // Microsoft supports direct constructor calls.
12758       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12759         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12760                              Args, CandidateSet);
12761       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12762         // If explicit template arguments were provided, we can't call a
12763         // non-template member function.
12764         if (TemplateArgs)
12765           continue;
12766 
12767         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12768                            ObjectClassification, Args, CandidateSet,
12769                            /*SuppressUserConversions=*/false);
12770       } else {
12771         AddMethodTemplateCandidate(
12772             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12773             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12774             /*SuppressUsedConversions=*/false);
12775       }
12776     }
12777 
12778     DeclarationName DeclName = UnresExpr->getMemberName();
12779 
12780     UnbridgedCasts.restore();
12781 
12782     OverloadCandidateSet::iterator Best;
12783     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12784                                             Best)) {
12785     case OR_Success:
12786       Method = cast<CXXMethodDecl>(Best->Function);
12787       FoundDecl = Best->FoundDecl;
12788       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12789       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12790         return ExprError();
12791       // If FoundDecl is different from Method (such as if one is a template
12792       // and the other a specialization), make sure DiagnoseUseOfDecl is
12793       // called on both.
12794       // FIXME: This would be more comprehensively addressed by modifying
12795       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12796       // being used.
12797       if (Method != FoundDecl.getDecl() &&
12798                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12799         return ExprError();
12800       break;
12801 
12802     case OR_No_Viable_Function:
12803       Diag(UnresExpr->getMemberLoc(),
12804            diag::err_ovl_no_viable_member_function_in_call)
12805         << DeclName << MemExprE->getSourceRange();
12806       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12807       // FIXME: Leaking incoming expressions!
12808       return ExprError();
12809 
12810     case OR_Ambiguous:
12811       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12812         << DeclName << MemExprE->getSourceRange();
12813       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12814       // FIXME: Leaking incoming expressions!
12815       return ExprError();
12816 
12817     case OR_Deleted:
12818       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12819         << Best->Function->isDeleted()
12820         << DeclName
12821         << getDeletedOrUnavailableSuffix(Best->Function)
12822         << MemExprE->getSourceRange();
12823       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12824       // FIXME: Leaking incoming expressions!
12825       return ExprError();
12826     }
12827 
12828     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12829 
12830     // If overload resolution picked a static member, build a
12831     // non-member call based on that function.
12832     if (Method->isStatic()) {
12833       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12834                                    RParenLoc);
12835     }
12836 
12837     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12838   }
12839 
12840   QualType ResultType = Method->getReturnType();
12841   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12842   ResultType = ResultType.getNonLValueExprType(Context);
12843 
12844   assert(Method && "Member call to something that isn't a method?");
12845   CXXMemberCallExpr *TheCall =
12846     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12847                                     ResultType, VK, RParenLoc);
12848 
12849   // Check for a valid return type.
12850   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12851                           TheCall, Method))
12852     return ExprError();
12853 
12854   // Convert the object argument (for a non-static member function call).
12855   // We only need to do this if there was actually an overload; otherwise
12856   // it was done at lookup.
12857   if (!Method->isStatic()) {
12858     ExprResult ObjectArg =
12859       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12860                                           FoundDecl, Method);
12861     if (ObjectArg.isInvalid())
12862       return ExprError();
12863     MemExpr->setBase(ObjectArg.get());
12864   }
12865 
12866   // Convert the rest of the arguments
12867   const FunctionProtoType *Proto =
12868     Method->getType()->getAs<FunctionProtoType>();
12869   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12870                               RParenLoc))
12871     return ExprError();
12872 
12873   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12874 
12875   if (CheckFunctionCall(Method, TheCall, Proto))
12876     return ExprError();
12877 
12878   // In the case the method to call was not selected by the overloading
12879   // resolution process, we still need to handle the enable_if attribute. Do
12880   // that here, so it will not hide previous -- and more relevant -- errors.
12881   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12882     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12883       Diag(MemE->getMemberLoc(),
12884            diag::err_ovl_no_viable_member_function_in_call)
12885           << Method << Method->getSourceRange();
12886       Diag(Method->getLocation(),
12887            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12888           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12889       return ExprError();
12890     }
12891   }
12892 
12893   if ((isa<CXXConstructorDecl>(CurContext) ||
12894        isa<CXXDestructorDecl>(CurContext)) &&
12895       TheCall->getMethodDecl()->isPure()) {
12896     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12897 
12898     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12899         MemExpr->performsVirtualDispatch(getLangOpts())) {
12900       Diag(MemExpr->getLocStart(),
12901            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12902         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12903         << MD->getParent()->getDeclName();
12904 
12905       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12906       if (getLangOpts().AppleKext)
12907         Diag(MemExpr->getLocStart(),
12908              diag::note_pure_qualified_call_kext)
12909              << MD->getParent()->getDeclName()
12910              << MD->getDeclName();
12911     }
12912   }
12913 
12914   if (CXXDestructorDecl *DD =
12915           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12916     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12917     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12918     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12919                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12920                          MemExpr->getMemberLoc());
12921   }
12922 
12923   return MaybeBindToTemporary(TheCall);
12924 }
12925 
12926 /// BuildCallToObjectOfClassType - Build a call to an object of class
12927 /// type (C++ [over.call.object]), which can end up invoking an
12928 /// overloaded function call operator (@c operator()) or performing a
12929 /// user-defined conversion on the object argument.
12930 ExprResult
12931 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12932                                    SourceLocation LParenLoc,
12933                                    MultiExprArg Args,
12934                                    SourceLocation RParenLoc) {
12935   if (checkPlaceholderForOverload(*this, Obj))
12936     return ExprError();
12937   ExprResult Object = Obj;
12938 
12939   UnbridgedCastsSet UnbridgedCasts;
12940   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12941     return ExprError();
12942 
12943   assert(Object.get()->getType()->isRecordType() &&
12944          "Requires object type argument");
12945   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12946 
12947   // C++ [over.call.object]p1:
12948   //  If the primary-expression E in the function call syntax
12949   //  evaluates to a class object of type "cv T", then the set of
12950   //  candidate functions includes at least the function call
12951   //  operators of T. The function call operators of T are obtained by
12952   //  ordinary lookup of the name operator() in the context of
12953   //  (E).operator().
12954   OverloadCandidateSet CandidateSet(LParenLoc,
12955                                     OverloadCandidateSet::CSK_Operator);
12956   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12957 
12958   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12959                           diag::err_incomplete_object_call, Object.get()))
12960     return true;
12961 
12962   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12963   LookupQualifiedName(R, Record->getDecl());
12964   R.suppressDiagnostics();
12965 
12966   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12967        Oper != OperEnd; ++Oper) {
12968     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12969                        Object.get()->Classify(Context), Args, CandidateSet,
12970                        /*SuppressUserConversions=*/false);
12971   }
12972 
12973   // C++ [over.call.object]p2:
12974   //   In addition, for each (non-explicit in C++0x) conversion function
12975   //   declared in T of the form
12976   //
12977   //        operator conversion-type-id () cv-qualifier;
12978   //
12979   //   where cv-qualifier is the same cv-qualification as, or a
12980   //   greater cv-qualification than, cv, and where conversion-type-id
12981   //   denotes the type "pointer to function of (P1,...,Pn) returning
12982   //   R", or the type "reference to pointer to function of
12983   //   (P1,...,Pn) returning R", or the type "reference to function
12984   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12985   //   is also considered as a candidate function. Similarly,
12986   //   surrogate call functions are added to the set of candidate
12987   //   functions for each conversion function declared in an
12988   //   accessible base class provided the function is not hidden
12989   //   within T by another intervening declaration.
12990   const auto &Conversions =
12991       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12992   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12993     NamedDecl *D = *I;
12994     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12995     if (isa<UsingShadowDecl>(D))
12996       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12997 
12998     // Skip over templated conversion functions; they aren't
12999     // surrogates.
13000     if (isa<FunctionTemplateDecl>(D))
13001       continue;
13002 
13003     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13004     if (!Conv->isExplicit()) {
13005       // Strip the reference type (if any) and then the pointer type (if
13006       // any) to get down to what might be a function type.
13007       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13008       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13009         ConvType = ConvPtrType->getPointeeType();
13010 
13011       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13012       {
13013         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13014                               Object.get(), Args, CandidateSet);
13015       }
13016     }
13017   }
13018 
13019   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13020 
13021   // Perform overload resolution.
13022   OverloadCandidateSet::iterator Best;
13023   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13024                                           Best)) {
13025   case OR_Success:
13026     // Overload resolution succeeded; we'll build the appropriate call
13027     // below.
13028     break;
13029 
13030   case OR_No_Viable_Function:
13031     if (CandidateSet.empty())
13032       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13033         << Object.get()->getType() << /*call*/ 1
13034         << Object.get()->getSourceRange();
13035     else
13036       Diag(Object.get()->getLocStart(),
13037            diag::err_ovl_no_viable_object_call)
13038         << Object.get()->getType() << Object.get()->getSourceRange();
13039     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13040     break;
13041 
13042   case OR_Ambiguous:
13043     Diag(Object.get()->getLocStart(),
13044          diag::err_ovl_ambiguous_object_call)
13045       << Object.get()->getType() << Object.get()->getSourceRange();
13046     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13047     break;
13048 
13049   case OR_Deleted:
13050     Diag(Object.get()->getLocStart(),
13051          diag::err_ovl_deleted_object_call)
13052       << Best->Function->isDeleted()
13053       << Object.get()->getType()
13054       << getDeletedOrUnavailableSuffix(Best->Function)
13055       << Object.get()->getSourceRange();
13056     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13057     break;
13058   }
13059 
13060   if (Best == CandidateSet.end())
13061     return true;
13062 
13063   UnbridgedCasts.restore();
13064 
13065   if (Best->Function == nullptr) {
13066     // Since there is no function declaration, this is one of the
13067     // surrogate candidates. Dig out the conversion function.
13068     CXXConversionDecl *Conv
13069       = cast<CXXConversionDecl>(
13070                          Best->Conversions[0].UserDefined.ConversionFunction);
13071 
13072     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13073                               Best->FoundDecl);
13074     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13075       return ExprError();
13076     assert(Conv == Best->FoundDecl.getDecl() &&
13077              "Found Decl & conversion-to-functionptr should be same, right?!");
13078     // We selected one of the surrogate functions that converts the
13079     // object parameter to a function pointer. Perform the conversion
13080     // on the object argument, then let ActOnCallExpr finish the job.
13081 
13082     // Create an implicit member expr to refer to the conversion operator.
13083     // and then call it.
13084     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13085                                              Conv, HadMultipleCandidates);
13086     if (Call.isInvalid())
13087       return ExprError();
13088     // Record usage of conversion in an implicit cast.
13089     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13090                                     CK_UserDefinedConversion, Call.get(),
13091                                     nullptr, VK_RValue);
13092 
13093     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13094   }
13095 
13096   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13097 
13098   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13099   // that calls this method, using Object for the implicit object
13100   // parameter and passing along the remaining arguments.
13101   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13102 
13103   // An error diagnostic has already been printed when parsing the declaration.
13104   if (Method->isInvalidDecl())
13105     return ExprError();
13106 
13107   const FunctionProtoType *Proto =
13108     Method->getType()->getAs<FunctionProtoType>();
13109 
13110   unsigned NumParams = Proto->getNumParams();
13111 
13112   DeclarationNameInfo OpLocInfo(
13113                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13114   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13115   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13116                                            Obj, HadMultipleCandidates,
13117                                            OpLocInfo.getLoc(),
13118                                            OpLocInfo.getInfo());
13119   if (NewFn.isInvalid())
13120     return true;
13121 
13122   // Build the full argument list for the method call (the implicit object
13123   // parameter is placed at the beginning of the list).
13124   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13125   MethodArgs[0] = Object.get();
13126   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13127 
13128   // Once we've built TheCall, all of the expressions are properly
13129   // owned.
13130   QualType ResultTy = Method->getReturnType();
13131   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13132   ResultTy = ResultTy.getNonLValueExprType(Context);
13133 
13134   CXXOperatorCallExpr *TheCall = new (Context)
13135       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13136                           VK, RParenLoc, FPOptions());
13137 
13138   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13139     return true;
13140 
13141   // We may have default arguments. If so, we need to allocate more
13142   // slots in the call for them.
13143   if (Args.size() < NumParams)
13144     TheCall->setNumArgs(Context, NumParams + 1);
13145 
13146   bool IsError = false;
13147 
13148   // Initialize the implicit object parameter.
13149   ExprResult ObjRes =
13150     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13151                                         Best->FoundDecl, Method);
13152   if (ObjRes.isInvalid())
13153     IsError = true;
13154   else
13155     Object = ObjRes;
13156   TheCall->setArg(0, Object.get());
13157 
13158   // Check the argument types.
13159   for (unsigned i = 0; i != NumParams; i++) {
13160     Expr *Arg;
13161     if (i < Args.size()) {
13162       Arg = Args[i];
13163 
13164       // Pass the argument.
13165 
13166       ExprResult InputInit
13167         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13168                                                     Context,
13169                                                     Method->getParamDecl(i)),
13170                                     SourceLocation(), Arg);
13171 
13172       IsError |= InputInit.isInvalid();
13173       Arg = InputInit.getAs<Expr>();
13174     } else {
13175       ExprResult DefArg
13176         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13177       if (DefArg.isInvalid()) {
13178         IsError = true;
13179         break;
13180       }
13181 
13182       Arg = DefArg.getAs<Expr>();
13183     }
13184 
13185     TheCall->setArg(i + 1, Arg);
13186   }
13187 
13188   // If this is a variadic call, handle args passed through "...".
13189   if (Proto->isVariadic()) {
13190     // Promote the arguments (C99 6.5.2.2p7).
13191     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13192       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13193                                                         nullptr);
13194       IsError |= Arg.isInvalid();
13195       TheCall->setArg(i + 1, Arg.get());
13196     }
13197   }
13198 
13199   if (IsError) return true;
13200 
13201   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13202 
13203   if (CheckFunctionCall(Method, TheCall, Proto))
13204     return true;
13205 
13206   return MaybeBindToTemporary(TheCall);
13207 }
13208 
13209 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13210 ///  (if one exists), where @c Base is an expression of class type and
13211 /// @c Member is the name of the member we're trying to find.
13212 ExprResult
13213 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13214                                bool *NoArrowOperatorFound) {
13215   assert(Base->getType()->isRecordType() &&
13216          "left-hand side must have class type");
13217 
13218   if (checkPlaceholderForOverload(*this, Base))
13219     return ExprError();
13220 
13221   SourceLocation Loc = Base->getExprLoc();
13222 
13223   // C++ [over.ref]p1:
13224   //
13225   //   [...] An expression x->m is interpreted as (x.operator->())->m
13226   //   for a class object x of type T if T::operator->() exists and if
13227   //   the operator is selected as the best match function by the
13228   //   overload resolution mechanism (13.3).
13229   DeclarationName OpName =
13230     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13231   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13232   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13233 
13234   if (RequireCompleteType(Loc, Base->getType(),
13235                           diag::err_typecheck_incomplete_tag, Base))
13236     return ExprError();
13237 
13238   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13239   LookupQualifiedName(R, BaseRecord->getDecl());
13240   R.suppressDiagnostics();
13241 
13242   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13243        Oper != OperEnd; ++Oper) {
13244     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13245                        None, CandidateSet, /*SuppressUserConversions=*/false);
13246   }
13247 
13248   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13249 
13250   // Perform overload resolution.
13251   OverloadCandidateSet::iterator Best;
13252   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13253   case OR_Success:
13254     // Overload resolution succeeded; we'll build the call below.
13255     break;
13256 
13257   case OR_No_Viable_Function:
13258     if (CandidateSet.empty()) {
13259       QualType BaseType = Base->getType();
13260       if (NoArrowOperatorFound) {
13261         // Report this specific error to the caller instead of emitting a
13262         // diagnostic, as requested.
13263         *NoArrowOperatorFound = true;
13264         return ExprError();
13265       }
13266       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13267         << BaseType << Base->getSourceRange();
13268       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13269         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13270           << FixItHint::CreateReplacement(OpLoc, ".");
13271       }
13272     } else
13273       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13274         << "operator->" << Base->getSourceRange();
13275     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13276     return ExprError();
13277 
13278   case OR_Ambiguous:
13279     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13280       << "->" << Base->getType() << Base->getSourceRange();
13281     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13282     return ExprError();
13283 
13284   case OR_Deleted:
13285     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13286       << Best->Function->isDeleted()
13287       << "->"
13288       << getDeletedOrUnavailableSuffix(Best->Function)
13289       << Base->getSourceRange();
13290     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13291     return ExprError();
13292   }
13293 
13294   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13295 
13296   // Convert the object parameter.
13297   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13298   ExprResult BaseResult =
13299     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13300                                         Best->FoundDecl, Method);
13301   if (BaseResult.isInvalid())
13302     return ExprError();
13303   Base = BaseResult.get();
13304 
13305   // Build the operator call.
13306   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13307                                             Base, HadMultipleCandidates, OpLoc);
13308   if (FnExpr.isInvalid())
13309     return ExprError();
13310 
13311   QualType ResultTy = Method->getReturnType();
13312   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13313   ResultTy = ResultTy.getNonLValueExprType(Context);
13314   CXXOperatorCallExpr *TheCall =
13315     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13316                                       Base, ResultTy, VK, OpLoc, FPOptions());
13317 
13318   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13319     return ExprError();
13320 
13321   if (CheckFunctionCall(Method, TheCall,
13322                         Method->getType()->castAs<FunctionProtoType>()))
13323     return ExprError();
13324 
13325   return MaybeBindToTemporary(TheCall);
13326 }
13327 
13328 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13329 /// a literal operator described by the provided lookup results.
13330 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13331                                           DeclarationNameInfo &SuffixInfo,
13332                                           ArrayRef<Expr*> Args,
13333                                           SourceLocation LitEndLoc,
13334                                        TemplateArgumentListInfo *TemplateArgs) {
13335   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13336 
13337   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13338                                     OverloadCandidateSet::CSK_Normal);
13339   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13340                         /*SuppressUserConversions=*/true);
13341 
13342   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13343 
13344   // Perform overload resolution. This will usually be trivial, but might need
13345   // to perform substitutions for a literal operator template.
13346   OverloadCandidateSet::iterator Best;
13347   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13348   case OR_Success:
13349   case OR_Deleted:
13350     break;
13351 
13352   case OR_No_Viable_Function:
13353     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13354       << R.getLookupName();
13355     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13356     return ExprError();
13357 
13358   case OR_Ambiguous:
13359     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13360     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13361     return ExprError();
13362   }
13363 
13364   FunctionDecl *FD = Best->Function;
13365   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13366                                         nullptr, HadMultipleCandidates,
13367                                         SuffixInfo.getLoc(),
13368                                         SuffixInfo.getInfo());
13369   if (Fn.isInvalid())
13370     return true;
13371 
13372   // Check the argument types. This should almost always be a no-op, except
13373   // that array-to-pointer decay is applied to string literals.
13374   Expr *ConvArgs[2];
13375   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13376     ExprResult InputInit = PerformCopyInitialization(
13377       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13378       SourceLocation(), Args[ArgIdx]);
13379     if (InputInit.isInvalid())
13380       return true;
13381     ConvArgs[ArgIdx] = InputInit.get();
13382   }
13383 
13384   QualType ResultTy = FD->getReturnType();
13385   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13386   ResultTy = ResultTy.getNonLValueExprType(Context);
13387 
13388   UserDefinedLiteral *UDL =
13389     new (Context) UserDefinedLiteral(Context, Fn.get(),
13390                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13391                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13392 
13393   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13394     return ExprError();
13395 
13396   if (CheckFunctionCall(FD, UDL, nullptr))
13397     return ExprError();
13398 
13399   return MaybeBindToTemporary(UDL);
13400 }
13401 
13402 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13403 /// given LookupResult is non-empty, it is assumed to describe a member which
13404 /// will be invoked. Otherwise, the function will be found via argument
13405 /// dependent lookup.
13406 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13407 /// otherwise CallExpr is set to ExprError() and some non-success value
13408 /// is returned.
13409 Sema::ForRangeStatus
13410 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13411                                 SourceLocation RangeLoc,
13412                                 const DeclarationNameInfo &NameInfo,
13413                                 LookupResult &MemberLookup,
13414                                 OverloadCandidateSet *CandidateSet,
13415                                 Expr *Range, ExprResult *CallExpr) {
13416   Scope *S = nullptr;
13417 
13418   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13419   if (!MemberLookup.empty()) {
13420     ExprResult MemberRef =
13421         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13422                                  /*IsPtr=*/false, CXXScopeSpec(),
13423                                  /*TemplateKWLoc=*/SourceLocation(),
13424                                  /*FirstQualifierInScope=*/nullptr,
13425                                  MemberLookup,
13426                                  /*TemplateArgs=*/nullptr, S);
13427     if (MemberRef.isInvalid()) {
13428       *CallExpr = ExprError();
13429       return FRS_DiagnosticIssued;
13430     }
13431     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13432     if (CallExpr->isInvalid()) {
13433       *CallExpr = ExprError();
13434       return FRS_DiagnosticIssued;
13435     }
13436   } else {
13437     UnresolvedSet<0> FoundNames;
13438     UnresolvedLookupExpr *Fn =
13439       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13440                                    NestedNameSpecifierLoc(), NameInfo,
13441                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13442                                    FoundNames.begin(), FoundNames.end());
13443 
13444     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13445                                                     CandidateSet, CallExpr);
13446     if (CandidateSet->empty() || CandidateSetError) {
13447       *CallExpr = ExprError();
13448       return FRS_NoViableFunction;
13449     }
13450     OverloadCandidateSet::iterator Best;
13451     OverloadingResult OverloadResult =
13452         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13453 
13454     if (OverloadResult == OR_No_Viable_Function) {
13455       *CallExpr = ExprError();
13456       return FRS_NoViableFunction;
13457     }
13458     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13459                                          Loc, nullptr, CandidateSet, &Best,
13460                                          OverloadResult,
13461                                          /*AllowTypoCorrection=*/false);
13462     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13463       *CallExpr = ExprError();
13464       return FRS_DiagnosticIssued;
13465     }
13466   }
13467   return FRS_Success;
13468 }
13469 
13470 
13471 /// FixOverloadedFunctionReference - E is an expression that refers to
13472 /// a C++ overloaded function (possibly with some parentheses and
13473 /// perhaps a '&' around it). We have resolved the overloaded function
13474 /// to the function declaration Fn, so patch up the expression E to
13475 /// refer (possibly indirectly) to Fn. Returns the new expr.
13476 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13477                                            FunctionDecl *Fn) {
13478   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13479     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13480                                                    Found, Fn);
13481     if (SubExpr == PE->getSubExpr())
13482       return PE;
13483 
13484     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13485   }
13486 
13487   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13488     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13489                                                    Found, Fn);
13490     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13491                                SubExpr->getType()) &&
13492            "Implicit cast type cannot be determined from overload");
13493     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13494     if (SubExpr == ICE->getSubExpr())
13495       return ICE;
13496 
13497     return ImplicitCastExpr::Create(Context, ICE->getType(),
13498                                     ICE->getCastKind(),
13499                                     SubExpr, nullptr,
13500                                     ICE->getValueKind());
13501   }
13502 
13503   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13504     if (!GSE->isResultDependent()) {
13505       Expr *SubExpr =
13506           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13507       if (SubExpr == GSE->getResultExpr())
13508         return GSE;
13509 
13510       // Replace the resulting type information before rebuilding the generic
13511       // selection expression.
13512       ArrayRef<Expr *> A = GSE->getAssocExprs();
13513       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13514       unsigned ResultIdx = GSE->getResultIndex();
13515       AssocExprs[ResultIdx] = SubExpr;
13516 
13517       return new (Context) GenericSelectionExpr(
13518           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13519           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13520           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13521           ResultIdx);
13522     }
13523     // Rather than fall through to the unreachable, return the original generic
13524     // selection expression.
13525     return GSE;
13526   }
13527 
13528   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13529     assert(UnOp->getOpcode() == UO_AddrOf &&
13530            "Can only take the address of an overloaded function");
13531     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13532       if (Method->isStatic()) {
13533         // Do nothing: static member functions aren't any different
13534         // from non-member functions.
13535       } else {
13536         // Fix the subexpression, which really has to be an
13537         // UnresolvedLookupExpr holding an overloaded member function
13538         // or template.
13539         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13540                                                        Found, Fn);
13541         if (SubExpr == UnOp->getSubExpr())
13542           return UnOp;
13543 
13544         assert(isa<DeclRefExpr>(SubExpr)
13545                && "fixed to something other than a decl ref");
13546         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13547                && "fixed to a member ref with no nested name qualifier");
13548 
13549         // We have taken the address of a pointer to member
13550         // function. Perform the computation here so that we get the
13551         // appropriate pointer to member type.
13552         QualType ClassType
13553           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13554         QualType MemPtrType
13555           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13556         // Under the MS ABI, lock down the inheritance model now.
13557         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13558           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13559 
13560         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13561                                            VK_RValue, OK_Ordinary,
13562                                            UnOp->getOperatorLoc(), false);
13563       }
13564     }
13565     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13566                                                    Found, Fn);
13567     if (SubExpr == UnOp->getSubExpr())
13568       return UnOp;
13569 
13570     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13571                                      Context.getPointerType(SubExpr->getType()),
13572                                        VK_RValue, OK_Ordinary,
13573                                        UnOp->getOperatorLoc(), false);
13574   }
13575 
13576   // C++ [except.spec]p17:
13577   //   An exception-specification is considered to be needed when:
13578   //   - in an expression the function is the unique lookup result or the
13579   //     selected member of a set of overloaded functions
13580   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13581     ResolveExceptionSpec(E->getExprLoc(), FPT);
13582 
13583   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13584     // FIXME: avoid copy.
13585     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13586     if (ULE->hasExplicitTemplateArgs()) {
13587       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13588       TemplateArgs = &TemplateArgsBuffer;
13589     }
13590 
13591     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13592                                            ULE->getQualifierLoc(),
13593                                            ULE->getTemplateKeywordLoc(),
13594                                            Fn,
13595                                            /*enclosing*/ false, // FIXME?
13596                                            ULE->getNameLoc(),
13597                                            Fn->getType(),
13598                                            VK_LValue,
13599                                            Found.getDecl(),
13600                                            TemplateArgs);
13601     MarkDeclRefReferenced(DRE);
13602     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13603     return DRE;
13604   }
13605 
13606   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13607     // FIXME: avoid copy.
13608     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13609     if (MemExpr->hasExplicitTemplateArgs()) {
13610       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13611       TemplateArgs = &TemplateArgsBuffer;
13612     }
13613 
13614     Expr *Base;
13615 
13616     // If we're filling in a static method where we used to have an
13617     // implicit member access, rewrite to a simple decl ref.
13618     if (MemExpr->isImplicitAccess()) {
13619       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13620         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13621                                                MemExpr->getQualifierLoc(),
13622                                                MemExpr->getTemplateKeywordLoc(),
13623                                                Fn,
13624                                                /*enclosing*/ false,
13625                                                MemExpr->getMemberLoc(),
13626                                                Fn->getType(),
13627                                                VK_LValue,
13628                                                Found.getDecl(),
13629                                                TemplateArgs);
13630         MarkDeclRefReferenced(DRE);
13631         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13632         return DRE;
13633       } else {
13634         SourceLocation Loc = MemExpr->getMemberLoc();
13635         if (MemExpr->getQualifier())
13636           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13637         CheckCXXThisCapture(Loc);
13638         Base = new (Context) CXXThisExpr(Loc,
13639                                          MemExpr->getBaseType(),
13640                                          /*isImplicit=*/true);
13641       }
13642     } else
13643       Base = MemExpr->getBase();
13644 
13645     ExprValueKind valueKind;
13646     QualType type;
13647     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13648       valueKind = VK_LValue;
13649       type = Fn->getType();
13650     } else {
13651       valueKind = VK_RValue;
13652       type = Context.BoundMemberTy;
13653     }
13654 
13655     MemberExpr *ME = MemberExpr::Create(
13656         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13657         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13658         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13659         OK_Ordinary);
13660     ME->setHadMultipleCandidates(true);
13661     MarkMemberReferenced(ME);
13662     return ME;
13663   }
13664 
13665   llvm_unreachable("Invalid reference to overloaded function");
13666 }
13667 
13668 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13669                                                 DeclAccessPair Found,
13670                                                 FunctionDecl *Fn) {
13671   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13672 }
13673