1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Conversion,
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_OCL_Scalar_Widening,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isMemberPointerType() ||
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 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) 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       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_IncompletePack:
632     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633   case Sema::TDK_Inconsistent:
634   case Sema::TDK_Underqualified: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637     Saved->Param = Info.Param;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Result.Data = Saved;
641     break;
642   }
643 
644   case Sema::TDK_SubstitutionFailure:
645     Result.Data = Info.take();
646     if (Info.hasSFINAEDiagnostic()) {
647       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
648           SourceLocation(), PartialDiagnostic::NullDiagnostic());
649       Info.takeSFINAEDiagnostic(*Diag);
650       Result.HasDiagnostic = true;
651     }
652     break;
653 
654   case Sema::TDK_Success:
655   case Sema::TDK_NonDependentConversionFailure:
656     llvm_unreachable("not a deduction failure");
657   }
658 
659   return Result;
660 }
661 
662 void DeductionFailureInfo::Destroy() {
663   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664   case Sema::TDK_Success:
665   case Sema::TDK_Invalid:
666   case Sema::TDK_InstantiationDepth:
667   case Sema::TDK_Incomplete:
668   case Sema::TDK_TooManyArguments:
669   case Sema::TDK_TooFewArguments:
670   case Sema::TDK_InvalidExplicitArguments:
671   case Sema::TDK_CUDATargetMismatch:
672   case Sema::TDK_NonDependentConversionFailure:
673     break;
674 
675   case Sema::TDK_IncompletePack:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_DeducedMismatch:
679   case Sema::TDK_DeducedMismatchNested:
680   case Sema::TDK_NonDeducedMismatch:
681     // FIXME: Destroy the data?
682     Data = nullptr;
683     break;
684 
685   case Sema::TDK_SubstitutionFailure:
686     // FIXME: Destroy the template argument list?
687     Data = nullptr;
688     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689       Diag->~PartialDiagnosticAt();
690       HasDiagnostic = false;
691     }
692     break;
693 
694   // Unhandled
695   case Sema::TDK_MiscellaneousDeductionFailure:
696     break;
697   }
698 }
699 
700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701   if (HasDiagnostic)
702     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703   return nullptr;
704 }
705 
706 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708   case Sema::TDK_Success:
709   case Sema::TDK_Invalid:
710   case Sema::TDK_InstantiationDepth:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_SubstitutionFailure:
714   case Sema::TDK_DeducedMismatch:
715   case Sema::TDK_DeducedMismatchNested:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     return TemplateParameter();
720 
721   case Sema::TDK_Incomplete:
722   case Sema::TDK_InvalidExplicitArguments:
723     return TemplateParameter::getFromOpaqueValue(Data);
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728     return static_cast<DFIParamWithArguments*>(Data)->Param;
729 
730   // Unhandled
731   case Sema::TDK_MiscellaneousDeductionFailure:
732     break;
733   }
734 
735   return TemplateParameter();
736 }
737 
738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740   case Sema::TDK_Success:
741   case Sema::TDK_Invalid:
742   case Sema::TDK_InstantiationDepth:
743   case Sema::TDK_TooManyArguments:
744   case Sema::TDK_TooFewArguments:
745   case Sema::TDK_Incomplete:
746   case Sema::TDK_IncompletePack:
747   case Sema::TDK_InvalidExplicitArguments:
748   case Sema::TDK_Inconsistent:
749   case Sema::TDK_Underqualified:
750   case Sema::TDK_NonDeducedMismatch:
751   case Sema::TDK_CUDATargetMismatch:
752   case Sema::TDK_NonDependentConversionFailure:
753     return nullptr;
754 
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758 
759   case Sema::TDK_SubstitutionFailure:
760     return static_cast<TemplateArgumentList*>(Data);
761 
762   // Unhandled
763   case Sema::TDK_MiscellaneousDeductionFailure:
764     break;
765   }
766 
767   return nullptr;
768 }
769 
770 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772   case Sema::TDK_Success:
773   case Sema::TDK_Invalid:
774   case Sema::TDK_InstantiationDepth:
775   case Sema::TDK_Incomplete:
776   case Sema::TDK_TooManyArguments:
777   case Sema::TDK_TooFewArguments:
778   case Sema::TDK_InvalidExplicitArguments:
779   case Sema::TDK_SubstitutionFailure:
780   case Sema::TDK_CUDATargetMismatch:
781   case Sema::TDK_NonDependentConversionFailure:
782     return nullptr;
783 
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_Inconsistent:
786   case Sema::TDK_Underqualified:
787   case Sema::TDK_DeducedMismatch:
788   case Sema::TDK_DeducedMismatchNested:
789   case Sema::TDK_NonDeducedMismatch:
790     return &static_cast<DFIArguments*>(Data)->FirstArg;
791 
792   // Unhandled
793   case Sema::TDK_MiscellaneousDeductionFailure:
794     break;
795   }
796 
797   return nullptr;
798 }
799 
800 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_Incomplete:
806   case Sema::TDK_IncompletePack:
807   case Sema::TDK_TooManyArguments:
808   case Sema::TDK_TooFewArguments:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_SubstitutionFailure:
811   case Sema::TDK_CUDATargetMismatch:
812   case Sema::TDK_NonDependentConversionFailure:
813     return nullptr;
814 
815   case Sema::TDK_Inconsistent:
816   case Sema::TDK_Underqualified:
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819   case Sema::TDK_NonDeducedMismatch:
820     return &static_cast<DFIArguments*>(Data)->SecondArg;
821 
822   // Unhandled
823   case Sema::TDK_MiscellaneousDeductionFailure:
824     break;
825   }
826 
827   return nullptr;
828 }
829 
830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
831   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835 
836   default:
837     return llvm::None;
838   }
839 }
840 
841 void OverloadCandidateSet::destroyCandidates() {
842   for (iterator i = begin(), e = end(); i != e; ++i) {
843     for (auto &C : i->Conversions)
844       C.~ImplicitConversionSequence();
845     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
846       i->DeductionFailure.Destroy();
847   }
848 }
849 
850 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851   destroyCandidates();
852   SlabAllocator.Reset();
853   NumInlineBytesUsed = 0;
854   Candidates.clear();
855   Functions.clear();
856   Kind = CSK;
857 }
858 
859 namespace {
860   class UnbridgedCastsSet {
861     struct Entry {
862       Expr **Addr;
863       Expr *Saved;
864     };
865     SmallVector<Entry, 2> Entries;
866 
867   public:
868     void save(Sema &S, Expr *&E) {
869       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870       Entry entry = { &E, E };
871       Entries.push_back(entry);
872       E = S.stripARCUnbridgedCast(E);
873     }
874 
875     void restore() {
876       for (SmallVectorImpl<Entry>::iterator
877              i = Entries.begin(), e = Entries.end(); i != e; ++i)
878         *i->Addr = i->Saved;
879     }
880   };
881 }
882 
883 /// checkPlaceholderForOverload - Do any interesting placeholder-like
884 /// preprocessing on the given expression.
885 ///
886 /// \param unbridgedCasts a collection to which to add unbridged casts;
887 ///   without this, they will be immediately diagnosed as errors
888 ///
889 /// Return true on unrecoverable error.
890 static bool
891 checkPlaceholderForOverload(Sema &S, Expr *&E,
892                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
893   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894     // We can't handle overloaded expressions here because overload
895     // resolution might reasonably tweak them.
896     if (placeholder->getKind() == BuiltinType::Overload) return false;
897 
898     // If the context potentially accepts unbridged ARC casts, strip
899     // the unbridged cast and add it to the collection for later restoration.
900     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901         unbridgedCasts) {
902       unbridgedCasts->save(S, E);
903       return false;
904     }
905 
906     // Go ahead and check everything else.
907     ExprResult result = S.CheckPlaceholderExpr(E);
908     if (result.isInvalid())
909       return true;
910 
911     E = result.get();
912     return false;
913   }
914 
915   // Nothing to do.
916   return false;
917 }
918 
919 /// checkArgPlaceholdersForOverload - Check a set of call operands for
920 /// placeholders.
921 static bool checkArgPlaceholdersForOverload(Sema &S,
922                                             MultiExprArg Args,
923                                             UnbridgedCastsSet &unbridged) {
924   for (unsigned i = 0, e = Args.size(); i != e; ++i)
925     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926       return true;
927 
928   return false;
929 }
930 
931 /// Determine whether the given New declaration is an overload of the
932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933 /// New and Old cannot be overloaded, e.g., if New has the same signature as
934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935 /// functions (or function templates) at all. When it does return Ovl_Match or
936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938 /// declaration.
939 ///
940 /// Example: Given the following input:
941 ///
942 ///   void f(int, float); // #1
943 ///   void f(int, int); // #2
944 ///   int f(int, int); // #3
945 ///
946 /// When we process #1, there is no previous declaration of "f", so IsOverload
947 /// will not be used.
948 ///
949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950 /// the parameter types, we see that #1 and #2 are overloaded (since they have
951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952 /// unchanged.
953 ///
954 /// When we process #3, Old is an overload set containing #1 and #2. We compare
955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957 /// functions are not part of the signature), IsOverload returns Ovl_Match and
958 /// MatchedDecl will be set to point to the FunctionDecl for #2.
959 ///
960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961 /// by a using declaration. The rules for whether to hide shadow declarations
962 /// ignore some properties which otherwise figure into a function template's
963 /// signature.
964 Sema::OverloadKind
965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
966                     NamedDecl *&Match, bool NewIsUsingDecl) {
967   for (LookupResult::iterator I = Old.begin(), E = Old.end();
968          I != E; ++I) {
969     NamedDecl *OldD = *I;
970 
971     bool OldIsUsingDecl = false;
972     if (isa<UsingShadowDecl>(OldD)) {
973       OldIsUsingDecl = true;
974 
975       // We can always introduce two using declarations into the same
976       // context, even if they have identical signatures.
977       if (NewIsUsingDecl) continue;
978 
979       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980     }
981 
982     // A using-declaration does not conflict with another declaration
983     // if one of them is hidden.
984     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985       continue;
986 
987     // If either declaration was introduced by a using declaration,
988     // we'll need to use slightly different rules for matching.
989     // Essentially, these rules are the normal rules, except that
990     // function templates hide function templates with different
991     // return types or template parameter lists.
992     bool UseMemberUsingDeclRules =
993       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
994       !New->getFriendObjectKind();
995 
996     if (FunctionDecl *OldF = OldD->getAsFunction()) {
997       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
998         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
999           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000           continue;
1001         }
1002 
1003         if (!isa<FunctionTemplateDecl>(OldD) &&
1004             !shouldLinkPossiblyHiddenDecl(*I, New))
1005           continue;
1006 
1007         Match = *I;
1008         return Ovl_Match;
1009       }
1010 
1011       // Builtins that have custom typechecking or have a reference should
1012       // not be overloadable or redeclarable.
1013       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1018       // We can overload with these, which can show up when doing
1019       // redeclaration checks for UsingDecls.
1020       assert(Old.getLookupKind() == LookupUsingDeclName);
1021     } else if (isa<TagDecl>(OldD)) {
1022       // We can always overload with tags by hiding them.
1023     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024       // Optimistically assume that an unresolved using decl will
1025       // overload; if it doesn't, we'll have to diagnose during
1026       // template instantiation.
1027       //
1028       // Exception: if the scope is dependent and this is not a class
1029       // member, the using declaration can only introduce an enumerator.
1030       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031         Match = *I;
1032         return Ovl_NonFunction;
1033       }
1034     } else {
1035       // (C++ 13p1):
1036       //   Only function declarations can be overloaded; object and type
1037       //   declarations cannot be overloaded.
1038       Match = *I;
1039       return Ovl_NonFunction;
1040     }
1041   }
1042 
1043   // C++ [temp.friend]p1:
1044   //   For a friend function declaration that is not a template declaration:
1045   //    -- if the name of the friend is a qualified or unqualified template-id,
1046   //       [...], otherwise
1047   //    -- if the name of the friend is a qualified-id and a matching
1048   //       non-template function is found in the specified class or namespace,
1049   //       the friend declaration refers to that function, otherwise,
1050   //    -- if the name of the friend is a qualified-id and a matching function
1051   //       template is found in the specified class or namespace, the friend
1052   //       declaration refers to the deduced specialization of that function
1053   //       template, otherwise
1054   //    -- the name shall be an unqualified-id [...]
1055   // If we get here for a qualified friend declaration, we've just reached the
1056   // third bullet. If the type of the friend is dependent, skip this lookup
1057   // until instantiation.
1058   if (New->getFriendObjectKind() && New->getQualifier() &&
1059       !New->getDescribedFunctionTemplate() &&
1060       !New->getDependentSpecializationInfo() &&
1061       !New->getType()->isDependentType()) {
1062     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1063     TemplateSpecResult.addAllDecls(Old);
1064     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1065                                             /*QualifiedFriend*/true)) {
1066       New->setInvalidDecl();
1067       return Ovl_Overload;
1068     }
1069 
1070     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1071     return Ovl_Match;
1072   }
1073 
1074   return Ovl_Overload;
1075 }
1076 
1077 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1078                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1079   // C++ [basic.start.main]p2: This function shall not be overloaded.
1080   if (New->isMain())
1081     return false;
1082 
1083   // MSVCRT user defined entry points cannot be overloaded.
1084   if (New->isMSVCRTEntryPoint())
1085     return false;
1086 
1087   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1088   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1089 
1090   // C++ [temp.fct]p2:
1091   //   A function template can be overloaded with other function templates
1092   //   and with normal (non-template) functions.
1093   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1094     return true;
1095 
1096   // Is the function New an overload of the function Old?
1097   QualType OldQType = Context.getCanonicalType(Old->getType());
1098   QualType NewQType = Context.getCanonicalType(New->getType());
1099 
1100   // Compare the signatures (C++ 1.3.10) of the two functions to
1101   // determine whether they are overloads. If we find any mismatch
1102   // in the signature, they are overloads.
1103 
1104   // If either of these functions is a K&R-style function (no
1105   // prototype), then we consider them to have matching signatures.
1106   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1107       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1108     return false;
1109 
1110   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1111   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1112 
1113   // The signature of a function includes the types of its
1114   // parameters (C++ 1.3.10), which includes the presence or absence
1115   // of the ellipsis; see C++ DR 357).
1116   if (OldQType != NewQType &&
1117       (OldType->getNumParams() != NewType->getNumParams() ||
1118        OldType->isVariadic() != NewType->isVariadic() ||
1119        !FunctionParamTypesAreEqual(OldType, NewType)))
1120     return true;
1121 
1122   // C++ [temp.over.link]p4:
1123   //   The signature of a function template consists of its function
1124   //   signature, its return type and its template parameter list. The names
1125   //   of the template parameters are significant only for establishing the
1126   //   relationship between the template parameters and the rest of the
1127   //   signature.
1128   //
1129   // We check the return type and template parameter lists for function
1130   // templates first; the remaining checks follow.
1131   //
1132   // However, we don't consider either of these when deciding whether
1133   // a member introduced by a shadow declaration is hidden.
1134   if (!UseMemberUsingDeclRules && NewTemplate &&
1135       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1136                                        OldTemplate->getTemplateParameters(),
1137                                        false, TPL_TemplateMatch) ||
1138        !Context.hasSameType(Old->getDeclaredReturnType(),
1139                             New->getDeclaredReturnType())))
1140     return true;
1141 
1142   // If the function is a class member, its signature includes the
1143   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1144   //
1145   // As part of this, also check whether one of the member functions
1146   // is static, in which case they are not overloads (C++
1147   // 13.1p2). While not part of the definition of the signature,
1148   // this check is important to determine whether these functions
1149   // can be overloaded.
1150   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1151   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1152   if (OldMethod && NewMethod &&
1153       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1154     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1155       if (!UseMemberUsingDeclRules &&
1156           (OldMethod->getRefQualifier() == RQ_None ||
1157            NewMethod->getRefQualifier() == RQ_None)) {
1158         // C++0x [over.load]p2:
1159         //   - Member function declarations with the same name and the same
1160         //     parameter-type-list as well as member function template
1161         //     declarations with the same name, the same parameter-type-list, and
1162         //     the same template parameter lists cannot be overloaded if any of
1163         //     them, but not all, have a ref-qualifier (8.3.5).
1164         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1165           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1166         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1167       }
1168       return true;
1169     }
1170 
1171     // We may not have applied the implicit const for a constexpr member
1172     // function yet (because we haven't yet resolved whether this is a static
1173     // or non-static member function). Add it now, on the assumption that this
1174     // is a redeclaration of OldMethod.
1175     auto OldQuals = OldMethod->getMethodQualifiers();
1176     auto NewQuals = NewMethod->getMethodQualifiers();
1177     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1178         !isa<CXXConstructorDecl>(NewMethod))
1179       NewQuals.addConst();
1180     // We do not allow overloading based off of '__restrict'.
1181     OldQuals.removeRestrict();
1182     NewQuals.removeRestrict();
1183     if (OldQuals != NewQuals)
1184       return true;
1185   }
1186 
1187   // Though pass_object_size is placed on parameters and takes an argument, we
1188   // consider it to be a function-level modifier for the sake of function
1189   // identity. Either the function has one or more parameters with
1190   // pass_object_size or it doesn't.
1191   if (functionHasPassObjectSizeParams(New) !=
1192       functionHasPassObjectSizeParams(Old))
1193     return true;
1194 
1195   // enable_if attributes are an order-sensitive part of the signature.
1196   for (specific_attr_iterator<EnableIfAttr>
1197          NewI = New->specific_attr_begin<EnableIfAttr>(),
1198          NewE = New->specific_attr_end<EnableIfAttr>(),
1199          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1200          OldE = Old->specific_attr_end<EnableIfAttr>();
1201        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1202     if (NewI == NewE || OldI == OldE)
1203       return true;
1204     llvm::FoldingSetNodeID NewID, OldID;
1205     NewI->getCond()->Profile(NewID, Context, true);
1206     OldI->getCond()->Profile(OldID, Context, true);
1207     if (NewID != OldID)
1208       return true;
1209   }
1210 
1211   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1212     // Don't allow overloading of destructors.  (In theory we could, but it
1213     // would be a giant change to clang.)
1214     if (isa<CXXDestructorDecl>(New))
1215       return false;
1216 
1217     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1218                        OldTarget = IdentifyCUDATarget(Old);
1219     if (NewTarget == CFT_InvalidTarget)
1220       return false;
1221 
1222     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1223 
1224     // Allow overloading of functions with same signature and different CUDA
1225     // target attributes.
1226     return NewTarget != OldTarget;
1227   }
1228 
1229   // The signatures match; this is not an overload.
1230   return false;
1231 }
1232 
1233 /// Tries a user-defined conversion from From to ToType.
1234 ///
1235 /// Produces an implicit conversion sequence for when a standard conversion
1236 /// is not an option. See TryImplicitConversion for more information.
1237 static ImplicitConversionSequence
1238 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1239                          bool SuppressUserConversions,
1240                          bool AllowExplicit,
1241                          bool InOverloadResolution,
1242                          bool CStyle,
1243                          bool AllowObjCWritebackConversion,
1244                          bool AllowObjCConversionOnExplicit) {
1245   ImplicitConversionSequence ICS;
1246 
1247   if (SuppressUserConversions) {
1248     // We're not in the case above, so there is no conversion that
1249     // we can perform.
1250     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1251     return ICS;
1252   }
1253 
1254   // Attempt user-defined conversion.
1255   OverloadCandidateSet Conversions(From->getExprLoc(),
1256                                    OverloadCandidateSet::CSK_Normal);
1257   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1258                                   Conversions, AllowExplicit,
1259                                   AllowObjCConversionOnExplicit)) {
1260   case OR_Success:
1261   case OR_Deleted:
1262     ICS.setUserDefined();
1263     // C++ [over.ics.user]p4:
1264     //   A conversion of an expression of class type to the same class
1265     //   type is given Exact Match rank, and a conversion of an
1266     //   expression of class type to a base class of that type is
1267     //   given Conversion rank, in spite of the fact that a copy
1268     //   constructor (i.e., a user-defined conversion function) is
1269     //   called for those cases.
1270     if (CXXConstructorDecl *Constructor
1271           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1272       QualType FromCanon
1273         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1274       QualType ToCanon
1275         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1276       if (Constructor->isCopyConstructor() &&
1277           (FromCanon == ToCanon ||
1278            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1279         // Turn this into a "standard" conversion sequence, so that it
1280         // gets ranked with standard conversion sequences.
1281         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1282         ICS.setStandard();
1283         ICS.Standard.setAsIdentityConversion();
1284         ICS.Standard.setFromType(From->getType());
1285         ICS.Standard.setAllToTypes(ToType);
1286         ICS.Standard.CopyConstructor = Constructor;
1287         ICS.Standard.FoundCopyConstructor = Found;
1288         if (ToCanon != FromCanon)
1289           ICS.Standard.Second = ICK_Derived_To_Base;
1290       }
1291     }
1292     break;
1293 
1294   case OR_Ambiguous:
1295     ICS.setAmbiguous();
1296     ICS.Ambiguous.setFromType(From->getType());
1297     ICS.Ambiguous.setToType(ToType);
1298     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1299          Cand != Conversions.end(); ++Cand)
1300       if (Cand->Viable)
1301         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1302     break;
1303 
1304     // Fall through.
1305   case OR_No_Viable_Function:
1306     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1307     break;
1308   }
1309 
1310   return ICS;
1311 }
1312 
1313 /// TryImplicitConversion - Attempt to perform an implicit conversion
1314 /// from the given expression (Expr) to the given type (ToType). This
1315 /// function returns an implicit conversion sequence that can be used
1316 /// to perform the initialization. Given
1317 ///
1318 ///   void f(float f);
1319 ///   void g(int i) { f(i); }
1320 ///
1321 /// this routine would produce an implicit conversion sequence to
1322 /// describe the initialization of f from i, which will be a standard
1323 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1324 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1325 //
1326 /// Note that this routine only determines how the conversion can be
1327 /// performed; it does not actually perform the conversion. As such,
1328 /// it will not produce any diagnostics if no conversion is available,
1329 /// but will instead return an implicit conversion sequence of kind
1330 /// "BadConversion".
1331 ///
1332 /// If @p SuppressUserConversions, then user-defined conversions are
1333 /// not permitted.
1334 /// If @p AllowExplicit, then explicit user-defined conversions are
1335 /// permitted.
1336 ///
1337 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1338 /// writeback conversion, which allows __autoreleasing id* parameters to
1339 /// be initialized with __strong id* or __weak id* arguments.
1340 static ImplicitConversionSequence
1341 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1342                       bool SuppressUserConversions,
1343                       bool AllowExplicit,
1344                       bool InOverloadResolution,
1345                       bool CStyle,
1346                       bool AllowObjCWritebackConversion,
1347                       bool AllowObjCConversionOnExplicit) {
1348   ImplicitConversionSequence ICS;
1349   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1350                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1351     ICS.setStandard();
1352     return ICS;
1353   }
1354 
1355   if (!S.getLangOpts().CPlusPlus) {
1356     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1357     return ICS;
1358   }
1359 
1360   // C++ [over.ics.user]p4:
1361   //   A conversion of an expression of class type to the same class
1362   //   type is given Exact Match rank, and a conversion of an
1363   //   expression of class type to a base class of that type is
1364   //   given Conversion rank, in spite of the fact that a copy/move
1365   //   constructor (i.e., a user-defined conversion function) is
1366   //   called for those cases.
1367   QualType FromType = From->getType();
1368   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1369       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1370        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1371     ICS.setStandard();
1372     ICS.Standard.setAsIdentityConversion();
1373     ICS.Standard.setFromType(FromType);
1374     ICS.Standard.setAllToTypes(ToType);
1375 
1376     // We don't actually check at this point whether there is a valid
1377     // copy/move constructor, since overloading just assumes that it
1378     // exists. When we actually perform initialization, we'll find the
1379     // appropriate constructor to copy the returned object, if needed.
1380     ICS.Standard.CopyConstructor = nullptr;
1381 
1382     // Determine whether this is considered a derived-to-base conversion.
1383     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1384       ICS.Standard.Second = ICK_Derived_To_Base;
1385 
1386     return ICS;
1387   }
1388 
1389   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1390                                   AllowExplicit, InOverloadResolution, CStyle,
1391                                   AllowObjCWritebackConversion,
1392                                   AllowObjCConversionOnExplicit);
1393 }
1394 
1395 ImplicitConversionSequence
1396 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1397                             bool SuppressUserConversions,
1398                             bool AllowExplicit,
1399                             bool InOverloadResolution,
1400                             bool CStyle,
1401                             bool AllowObjCWritebackConversion) {
1402   return ::TryImplicitConversion(*this, From, ToType,
1403                                  SuppressUserConversions, AllowExplicit,
1404                                  InOverloadResolution, CStyle,
1405                                  AllowObjCWritebackConversion,
1406                                  /*AllowObjCConversionOnExplicit=*/false);
1407 }
1408 
1409 /// PerformImplicitConversion - Perform an implicit conversion of the
1410 /// expression From to the type ToType. Returns the
1411 /// converted expression. Flavor is the kind of conversion we're
1412 /// performing, used in the error message. If @p AllowExplicit,
1413 /// explicit user-defined conversions are permitted.
1414 ExprResult
1415 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1416                                 AssignmentAction Action, bool AllowExplicit) {
1417   ImplicitConversionSequence ICS;
1418   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1419 }
1420 
1421 ExprResult
1422 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1423                                 AssignmentAction Action, bool AllowExplicit,
1424                                 ImplicitConversionSequence& ICS) {
1425   if (checkPlaceholderForOverload(*this, From))
1426     return ExprError();
1427 
1428   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1429   bool AllowObjCWritebackConversion
1430     = getLangOpts().ObjCAutoRefCount &&
1431       (Action == AA_Passing || Action == AA_Sending);
1432   if (getLangOpts().ObjC)
1433     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1434                                       From->getType(), From);
1435   ICS = ::TryImplicitConversion(*this, From, ToType,
1436                                 /*SuppressUserConversions=*/false,
1437                                 AllowExplicit,
1438                                 /*InOverloadResolution=*/false,
1439                                 /*CStyle=*/false,
1440                                 AllowObjCWritebackConversion,
1441                                 /*AllowObjCConversionOnExplicit=*/false);
1442   return PerformImplicitConversion(From, ToType, ICS, Action);
1443 }
1444 
1445 /// Determine whether the conversion from FromType to ToType is a valid
1446 /// conversion that strips "noexcept" or "noreturn" off the nested function
1447 /// type.
1448 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1449                                 QualType &ResultTy) {
1450   if (Context.hasSameUnqualifiedType(FromType, ToType))
1451     return false;
1452 
1453   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1454   //                    or F(t noexcept) -> F(t)
1455   // where F adds one of the following at most once:
1456   //   - a pointer
1457   //   - a member pointer
1458   //   - a block pointer
1459   // Changes here need matching changes in FindCompositePointerType.
1460   CanQualType CanTo = Context.getCanonicalType(ToType);
1461   CanQualType CanFrom = Context.getCanonicalType(FromType);
1462   Type::TypeClass TyClass = CanTo->getTypeClass();
1463   if (TyClass != CanFrom->getTypeClass()) return false;
1464   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1465     if (TyClass == Type::Pointer) {
1466       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1467       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1468     } else if (TyClass == Type::BlockPointer) {
1469       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1470       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1471     } else if (TyClass == Type::MemberPointer) {
1472       auto ToMPT = CanTo.getAs<MemberPointerType>();
1473       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1474       // A function pointer conversion cannot change the class of the function.
1475       if (ToMPT->getClass() != FromMPT->getClass())
1476         return false;
1477       CanTo = ToMPT->getPointeeType();
1478       CanFrom = FromMPT->getPointeeType();
1479     } else {
1480       return false;
1481     }
1482 
1483     TyClass = CanTo->getTypeClass();
1484     if (TyClass != CanFrom->getTypeClass()) return false;
1485     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1486       return false;
1487   }
1488 
1489   const auto *FromFn = cast<FunctionType>(CanFrom);
1490   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1491 
1492   const auto *ToFn = cast<FunctionType>(CanTo);
1493   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1494 
1495   bool Changed = false;
1496 
1497   // Drop 'noreturn' if not present in target type.
1498   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1499     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1500     Changed = true;
1501   }
1502 
1503   // Drop 'noexcept' if not present in target type.
1504   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1505     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1506     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1507       FromFn = cast<FunctionType>(
1508           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1509                                                    EST_None)
1510                  .getTypePtr());
1511       Changed = true;
1512     }
1513 
1514     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1515     // only if the ExtParameterInfo lists of the two function prototypes can be
1516     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1517     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1518     bool CanUseToFPT, CanUseFromFPT;
1519     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1520                                       CanUseFromFPT, NewParamInfos) &&
1521         CanUseToFPT && !CanUseFromFPT) {
1522       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1523       ExtInfo.ExtParameterInfos =
1524           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1525       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1526                                             FromFPT->getParamTypes(), ExtInfo);
1527       FromFn = QT->getAs<FunctionType>();
1528       Changed = true;
1529     }
1530   }
1531 
1532   if (!Changed)
1533     return false;
1534 
1535   assert(QualType(FromFn, 0).isCanonical());
1536   if (QualType(FromFn, 0) != CanTo) return false;
1537 
1538   ResultTy = ToType;
1539   return true;
1540 }
1541 
1542 /// Determine whether the conversion from FromType to ToType is a valid
1543 /// vector conversion.
1544 ///
1545 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1546 /// conversion.
1547 static bool IsVectorConversion(Sema &S, QualType FromType,
1548                                QualType ToType, ImplicitConversionKind &ICK) {
1549   // We need at least one of these types to be a vector type to have a vector
1550   // conversion.
1551   if (!ToType->isVectorType() && !FromType->isVectorType())
1552     return false;
1553 
1554   // Identical types require no conversions.
1555   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1556     return false;
1557 
1558   // There are no conversions between extended vector types, only identity.
1559   if (ToType->isExtVectorType()) {
1560     // There are no conversions between extended vector types other than the
1561     // identity conversion.
1562     if (FromType->isExtVectorType())
1563       return false;
1564 
1565     // Vector splat from any arithmetic type to a vector.
1566     if (FromType->isArithmeticType()) {
1567       ICK = ICK_Vector_Splat;
1568       return true;
1569     }
1570   }
1571 
1572   // We can perform the conversion between vector types in the following cases:
1573   // 1)vector types are equivalent AltiVec and GCC vector types
1574   // 2)lax vector conversions are permitted and the vector types are of the
1575   //   same size
1576   if (ToType->isVectorType() && FromType->isVectorType()) {
1577     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1578         S.isLaxVectorConversion(FromType, ToType)) {
1579       ICK = ICK_Vector_Conversion;
1580       return true;
1581     }
1582   }
1583 
1584   return false;
1585 }
1586 
1587 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1588                                 bool InOverloadResolution,
1589                                 StandardConversionSequence &SCS,
1590                                 bool CStyle);
1591 
1592 /// IsStandardConversion - Determines whether there is a standard
1593 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1594 /// expression From to the type ToType. Standard conversion sequences
1595 /// only consider non-class types; for conversions that involve class
1596 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1597 /// contain the standard conversion sequence required to perform this
1598 /// conversion and this routine will return true. Otherwise, this
1599 /// routine will return false and the value of SCS is unspecified.
1600 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1601                                  bool InOverloadResolution,
1602                                  StandardConversionSequence &SCS,
1603                                  bool CStyle,
1604                                  bool AllowObjCWritebackConversion) {
1605   QualType FromType = From->getType();
1606 
1607   // Standard conversions (C++ [conv])
1608   SCS.setAsIdentityConversion();
1609   SCS.IncompatibleObjC = false;
1610   SCS.setFromType(FromType);
1611   SCS.CopyConstructor = nullptr;
1612 
1613   // There are no standard conversions for class types in C++, so
1614   // abort early. When overloading in C, however, we do permit them.
1615   if (S.getLangOpts().CPlusPlus &&
1616       (FromType->isRecordType() || ToType->isRecordType()))
1617     return false;
1618 
1619   // The first conversion can be an lvalue-to-rvalue conversion,
1620   // array-to-pointer conversion, or function-to-pointer conversion
1621   // (C++ 4p1).
1622 
1623   if (FromType == S.Context.OverloadTy) {
1624     DeclAccessPair AccessPair;
1625     if (FunctionDecl *Fn
1626           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1627                                                  AccessPair)) {
1628       // We were able to resolve the address of the overloaded function,
1629       // so we can convert to the type of that function.
1630       FromType = Fn->getType();
1631       SCS.setFromType(FromType);
1632 
1633       // we can sometimes resolve &foo<int> regardless of ToType, so check
1634       // if the type matches (identity) or we are converting to bool
1635       if (!S.Context.hasSameUnqualifiedType(
1636                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1637         QualType resultTy;
1638         // if the function type matches except for [[noreturn]], it's ok
1639         if (!S.IsFunctionConversion(FromType,
1640               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1641           // otherwise, only a boolean conversion is standard
1642           if (!ToType->isBooleanType())
1643             return false;
1644       }
1645 
1646       // Check if the "from" expression is taking the address of an overloaded
1647       // function and recompute the FromType accordingly. Take advantage of the
1648       // fact that non-static member functions *must* have such an address-of
1649       // expression.
1650       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1651       if (Method && !Method->isStatic()) {
1652         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1653                "Non-unary operator on non-static member address");
1654         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1655                == UO_AddrOf &&
1656                "Non-address-of operator on non-static member address");
1657         const Type *ClassType
1658           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1659         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1660       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1661         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1662                UO_AddrOf &&
1663                "Non-address-of operator for overloaded function expression");
1664         FromType = S.Context.getPointerType(FromType);
1665       }
1666 
1667       // Check that we've computed the proper type after overload resolution.
1668       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1669       // be calling it from within an NDEBUG block.
1670       assert(S.Context.hasSameType(
1671         FromType,
1672         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1673     } else {
1674       return false;
1675     }
1676   }
1677   // Lvalue-to-rvalue conversion (C++11 4.1):
1678   //   A glvalue (3.10) of a non-function, non-array type T can
1679   //   be converted to a prvalue.
1680   bool argIsLValue = From->isGLValue();
1681   if (argIsLValue &&
1682       !FromType->isFunctionType() && !FromType->isArrayType() &&
1683       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1684     SCS.First = ICK_Lvalue_To_Rvalue;
1685 
1686     // C11 6.3.2.1p2:
1687     //   ... if the lvalue has atomic type, the value has the non-atomic version
1688     //   of the type of the lvalue ...
1689     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1690       FromType = Atomic->getValueType();
1691 
1692     // If T is a non-class type, the type of the rvalue is the
1693     // cv-unqualified version of T. Otherwise, the type of the rvalue
1694     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1695     // just strip the qualifiers because they don't matter.
1696     FromType = FromType.getUnqualifiedType();
1697   } else if (FromType->isArrayType()) {
1698     // Array-to-pointer conversion (C++ 4.2)
1699     SCS.First = ICK_Array_To_Pointer;
1700 
1701     // An lvalue or rvalue of type "array of N T" or "array of unknown
1702     // bound of T" can be converted to an rvalue of type "pointer to
1703     // T" (C++ 4.2p1).
1704     FromType = S.Context.getArrayDecayedType(FromType);
1705 
1706     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1707       // This conversion is deprecated in C++03 (D.4)
1708       SCS.DeprecatedStringLiteralToCharPtr = true;
1709 
1710       // For the purpose of ranking in overload resolution
1711       // (13.3.3.1.1), this conversion is considered an
1712       // array-to-pointer conversion followed by a qualification
1713       // conversion (4.4). (C++ 4.2p2)
1714       SCS.Second = ICK_Identity;
1715       SCS.Third = ICK_Qualification;
1716       SCS.QualificationIncludesObjCLifetime = false;
1717       SCS.setAllToTypes(FromType);
1718       return true;
1719     }
1720   } else if (FromType->isFunctionType() && argIsLValue) {
1721     // Function-to-pointer conversion (C++ 4.3).
1722     SCS.First = ICK_Function_To_Pointer;
1723 
1724     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1725       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1726         if (!S.checkAddressOfFunctionIsAvailable(FD))
1727           return false;
1728 
1729     // An lvalue of function type T can be converted to an rvalue of
1730     // type "pointer to T." The result is a pointer to the
1731     // function. (C++ 4.3p1).
1732     FromType = S.Context.getPointerType(FromType);
1733   } else {
1734     // We don't require any conversions for the first step.
1735     SCS.First = ICK_Identity;
1736   }
1737   SCS.setToType(0, FromType);
1738 
1739   // The second conversion can be an integral promotion, floating
1740   // point promotion, integral conversion, floating point conversion,
1741   // floating-integral conversion, pointer conversion,
1742   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1743   // For overloading in C, this can also be a "compatible-type"
1744   // conversion.
1745   bool IncompatibleObjC = false;
1746   ImplicitConversionKind SecondICK = ICK_Identity;
1747   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1748     // The unqualified versions of the types are the same: there's no
1749     // conversion to do.
1750     SCS.Second = ICK_Identity;
1751   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1752     // Integral promotion (C++ 4.5).
1753     SCS.Second = ICK_Integral_Promotion;
1754     FromType = ToType.getUnqualifiedType();
1755   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1756     // Floating point promotion (C++ 4.6).
1757     SCS.Second = ICK_Floating_Promotion;
1758     FromType = ToType.getUnqualifiedType();
1759   } else if (S.IsComplexPromotion(FromType, ToType)) {
1760     // Complex promotion (Clang extension)
1761     SCS.Second = ICK_Complex_Promotion;
1762     FromType = ToType.getUnqualifiedType();
1763   } else if (ToType->isBooleanType() &&
1764              (FromType->isArithmeticType() ||
1765               FromType->isAnyPointerType() ||
1766               FromType->isBlockPointerType() ||
1767               FromType->isMemberPointerType() ||
1768               FromType->isNullPtrType())) {
1769     // Boolean conversions (C++ 4.12).
1770     SCS.Second = ICK_Boolean_Conversion;
1771     FromType = S.Context.BoolTy;
1772   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1773              ToType->isIntegralType(S.Context)) {
1774     // Integral conversions (C++ 4.7).
1775     SCS.Second = ICK_Integral_Conversion;
1776     FromType = ToType.getUnqualifiedType();
1777   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1778     // Complex conversions (C99 6.3.1.6)
1779     SCS.Second = ICK_Complex_Conversion;
1780     FromType = ToType.getUnqualifiedType();
1781   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1782              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1783     // Complex-real conversions (C99 6.3.1.7)
1784     SCS.Second = ICK_Complex_Real;
1785     FromType = ToType.getUnqualifiedType();
1786   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1787     // FIXME: disable conversions between long double and __float128 if
1788     // their representation is different until there is back end support
1789     // We of course allow this conversion if long double is really double.
1790     if (&S.Context.getFloatTypeSemantics(FromType) !=
1791         &S.Context.getFloatTypeSemantics(ToType)) {
1792       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1793                                     ToType == S.Context.LongDoubleTy) ||
1794                                    (FromType == S.Context.LongDoubleTy &&
1795                                     ToType == S.Context.Float128Ty));
1796       if (Float128AndLongDouble &&
1797           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1798            &llvm::APFloat::PPCDoubleDouble()))
1799         return false;
1800     }
1801     // Floating point conversions (C++ 4.8).
1802     SCS.Second = ICK_Floating_Conversion;
1803     FromType = ToType.getUnqualifiedType();
1804   } else if ((FromType->isRealFloatingType() &&
1805               ToType->isIntegralType(S.Context)) ||
1806              (FromType->isIntegralOrUnscopedEnumerationType() &&
1807               ToType->isRealFloatingType())) {
1808     // Floating-integral conversions (C++ 4.9).
1809     SCS.Second = ICK_Floating_Integral;
1810     FromType = ToType.getUnqualifiedType();
1811   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1812     SCS.Second = ICK_Block_Pointer_Conversion;
1813   } else if (AllowObjCWritebackConversion &&
1814              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1815     SCS.Second = ICK_Writeback_Conversion;
1816   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1817                                    FromType, IncompatibleObjC)) {
1818     // Pointer conversions (C++ 4.10).
1819     SCS.Second = ICK_Pointer_Conversion;
1820     SCS.IncompatibleObjC = IncompatibleObjC;
1821     FromType = FromType.getUnqualifiedType();
1822   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1823                                          InOverloadResolution, FromType)) {
1824     // Pointer to member conversions (4.11).
1825     SCS.Second = ICK_Pointer_Member;
1826   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1827     SCS.Second = SecondICK;
1828     FromType = ToType.getUnqualifiedType();
1829   } else if (!S.getLangOpts().CPlusPlus &&
1830              S.Context.typesAreCompatible(ToType, FromType)) {
1831     // Compatible conversions (Clang extension for C function overloading)
1832     SCS.Second = ICK_Compatible_Conversion;
1833     FromType = ToType.getUnqualifiedType();
1834   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1835                                              InOverloadResolution,
1836                                              SCS, CStyle)) {
1837     SCS.Second = ICK_TransparentUnionConversion;
1838     FromType = ToType;
1839   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1840                                  CStyle)) {
1841     // tryAtomicConversion has updated the standard conversion sequence
1842     // appropriately.
1843     return true;
1844   } else if (ToType->isEventT() &&
1845              From->isIntegerConstantExpr(S.getASTContext()) &&
1846              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1847     SCS.Second = ICK_Zero_Event_Conversion;
1848     FromType = ToType;
1849   } else if (ToType->isQueueT() &&
1850              From->isIntegerConstantExpr(S.getASTContext()) &&
1851              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1852     SCS.Second = ICK_Zero_Queue_Conversion;
1853     FromType = ToType;
1854   } else if (ToType->isSamplerT() &&
1855              From->isIntegerConstantExpr(S.getASTContext())) {
1856     SCS.Second = ICK_Compatible_Conversion;
1857     FromType = ToType;
1858   } else {
1859     // No second conversion required.
1860     SCS.Second = ICK_Identity;
1861   }
1862   SCS.setToType(1, FromType);
1863 
1864   // The third conversion can be a function pointer conversion or a
1865   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1866   bool ObjCLifetimeConversion;
1867   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1868     // Function pointer conversions (removing 'noexcept') including removal of
1869     // 'noreturn' (Clang extension).
1870     SCS.Third = ICK_Function_Conversion;
1871   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1872                                          ObjCLifetimeConversion)) {
1873     SCS.Third = ICK_Qualification;
1874     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1875     FromType = ToType;
1876   } else {
1877     // No conversion required
1878     SCS.Third = ICK_Identity;
1879   }
1880 
1881   // C++ [over.best.ics]p6:
1882   //   [...] Any difference in top-level cv-qualification is
1883   //   subsumed by the initialization itself and does not constitute
1884   //   a conversion. [...]
1885   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1886   QualType CanonTo = S.Context.getCanonicalType(ToType);
1887   if (CanonFrom.getLocalUnqualifiedType()
1888                                      == CanonTo.getLocalUnqualifiedType() &&
1889       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1890     FromType = ToType;
1891     CanonFrom = CanonTo;
1892   }
1893 
1894   SCS.setToType(2, FromType);
1895 
1896   if (CanonFrom == CanonTo)
1897     return true;
1898 
1899   // If we have not converted the argument type to the parameter type,
1900   // this is a bad conversion sequence, unless we're resolving an overload in C.
1901   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1902     return false;
1903 
1904   ExprResult ER = ExprResult{From};
1905   Sema::AssignConvertType Conv =
1906       S.CheckSingleAssignmentConstraints(ToType, ER,
1907                                          /*Diagnose=*/false,
1908                                          /*DiagnoseCFAudited=*/false,
1909                                          /*ConvertRHS=*/false);
1910   ImplicitConversionKind SecondConv;
1911   switch (Conv) {
1912   case Sema::Compatible:
1913     SecondConv = ICK_C_Only_Conversion;
1914     break;
1915   // For our purposes, discarding qualifiers is just as bad as using an
1916   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1917   // qualifiers, as well.
1918   case Sema::CompatiblePointerDiscardsQualifiers:
1919   case Sema::IncompatiblePointer:
1920   case Sema::IncompatiblePointerSign:
1921     SecondConv = ICK_Incompatible_Pointer_Conversion;
1922     break;
1923   default:
1924     return false;
1925   }
1926 
1927   // First can only be an lvalue conversion, so we pretend that this was the
1928   // second conversion. First should already be valid from earlier in the
1929   // function.
1930   SCS.Second = SecondConv;
1931   SCS.setToType(1, ToType);
1932 
1933   // Third is Identity, because Second should rank us worse than any other
1934   // conversion. This could also be ICK_Qualification, but it's simpler to just
1935   // lump everything in with the second conversion, and we don't gain anything
1936   // from making this ICK_Qualification.
1937   SCS.Third = ICK_Identity;
1938   SCS.setToType(2, ToType);
1939   return true;
1940 }
1941 
1942 static bool
1943 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1944                                      QualType &ToType,
1945                                      bool InOverloadResolution,
1946                                      StandardConversionSequence &SCS,
1947                                      bool CStyle) {
1948 
1949   const RecordType *UT = ToType->getAsUnionType();
1950   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1951     return false;
1952   // The field to initialize within the transparent union.
1953   RecordDecl *UD = UT->getDecl();
1954   // It's compatible if the expression matches any of the fields.
1955   for (const auto *it : UD->fields()) {
1956     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1957                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
1958       ToType = it->getType();
1959       return true;
1960     }
1961   }
1962   return false;
1963 }
1964 
1965 /// IsIntegralPromotion - Determines whether the conversion from the
1966 /// expression From (whose potentially-adjusted type is FromType) to
1967 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1968 /// sets PromotedType to the promoted type.
1969 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1970   const BuiltinType *To = ToType->getAs<BuiltinType>();
1971   // All integers are built-in.
1972   if (!To) {
1973     return false;
1974   }
1975 
1976   // An rvalue of type char, signed char, unsigned char, short int, or
1977   // unsigned short int can be converted to an rvalue of type int if
1978   // int can represent all the values of the source type; otherwise,
1979   // the source rvalue can be converted to an rvalue of type unsigned
1980   // int (C++ 4.5p1).
1981   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1982       !FromType->isEnumeralType()) {
1983     if (// We can promote any signed, promotable integer type to an int
1984         (FromType->isSignedIntegerType() ||
1985          // We can promote any unsigned integer type whose size is
1986          // less than int to an int.
1987          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1988       return To->getKind() == BuiltinType::Int;
1989     }
1990 
1991     return To->getKind() == BuiltinType::UInt;
1992   }
1993 
1994   // C++11 [conv.prom]p3:
1995   //   A prvalue of an unscoped enumeration type whose underlying type is not
1996   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1997   //   following types that can represent all the values of the enumeration
1998   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1999   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2000   //   long long int. If none of the types in that list can represent all the
2001   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2002   //   type can be converted to an rvalue a prvalue of the extended integer type
2003   //   with lowest integer conversion rank (4.13) greater than the rank of long
2004   //   long in which all the values of the enumeration can be represented. If
2005   //   there are two such extended types, the signed one is chosen.
2006   // C++11 [conv.prom]p4:
2007   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2008   //   can be converted to a prvalue of its underlying type. Moreover, if
2009   //   integral promotion can be applied to its underlying type, a prvalue of an
2010   //   unscoped enumeration type whose underlying type is fixed can also be
2011   //   converted to a prvalue of the promoted underlying type.
2012   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2013     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2014     // provided for a scoped enumeration.
2015     if (FromEnumType->getDecl()->isScoped())
2016       return false;
2017 
2018     // We can perform an integral promotion to the underlying type of the enum,
2019     // even if that's not the promoted type. Note that the check for promoting
2020     // the underlying type is based on the type alone, and does not consider
2021     // the bitfield-ness of the actual source expression.
2022     if (FromEnumType->getDecl()->isFixed()) {
2023       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2024       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2025              IsIntegralPromotion(nullptr, Underlying, ToType);
2026     }
2027 
2028     // We have already pre-calculated the promotion type, so this is trivial.
2029     if (ToType->isIntegerType() &&
2030         isCompleteType(From->getBeginLoc(), FromType))
2031       return Context.hasSameUnqualifiedType(
2032           ToType, FromEnumType->getDecl()->getPromotionType());
2033 
2034     // C++ [conv.prom]p5:
2035     //   If the bit-field has an enumerated type, it is treated as any other
2036     //   value of that type for promotion purposes.
2037     //
2038     // ... so do not fall through into the bit-field checks below in C++.
2039     if (getLangOpts().CPlusPlus)
2040       return false;
2041   }
2042 
2043   // C++0x [conv.prom]p2:
2044   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2045   //   to an rvalue a prvalue of the first of the following types that can
2046   //   represent all the values of its underlying type: int, unsigned int,
2047   //   long int, unsigned long int, long long int, or unsigned long long int.
2048   //   If none of the types in that list can represent all the values of its
2049   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2050   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2051   //   type.
2052   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2053       ToType->isIntegerType()) {
2054     // Determine whether the type we're converting from is signed or
2055     // unsigned.
2056     bool FromIsSigned = FromType->isSignedIntegerType();
2057     uint64_t FromSize = Context.getTypeSize(FromType);
2058 
2059     // The types we'll try to promote to, in the appropriate
2060     // order. Try each of these types.
2061     QualType PromoteTypes[6] = {
2062       Context.IntTy, Context.UnsignedIntTy,
2063       Context.LongTy, Context.UnsignedLongTy ,
2064       Context.LongLongTy, Context.UnsignedLongLongTy
2065     };
2066     for (int Idx = 0; Idx < 6; ++Idx) {
2067       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2068       if (FromSize < ToSize ||
2069           (FromSize == ToSize &&
2070            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2071         // We found the type that we can promote to. If this is the
2072         // type we wanted, we have a promotion. Otherwise, no
2073         // promotion.
2074         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2075       }
2076     }
2077   }
2078 
2079   // An rvalue for an integral bit-field (9.6) can be converted to an
2080   // rvalue of type int if int can represent all the values of the
2081   // bit-field; otherwise, it can be converted to unsigned int if
2082   // unsigned int can represent all the values of the bit-field. If
2083   // the bit-field is larger yet, no integral promotion applies to
2084   // it. If the bit-field has an enumerated type, it is treated as any
2085   // other value of that type for promotion purposes (C++ 4.5p3).
2086   // FIXME: We should delay checking of bit-fields until we actually perform the
2087   // conversion.
2088   //
2089   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2090   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2091   // bit-fields and those whose underlying type is larger than int) for GCC
2092   // compatibility.
2093   if (From) {
2094     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2095       llvm::APSInt BitWidth;
2096       if (FromType->isIntegralType(Context) &&
2097           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2098         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2099         ToSize = Context.getTypeSize(ToType);
2100 
2101         // Are we promoting to an int from a bitfield that fits in an int?
2102         if (BitWidth < ToSize ||
2103             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2104           return To->getKind() == BuiltinType::Int;
2105         }
2106 
2107         // Are we promoting to an unsigned int from an unsigned bitfield
2108         // that fits into an unsigned int?
2109         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2110           return To->getKind() == BuiltinType::UInt;
2111         }
2112 
2113         return false;
2114       }
2115     }
2116   }
2117 
2118   // An rvalue of type bool can be converted to an rvalue of type int,
2119   // with false becoming zero and true becoming one (C++ 4.5p4).
2120   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2121     return true;
2122   }
2123 
2124   return false;
2125 }
2126 
2127 /// IsFloatingPointPromotion - Determines whether the conversion from
2128 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2129 /// returns true and sets PromotedType to the promoted type.
2130 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2131   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2132     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2133       /// An rvalue of type float can be converted to an rvalue of type
2134       /// double. (C++ 4.6p1).
2135       if (FromBuiltin->getKind() == BuiltinType::Float &&
2136           ToBuiltin->getKind() == BuiltinType::Double)
2137         return true;
2138 
2139       // C99 6.3.1.5p1:
2140       //   When a float is promoted to double or long double, or a
2141       //   double is promoted to long double [...].
2142       if (!getLangOpts().CPlusPlus &&
2143           (FromBuiltin->getKind() == BuiltinType::Float ||
2144            FromBuiltin->getKind() == BuiltinType::Double) &&
2145           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2146            ToBuiltin->getKind() == BuiltinType::Float128))
2147         return true;
2148 
2149       // Half can be promoted to float.
2150       if (!getLangOpts().NativeHalfType &&
2151            FromBuiltin->getKind() == BuiltinType::Half &&
2152           ToBuiltin->getKind() == BuiltinType::Float)
2153         return true;
2154     }
2155 
2156   return false;
2157 }
2158 
2159 /// Determine if a conversion is a complex promotion.
2160 ///
2161 /// A complex promotion is defined as a complex -> complex conversion
2162 /// where the conversion between the underlying real types is a
2163 /// floating-point or integral promotion.
2164 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2165   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2166   if (!FromComplex)
2167     return false;
2168 
2169   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2170   if (!ToComplex)
2171     return false;
2172 
2173   return IsFloatingPointPromotion(FromComplex->getElementType(),
2174                                   ToComplex->getElementType()) ||
2175     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2176                         ToComplex->getElementType());
2177 }
2178 
2179 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2180 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2181 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2182 /// if non-empty, will be a pointer to ToType that may or may not have
2183 /// the right set of qualifiers on its pointee.
2184 ///
2185 static QualType
2186 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2187                                    QualType ToPointee, QualType ToType,
2188                                    ASTContext &Context,
2189                                    bool StripObjCLifetime = false) {
2190   assert((FromPtr->getTypeClass() == Type::Pointer ||
2191           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2192          "Invalid similarly-qualified pointer type");
2193 
2194   /// Conversions to 'id' subsume cv-qualifier conversions.
2195   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2196     return ToType.getUnqualifiedType();
2197 
2198   QualType CanonFromPointee
2199     = Context.getCanonicalType(FromPtr->getPointeeType());
2200   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2201   Qualifiers Quals = CanonFromPointee.getQualifiers();
2202 
2203   if (StripObjCLifetime)
2204     Quals.removeObjCLifetime();
2205 
2206   // Exact qualifier match -> return the pointer type we're converting to.
2207   if (CanonToPointee.getLocalQualifiers() == Quals) {
2208     // ToType is exactly what we need. Return it.
2209     if (!ToType.isNull())
2210       return ToType.getUnqualifiedType();
2211 
2212     // Build a pointer to ToPointee. It has the right qualifiers
2213     // already.
2214     if (isa<ObjCObjectPointerType>(ToType))
2215       return Context.getObjCObjectPointerType(ToPointee);
2216     return Context.getPointerType(ToPointee);
2217   }
2218 
2219   // Just build a canonical type that has the right qualifiers.
2220   QualType QualifiedCanonToPointee
2221     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2222 
2223   if (isa<ObjCObjectPointerType>(ToType))
2224     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2225   return Context.getPointerType(QualifiedCanonToPointee);
2226 }
2227 
2228 static bool isNullPointerConstantForConversion(Expr *Expr,
2229                                                bool InOverloadResolution,
2230                                                ASTContext &Context) {
2231   // Handle value-dependent integral null pointer constants correctly.
2232   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2233   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2234       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2235     return !InOverloadResolution;
2236 
2237   return Expr->isNullPointerConstant(Context,
2238                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2239                                         : Expr::NPC_ValueDependentIsNull);
2240 }
2241 
2242 /// IsPointerConversion - Determines whether the conversion of the
2243 /// expression From, which has the (possibly adjusted) type FromType,
2244 /// can be converted to the type ToType via a pointer conversion (C++
2245 /// 4.10). If so, returns true and places the converted type (that
2246 /// might differ from ToType in its cv-qualifiers at some level) into
2247 /// ConvertedType.
2248 ///
2249 /// This routine also supports conversions to and from block pointers
2250 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2251 /// pointers to interfaces. FIXME: Once we've determined the
2252 /// appropriate overloading rules for Objective-C, we may want to
2253 /// split the Objective-C checks into a different routine; however,
2254 /// GCC seems to consider all of these conversions to be pointer
2255 /// conversions, so for now they live here. IncompatibleObjC will be
2256 /// set if the conversion is an allowed Objective-C conversion that
2257 /// should result in a warning.
2258 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2259                                bool InOverloadResolution,
2260                                QualType& ConvertedType,
2261                                bool &IncompatibleObjC) {
2262   IncompatibleObjC = false;
2263   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2264                               IncompatibleObjC))
2265     return true;
2266 
2267   // Conversion from a null pointer constant to any Objective-C pointer type.
2268   if (ToType->isObjCObjectPointerType() &&
2269       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2270     ConvertedType = ToType;
2271     return true;
2272   }
2273 
2274   // Blocks: Block pointers can be converted to void*.
2275   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2276       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2277     ConvertedType = ToType;
2278     return true;
2279   }
2280   // Blocks: A null pointer constant can be converted to a block
2281   // pointer type.
2282   if (ToType->isBlockPointerType() &&
2283       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2284     ConvertedType = ToType;
2285     return true;
2286   }
2287 
2288   // If the left-hand-side is nullptr_t, the right side can be a null
2289   // pointer constant.
2290   if (ToType->isNullPtrType() &&
2291       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2292     ConvertedType = ToType;
2293     return true;
2294   }
2295 
2296   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2297   if (!ToTypePtr)
2298     return false;
2299 
2300   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2301   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2302     ConvertedType = ToType;
2303     return true;
2304   }
2305 
2306   // Beyond this point, both types need to be pointers
2307   // , including objective-c pointers.
2308   QualType ToPointeeType = ToTypePtr->getPointeeType();
2309   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2310       !getLangOpts().ObjCAutoRefCount) {
2311     ConvertedType = BuildSimilarlyQualifiedPointerType(
2312                                       FromType->getAs<ObjCObjectPointerType>(),
2313                                                        ToPointeeType,
2314                                                        ToType, Context);
2315     return true;
2316   }
2317   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2318   if (!FromTypePtr)
2319     return false;
2320 
2321   QualType FromPointeeType = FromTypePtr->getPointeeType();
2322 
2323   // If the unqualified pointee types are the same, this can't be a
2324   // pointer conversion, so don't do all of the work below.
2325   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2326     return false;
2327 
2328   // An rvalue of type "pointer to cv T," where T is an object type,
2329   // can be converted to an rvalue of type "pointer to cv void" (C++
2330   // 4.10p2).
2331   if (FromPointeeType->isIncompleteOrObjectType() &&
2332       ToPointeeType->isVoidType()) {
2333     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2334                                                        ToPointeeType,
2335                                                        ToType, Context,
2336                                                    /*StripObjCLifetime=*/true);
2337     return true;
2338   }
2339 
2340   // MSVC allows implicit function to void* type conversion.
2341   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2342       ToPointeeType->isVoidType()) {
2343     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2344                                                        ToPointeeType,
2345                                                        ToType, Context);
2346     return true;
2347   }
2348 
2349   // When we're overloading in C, we allow a special kind of pointer
2350   // conversion for compatible-but-not-identical pointee types.
2351   if (!getLangOpts().CPlusPlus &&
2352       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2353     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354                                                        ToPointeeType,
2355                                                        ToType, Context);
2356     return true;
2357   }
2358 
2359   // C++ [conv.ptr]p3:
2360   //
2361   //   An rvalue of type "pointer to cv D," where D is a class type,
2362   //   can be converted to an rvalue of type "pointer to cv B," where
2363   //   B is a base class (clause 10) of D. If B is an inaccessible
2364   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2365   //   necessitates this conversion is ill-formed. The result of the
2366   //   conversion is a pointer to the base class sub-object of the
2367   //   derived class object. The null pointer value is converted to
2368   //   the null pointer value of the destination type.
2369   //
2370   // Note that we do not check for ambiguity or inaccessibility
2371   // here. That is handled by CheckPointerConversion.
2372   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2373       ToPointeeType->isRecordType() &&
2374       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2375       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2376     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2377                                                        ToPointeeType,
2378                                                        ToType, Context);
2379     return true;
2380   }
2381 
2382   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2383       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2384     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2385                                                        ToPointeeType,
2386                                                        ToType, Context);
2387     return true;
2388   }
2389 
2390   return false;
2391 }
2392 
2393 /// Adopt the given qualifiers for the given type.
2394 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2395   Qualifiers TQs = T.getQualifiers();
2396 
2397   // Check whether qualifiers already match.
2398   if (TQs == Qs)
2399     return T;
2400 
2401   if (Qs.compatiblyIncludes(TQs))
2402     return Context.getQualifiedType(T, Qs);
2403 
2404   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2405 }
2406 
2407 /// isObjCPointerConversion - Determines whether this is an
2408 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2409 /// with the same arguments and return values.
2410 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2411                                    QualType& ConvertedType,
2412                                    bool &IncompatibleObjC) {
2413   if (!getLangOpts().ObjC)
2414     return false;
2415 
2416   // The set of qualifiers on the type we're converting from.
2417   Qualifiers FromQualifiers = FromType.getQualifiers();
2418 
2419   // First, we handle all conversions on ObjC object pointer types.
2420   const ObjCObjectPointerType* ToObjCPtr =
2421     ToType->getAs<ObjCObjectPointerType>();
2422   const ObjCObjectPointerType *FromObjCPtr =
2423     FromType->getAs<ObjCObjectPointerType>();
2424 
2425   if (ToObjCPtr && FromObjCPtr) {
2426     // If the pointee types are the same (ignoring qualifications),
2427     // then this is not a pointer conversion.
2428     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2429                                        FromObjCPtr->getPointeeType()))
2430       return false;
2431 
2432     // Conversion between Objective-C pointers.
2433     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2434       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2435       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2436       if (getLangOpts().CPlusPlus && LHS && RHS &&
2437           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2438                                                 FromObjCPtr->getPointeeType()))
2439         return false;
2440       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2441                                                    ToObjCPtr->getPointeeType(),
2442                                                          ToType, Context);
2443       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2444       return true;
2445     }
2446 
2447     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2448       // Okay: this is some kind of implicit downcast of Objective-C
2449       // interfaces, which is permitted. However, we're going to
2450       // complain about it.
2451       IncompatibleObjC = true;
2452       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2453                                                    ToObjCPtr->getPointeeType(),
2454                                                          ToType, Context);
2455       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2456       return true;
2457     }
2458   }
2459   // Beyond this point, both types need to be C pointers or block pointers.
2460   QualType ToPointeeType;
2461   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2462     ToPointeeType = ToCPtr->getPointeeType();
2463   else if (const BlockPointerType *ToBlockPtr =
2464             ToType->getAs<BlockPointerType>()) {
2465     // Objective C++: We're able to convert from a pointer to any object
2466     // to a block pointer type.
2467     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2468       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2469       return true;
2470     }
2471     ToPointeeType = ToBlockPtr->getPointeeType();
2472   }
2473   else if (FromType->getAs<BlockPointerType>() &&
2474            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2475     // Objective C++: We're able to convert from a block pointer type to a
2476     // pointer to any object.
2477     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2478     return true;
2479   }
2480   else
2481     return false;
2482 
2483   QualType FromPointeeType;
2484   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2485     FromPointeeType = FromCPtr->getPointeeType();
2486   else if (const BlockPointerType *FromBlockPtr =
2487            FromType->getAs<BlockPointerType>())
2488     FromPointeeType = FromBlockPtr->getPointeeType();
2489   else
2490     return false;
2491 
2492   // If we have pointers to pointers, recursively check whether this
2493   // is an Objective-C conversion.
2494   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2495       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2496                               IncompatibleObjC)) {
2497     // We always complain about this conversion.
2498     IncompatibleObjC = true;
2499     ConvertedType = Context.getPointerType(ConvertedType);
2500     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2501     return true;
2502   }
2503   // Allow conversion of pointee being objective-c pointer to another one;
2504   // as in I* to id.
2505   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2506       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2507       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2508                               IncompatibleObjC)) {
2509 
2510     ConvertedType = Context.getPointerType(ConvertedType);
2511     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2512     return true;
2513   }
2514 
2515   // If we have pointers to functions or blocks, check whether the only
2516   // differences in the argument and result types are in Objective-C
2517   // pointer conversions. If so, we permit the conversion (but
2518   // complain about it).
2519   const FunctionProtoType *FromFunctionType
2520     = FromPointeeType->getAs<FunctionProtoType>();
2521   const FunctionProtoType *ToFunctionType
2522     = ToPointeeType->getAs<FunctionProtoType>();
2523   if (FromFunctionType && ToFunctionType) {
2524     // If the function types are exactly the same, this isn't an
2525     // Objective-C pointer conversion.
2526     if (Context.getCanonicalType(FromPointeeType)
2527           == Context.getCanonicalType(ToPointeeType))
2528       return false;
2529 
2530     // Perform the quick checks that will tell us whether these
2531     // function types are obviously different.
2532     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2533         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2534         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2535       return false;
2536 
2537     bool HasObjCConversion = false;
2538     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2539         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2540       // Okay, the types match exactly. Nothing to do.
2541     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2542                                        ToFunctionType->getReturnType(),
2543                                        ConvertedType, IncompatibleObjC)) {
2544       // Okay, we have an Objective-C pointer conversion.
2545       HasObjCConversion = true;
2546     } else {
2547       // Function types are too different. Abort.
2548       return false;
2549     }
2550 
2551     // Check argument types.
2552     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2553          ArgIdx != NumArgs; ++ArgIdx) {
2554       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2555       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2556       if (Context.getCanonicalType(FromArgType)
2557             == Context.getCanonicalType(ToArgType)) {
2558         // Okay, the types match exactly. Nothing to do.
2559       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2560                                          ConvertedType, IncompatibleObjC)) {
2561         // Okay, we have an Objective-C pointer conversion.
2562         HasObjCConversion = true;
2563       } else {
2564         // Argument types are too different. Abort.
2565         return false;
2566       }
2567     }
2568 
2569     if (HasObjCConversion) {
2570       // We had an Objective-C conversion. Allow this pointer
2571       // conversion, but complain about it.
2572       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573       IncompatibleObjC = true;
2574       return true;
2575     }
2576   }
2577 
2578   return false;
2579 }
2580 
2581 /// Determine whether this is an Objective-C writeback conversion,
2582 /// used for parameter passing when performing automatic reference counting.
2583 ///
2584 /// \param FromType The type we're converting form.
2585 ///
2586 /// \param ToType The type we're converting to.
2587 ///
2588 /// \param ConvertedType The type that will be produced after applying
2589 /// this conversion.
2590 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2591                                      QualType &ConvertedType) {
2592   if (!getLangOpts().ObjCAutoRefCount ||
2593       Context.hasSameUnqualifiedType(FromType, ToType))
2594     return false;
2595 
2596   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2597   QualType ToPointee;
2598   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2599     ToPointee = ToPointer->getPointeeType();
2600   else
2601     return false;
2602 
2603   Qualifiers ToQuals = ToPointee.getQualifiers();
2604   if (!ToPointee->isObjCLifetimeType() ||
2605       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2606       !ToQuals.withoutObjCLifetime().empty())
2607     return false;
2608 
2609   // Argument must be a pointer to __strong to __weak.
2610   QualType FromPointee;
2611   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2612     FromPointee = FromPointer->getPointeeType();
2613   else
2614     return false;
2615 
2616   Qualifiers FromQuals = FromPointee.getQualifiers();
2617   if (!FromPointee->isObjCLifetimeType() ||
2618       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2619        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2620     return false;
2621 
2622   // Make sure that we have compatible qualifiers.
2623   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2624   if (!ToQuals.compatiblyIncludes(FromQuals))
2625     return false;
2626 
2627   // Remove qualifiers from the pointee type we're converting from; they
2628   // aren't used in the compatibility check belong, and we'll be adding back
2629   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2630   FromPointee = FromPointee.getUnqualifiedType();
2631 
2632   // The unqualified form of the pointee types must be compatible.
2633   ToPointee = ToPointee.getUnqualifiedType();
2634   bool IncompatibleObjC;
2635   if (Context.typesAreCompatible(FromPointee, ToPointee))
2636     FromPointee = ToPointee;
2637   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2638                                     IncompatibleObjC))
2639     return false;
2640 
2641   /// Construct the type we're converting to, which is a pointer to
2642   /// __autoreleasing pointee.
2643   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2644   ConvertedType = Context.getPointerType(FromPointee);
2645   return true;
2646 }
2647 
2648 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2649                                     QualType& ConvertedType) {
2650   QualType ToPointeeType;
2651   if (const BlockPointerType *ToBlockPtr =
2652         ToType->getAs<BlockPointerType>())
2653     ToPointeeType = ToBlockPtr->getPointeeType();
2654   else
2655     return false;
2656 
2657   QualType FromPointeeType;
2658   if (const BlockPointerType *FromBlockPtr =
2659       FromType->getAs<BlockPointerType>())
2660     FromPointeeType = FromBlockPtr->getPointeeType();
2661   else
2662     return false;
2663   // We have pointer to blocks, check whether the only
2664   // differences in the argument and result types are in Objective-C
2665   // pointer conversions. If so, we permit the conversion.
2666 
2667   const FunctionProtoType *FromFunctionType
2668     = FromPointeeType->getAs<FunctionProtoType>();
2669   const FunctionProtoType *ToFunctionType
2670     = ToPointeeType->getAs<FunctionProtoType>();
2671 
2672   if (!FromFunctionType || !ToFunctionType)
2673     return false;
2674 
2675   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2676     return true;
2677 
2678   // Perform the quick checks that will tell us whether these
2679   // function types are obviously different.
2680   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2681       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2682     return false;
2683 
2684   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2685   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2686   if (FromEInfo != ToEInfo)
2687     return false;
2688 
2689   bool IncompatibleObjC = false;
2690   if (Context.hasSameType(FromFunctionType->getReturnType(),
2691                           ToFunctionType->getReturnType())) {
2692     // Okay, the types match exactly. Nothing to do.
2693   } else {
2694     QualType RHS = FromFunctionType->getReturnType();
2695     QualType LHS = ToFunctionType->getReturnType();
2696     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2697         !RHS.hasQualifiers() && LHS.hasQualifiers())
2698        LHS = LHS.getUnqualifiedType();
2699 
2700      if (Context.hasSameType(RHS,LHS)) {
2701        // OK exact match.
2702      } else if (isObjCPointerConversion(RHS, LHS,
2703                                         ConvertedType, IncompatibleObjC)) {
2704      if (IncompatibleObjC)
2705        return false;
2706      // Okay, we have an Objective-C pointer conversion.
2707      }
2708      else
2709        return false;
2710    }
2711 
2712    // Check argument types.
2713    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2714         ArgIdx != NumArgs; ++ArgIdx) {
2715      IncompatibleObjC = false;
2716      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2717      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2718      if (Context.hasSameType(FromArgType, ToArgType)) {
2719        // Okay, the types match exactly. Nothing to do.
2720      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2721                                         ConvertedType, IncompatibleObjC)) {
2722        if (IncompatibleObjC)
2723          return false;
2724        // Okay, we have an Objective-C pointer conversion.
2725      } else
2726        // Argument types are too different. Abort.
2727        return false;
2728    }
2729 
2730    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2731    bool CanUseToFPT, CanUseFromFPT;
2732    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2733                                       CanUseToFPT, CanUseFromFPT,
2734                                       NewParamInfos))
2735      return false;
2736 
2737    ConvertedType = ToType;
2738    return true;
2739 }
2740 
2741 enum {
2742   ft_default,
2743   ft_different_class,
2744   ft_parameter_arity,
2745   ft_parameter_mismatch,
2746   ft_return_type,
2747   ft_qualifer_mismatch,
2748   ft_noexcept
2749 };
2750 
2751 /// Attempts to get the FunctionProtoType from a Type. Handles
2752 /// MemberFunctionPointers properly.
2753 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2754   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2755     return FPT;
2756 
2757   if (auto *MPT = FromType->getAs<MemberPointerType>())
2758     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2759 
2760   return nullptr;
2761 }
2762 
2763 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2764 /// function types.  Catches different number of parameter, mismatch in
2765 /// parameter types, and different return types.
2766 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2767                                       QualType FromType, QualType ToType) {
2768   // If either type is not valid, include no extra info.
2769   if (FromType.isNull() || ToType.isNull()) {
2770     PDiag << ft_default;
2771     return;
2772   }
2773 
2774   // Get the function type from the pointers.
2775   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2776     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2777                             *ToMember = ToType->getAs<MemberPointerType>();
2778     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2779       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2780             << QualType(FromMember->getClass(), 0);
2781       return;
2782     }
2783     FromType = FromMember->getPointeeType();
2784     ToType = ToMember->getPointeeType();
2785   }
2786 
2787   if (FromType->isPointerType())
2788     FromType = FromType->getPointeeType();
2789   if (ToType->isPointerType())
2790     ToType = ToType->getPointeeType();
2791 
2792   // Remove references.
2793   FromType = FromType.getNonReferenceType();
2794   ToType = ToType.getNonReferenceType();
2795 
2796   // Don't print extra info for non-specialized template functions.
2797   if (FromType->isInstantiationDependentType() &&
2798       !FromType->getAs<TemplateSpecializationType>()) {
2799     PDiag << ft_default;
2800     return;
2801   }
2802 
2803   // No extra info for same types.
2804   if (Context.hasSameType(FromType, ToType)) {
2805     PDiag << ft_default;
2806     return;
2807   }
2808 
2809   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2810                           *ToFunction = tryGetFunctionProtoType(ToType);
2811 
2812   // Both types need to be function types.
2813   if (!FromFunction || !ToFunction) {
2814     PDiag << ft_default;
2815     return;
2816   }
2817 
2818   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2819     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2820           << FromFunction->getNumParams();
2821     return;
2822   }
2823 
2824   // Handle different parameter types.
2825   unsigned ArgPos;
2826   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2827     PDiag << ft_parameter_mismatch << ArgPos + 1
2828           << ToFunction->getParamType(ArgPos)
2829           << FromFunction->getParamType(ArgPos);
2830     return;
2831   }
2832 
2833   // Handle different return type.
2834   if (!Context.hasSameType(FromFunction->getReturnType(),
2835                            ToFunction->getReturnType())) {
2836     PDiag << ft_return_type << ToFunction->getReturnType()
2837           << FromFunction->getReturnType();
2838     return;
2839   }
2840 
2841   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2842     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2843           << FromFunction->getMethodQuals();
2844     return;
2845   }
2846 
2847   // Handle exception specification differences on canonical type (in C++17
2848   // onwards).
2849   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2850           ->isNothrow() !=
2851       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2852           ->isNothrow()) {
2853     PDiag << ft_noexcept;
2854     return;
2855   }
2856 
2857   // Unable to find a difference, so add no extra info.
2858   PDiag << ft_default;
2859 }
2860 
2861 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2862 /// for equality of their argument types. Caller has already checked that
2863 /// they have same number of arguments.  If the parameters are different,
2864 /// ArgPos will have the parameter index of the first different parameter.
2865 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2866                                       const FunctionProtoType *NewType,
2867                                       unsigned *ArgPos) {
2868   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2869                                               N = NewType->param_type_begin(),
2870                                               E = OldType->param_type_end();
2871        O && (O != E); ++O, ++N) {
2872     if (!Context.hasSameType(O->getUnqualifiedType(),
2873                              N->getUnqualifiedType())) {
2874       if (ArgPos)
2875         *ArgPos = O - OldType->param_type_begin();
2876       return false;
2877     }
2878   }
2879   return true;
2880 }
2881 
2882 /// CheckPointerConversion - Check the pointer conversion from the
2883 /// expression From to the type ToType. This routine checks for
2884 /// ambiguous or inaccessible derived-to-base pointer
2885 /// conversions for which IsPointerConversion has already returned
2886 /// true. It returns true and produces a diagnostic if there was an
2887 /// error, or returns false otherwise.
2888 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2889                                   CastKind &Kind,
2890                                   CXXCastPath& BasePath,
2891                                   bool IgnoreBaseAccess,
2892                                   bool Diagnose) {
2893   QualType FromType = From->getType();
2894   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2895 
2896   Kind = CK_BitCast;
2897 
2898   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2899       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2900           Expr::NPCK_ZeroExpression) {
2901     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2902       DiagRuntimeBehavior(From->getExprLoc(), From,
2903                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2904                             << ToType << From->getSourceRange());
2905     else if (!isUnevaluatedContext())
2906       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2907         << ToType << From->getSourceRange();
2908   }
2909   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2910     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2911       QualType FromPointeeType = FromPtrType->getPointeeType(),
2912                ToPointeeType   = ToPtrType->getPointeeType();
2913 
2914       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2915           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2916         // We must have a derived-to-base conversion. Check an
2917         // ambiguous or inaccessible conversion.
2918         unsigned InaccessibleID = 0;
2919         unsigned AmbigiousID = 0;
2920         if (Diagnose) {
2921           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2922           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2923         }
2924         if (CheckDerivedToBaseConversion(
2925                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2926                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2927                 &BasePath, IgnoreBaseAccess))
2928           return true;
2929 
2930         // The conversion was successful.
2931         Kind = CK_DerivedToBase;
2932       }
2933 
2934       if (Diagnose && !IsCStyleOrFunctionalCast &&
2935           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2936         assert(getLangOpts().MSVCCompat &&
2937                "this should only be possible with MSVCCompat!");
2938         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2939             << From->getSourceRange();
2940       }
2941     }
2942   } else if (const ObjCObjectPointerType *ToPtrType =
2943                ToType->getAs<ObjCObjectPointerType>()) {
2944     if (const ObjCObjectPointerType *FromPtrType =
2945           FromType->getAs<ObjCObjectPointerType>()) {
2946       // Objective-C++ conversions are always okay.
2947       // FIXME: We should have a different class of conversions for the
2948       // Objective-C++ implicit conversions.
2949       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2950         return false;
2951     } else if (FromType->isBlockPointerType()) {
2952       Kind = CK_BlockPointerToObjCPointerCast;
2953     } else {
2954       Kind = CK_CPointerToObjCPointerCast;
2955     }
2956   } else if (ToType->isBlockPointerType()) {
2957     if (!FromType->isBlockPointerType())
2958       Kind = CK_AnyPointerToBlockPointerCast;
2959   }
2960 
2961   // We shouldn't fall into this case unless it's valid for other
2962   // reasons.
2963   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2964     Kind = CK_NullToPointer;
2965 
2966   return false;
2967 }
2968 
2969 /// IsMemberPointerConversion - Determines whether the conversion of the
2970 /// expression From, which has the (possibly adjusted) type FromType, can be
2971 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2972 /// If so, returns true and places the converted type (that might differ from
2973 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2974 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2975                                      QualType ToType,
2976                                      bool InOverloadResolution,
2977                                      QualType &ConvertedType) {
2978   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2979   if (!ToTypePtr)
2980     return false;
2981 
2982   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2983   if (From->isNullPointerConstant(Context,
2984                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2985                                         : Expr::NPC_ValueDependentIsNull)) {
2986     ConvertedType = ToType;
2987     return true;
2988   }
2989 
2990   // Otherwise, both types have to be member pointers.
2991   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2992   if (!FromTypePtr)
2993     return false;
2994 
2995   // A pointer to member of B can be converted to a pointer to member of D,
2996   // where D is derived from B (C++ 4.11p2).
2997   QualType FromClass(FromTypePtr->getClass(), 0);
2998   QualType ToClass(ToTypePtr->getClass(), 0);
2999 
3000   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3001       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3002     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3003                                                  ToClass.getTypePtr());
3004     return true;
3005   }
3006 
3007   return false;
3008 }
3009 
3010 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3011 /// expression From to the type ToType. This routine checks for ambiguous or
3012 /// virtual or inaccessible base-to-derived member pointer conversions
3013 /// for which IsMemberPointerConversion has already returned true. It returns
3014 /// true and produces a diagnostic if there was an error, or returns false
3015 /// otherwise.
3016 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3017                                         CastKind &Kind,
3018                                         CXXCastPath &BasePath,
3019                                         bool IgnoreBaseAccess) {
3020   QualType FromType = From->getType();
3021   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3022   if (!FromPtrType) {
3023     // This must be a null pointer to member pointer conversion
3024     assert(From->isNullPointerConstant(Context,
3025                                        Expr::NPC_ValueDependentIsNull) &&
3026            "Expr must be null pointer constant!");
3027     Kind = CK_NullToMemberPointer;
3028     return false;
3029   }
3030 
3031   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3032   assert(ToPtrType && "No member pointer cast has a target type "
3033                       "that is not a member pointer.");
3034 
3035   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3036   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3037 
3038   // FIXME: What about dependent types?
3039   assert(FromClass->isRecordType() && "Pointer into non-class.");
3040   assert(ToClass->isRecordType() && "Pointer into non-class.");
3041 
3042   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3043                      /*DetectVirtual=*/true);
3044   bool DerivationOkay =
3045       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3046   assert(DerivationOkay &&
3047          "Should not have been called if derivation isn't OK.");
3048   (void)DerivationOkay;
3049 
3050   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3051                                   getUnqualifiedType())) {
3052     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3053     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3054       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3055     return true;
3056   }
3057 
3058   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3059     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3060       << FromClass << ToClass << QualType(VBase, 0)
3061       << From->getSourceRange();
3062     return true;
3063   }
3064 
3065   if (!IgnoreBaseAccess)
3066     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3067                          Paths.front(),
3068                          diag::err_downcast_from_inaccessible_base);
3069 
3070   // Must be a base to derived member conversion.
3071   BuildBasePathArray(Paths, BasePath);
3072   Kind = CK_BaseToDerivedMemberPointer;
3073   return false;
3074 }
3075 
3076 /// Determine whether the lifetime conversion between the two given
3077 /// qualifiers sets is nontrivial.
3078 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3079                                                Qualifiers ToQuals) {
3080   // Converting anything to const __unsafe_unretained is trivial.
3081   if (ToQuals.hasConst() &&
3082       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3083     return false;
3084 
3085   return true;
3086 }
3087 
3088 /// IsQualificationConversion - Determines whether the conversion from
3089 /// an rvalue of type FromType to ToType is a qualification conversion
3090 /// (C++ 4.4).
3091 ///
3092 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3093 /// when the qualification conversion involves a change in the Objective-C
3094 /// object lifetime.
3095 bool
3096 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3097                                 bool CStyle, bool &ObjCLifetimeConversion) {
3098   FromType = Context.getCanonicalType(FromType);
3099   ToType = Context.getCanonicalType(ToType);
3100   ObjCLifetimeConversion = false;
3101 
3102   // If FromType and ToType are the same type, this is not a
3103   // qualification conversion.
3104   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3105     return false;
3106 
3107   // (C++ 4.4p4):
3108   //   A conversion can add cv-qualifiers at levels other than the first
3109   //   in multi-level pointers, subject to the following rules: [...]
3110   bool PreviousToQualsIncludeConst = true;
3111   bool UnwrappedAnyPointer = false;
3112   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3113     // Within each iteration of the loop, we check the qualifiers to
3114     // determine if this still looks like a qualification
3115     // conversion. Then, if all is well, we unwrap one more level of
3116     // pointers or pointers-to-members and do it all again
3117     // until there are no more pointers or pointers-to-members left to
3118     // unwrap.
3119     UnwrappedAnyPointer = true;
3120 
3121     Qualifiers FromQuals = FromType.getQualifiers();
3122     Qualifiers ToQuals = ToType.getQualifiers();
3123 
3124     // Ignore __unaligned qualifier if this type is void.
3125     if (ToType.getUnqualifiedType()->isVoidType())
3126       FromQuals.removeUnaligned();
3127 
3128     // Objective-C ARC:
3129     //   Check Objective-C lifetime conversions.
3130     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3131         UnwrappedAnyPointer) {
3132       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3133         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3134           ObjCLifetimeConversion = true;
3135         FromQuals.removeObjCLifetime();
3136         ToQuals.removeObjCLifetime();
3137       } else {
3138         // Qualification conversions cannot cast between different
3139         // Objective-C lifetime qualifiers.
3140         return false;
3141       }
3142     }
3143 
3144     // Allow addition/removal of GC attributes but not changing GC attributes.
3145     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3146         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3147       FromQuals.removeObjCGCAttr();
3148       ToQuals.removeObjCGCAttr();
3149     }
3150 
3151     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3152     //      2,j, and similarly for volatile.
3153     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3154       return false;
3155 
3156     //   -- if the cv 1,j and cv 2,j are different, then const is in
3157     //      every cv for 0 < k < j.
3158     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3159         && !PreviousToQualsIncludeConst)
3160       return false;
3161 
3162     // Keep track of whether all prior cv-qualifiers in the "to" type
3163     // include const.
3164     PreviousToQualsIncludeConst
3165       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3166   }
3167 
3168   // Allows address space promotion by language rules implemented in
3169   // Type::Qualifiers::isAddressSpaceSupersetOf.
3170   Qualifiers FromQuals = FromType.getQualifiers();
3171   Qualifiers ToQuals = ToType.getQualifiers();
3172   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3173       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3174     return false;
3175   }
3176 
3177   // We are left with FromType and ToType being the pointee types
3178   // after unwrapping the original FromType and ToType the same number
3179   // of types. If we unwrapped any pointers, and if FromType and
3180   // ToType have the same unqualified type (since we checked
3181   // qualifiers above), then this is a qualification conversion.
3182   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3183 }
3184 
3185 /// - Determine whether this is a conversion from a scalar type to an
3186 /// atomic type.
3187 ///
3188 /// If successful, updates \c SCS's second and third steps in the conversion
3189 /// sequence to finish the conversion.
3190 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3191                                 bool InOverloadResolution,
3192                                 StandardConversionSequence &SCS,
3193                                 bool CStyle) {
3194   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3195   if (!ToAtomic)
3196     return false;
3197 
3198   StandardConversionSequence InnerSCS;
3199   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3200                             InOverloadResolution, InnerSCS,
3201                             CStyle, /*AllowObjCWritebackConversion=*/false))
3202     return false;
3203 
3204   SCS.Second = InnerSCS.Second;
3205   SCS.setToType(1, InnerSCS.getToType(1));
3206   SCS.Third = InnerSCS.Third;
3207   SCS.QualificationIncludesObjCLifetime
3208     = InnerSCS.QualificationIncludesObjCLifetime;
3209   SCS.setToType(2, InnerSCS.getToType(2));
3210   return true;
3211 }
3212 
3213 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3214                                               CXXConstructorDecl *Constructor,
3215                                               QualType Type) {
3216   const FunctionProtoType *CtorType =
3217       Constructor->getType()->getAs<FunctionProtoType>();
3218   if (CtorType->getNumParams() > 0) {
3219     QualType FirstArg = CtorType->getParamType(0);
3220     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3221       return true;
3222   }
3223   return false;
3224 }
3225 
3226 static OverloadingResult
3227 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3228                                        CXXRecordDecl *To,
3229                                        UserDefinedConversionSequence &User,
3230                                        OverloadCandidateSet &CandidateSet,
3231                                        bool AllowExplicit) {
3232   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3233   for (auto *D : S.LookupConstructors(To)) {
3234     auto Info = getConstructorInfo(D);
3235     if (!Info)
3236       continue;
3237 
3238     bool Usable = !Info.Constructor->isInvalidDecl() &&
3239                   S.isInitListConstructor(Info.Constructor) &&
3240                   (AllowExplicit || !Info.Constructor->isExplicit());
3241     if (Usable) {
3242       // If the first argument is (a reference to) the target type,
3243       // suppress conversions.
3244       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3245           S.Context, Info.Constructor, ToType);
3246       if (Info.ConstructorTmpl)
3247         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3248                                        /*ExplicitArgs*/ nullptr, From,
3249                                        CandidateSet, SuppressUserConversions,
3250                                        /*PartialOverloading*/ false,
3251                                        AllowExplicit);
3252       else
3253         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3254                                CandidateSet, SuppressUserConversions,
3255                                /*PartialOverloading*/ false, AllowExplicit);
3256     }
3257   }
3258 
3259   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3260 
3261   OverloadCandidateSet::iterator Best;
3262   switch (auto Result =
3263               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3264   case OR_Deleted:
3265   case OR_Success: {
3266     // Record the standard conversion we used and the conversion function.
3267     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3268     QualType ThisType = Constructor->getThisType();
3269     // Initializer lists don't have conversions as such.
3270     User.Before.setAsIdentityConversion();
3271     User.HadMultipleCandidates = HadMultipleCandidates;
3272     User.ConversionFunction = Constructor;
3273     User.FoundConversionFunction = Best->FoundDecl;
3274     User.After.setAsIdentityConversion();
3275     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3276     User.After.setAllToTypes(ToType);
3277     return Result;
3278   }
3279 
3280   case OR_No_Viable_Function:
3281     return OR_No_Viable_Function;
3282   case OR_Ambiguous:
3283     return OR_Ambiguous;
3284   }
3285 
3286   llvm_unreachable("Invalid OverloadResult!");
3287 }
3288 
3289 /// Determines whether there is a user-defined conversion sequence
3290 /// (C++ [over.ics.user]) that converts expression From to the type
3291 /// ToType. If such a conversion exists, User will contain the
3292 /// user-defined conversion sequence that performs such a conversion
3293 /// and this routine will return true. Otherwise, this routine returns
3294 /// false and User is unspecified.
3295 ///
3296 /// \param AllowExplicit  true if the conversion should consider C++0x
3297 /// "explicit" conversion functions as well as non-explicit conversion
3298 /// functions (C++0x [class.conv.fct]p2).
3299 ///
3300 /// \param AllowObjCConversionOnExplicit true if the conversion should
3301 /// allow an extra Objective-C pointer conversion on uses of explicit
3302 /// constructors. Requires \c AllowExplicit to also be set.
3303 static OverloadingResult
3304 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3305                         UserDefinedConversionSequence &User,
3306                         OverloadCandidateSet &CandidateSet,
3307                         bool AllowExplicit,
3308                         bool AllowObjCConversionOnExplicit) {
3309   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3310   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3311 
3312   // Whether we will only visit constructors.
3313   bool ConstructorsOnly = false;
3314 
3315   // If the type we are conversion to is a class type, enumerate its
3316   // constructors.
3317   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3318     // C++ [over.match.ctor]p1:
3319     //   When objects of class type are direct-initialized (8.5), or
3320     //   copy-initialized from an expression of the same or a
3321     //   derived class type (8.5), overload resolution selects the
3322     //   constructor. [...] For copy-initialization, the candidate
3323     //   functions are all the converting constructors (12.3.1) of
3324     //   that class. The argument list is the expression-list within
3325     //   the parentheses of the initializer.
3326     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3327         (From->getType()->getAs<RecordType>() &&
3328          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3329       ConstructorsOnly = true;
3330 
3331     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3332       // We're not going to find any constructors.
3333     } else if (CXXRecordDecl *ToRecordDecl
3334                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3335 
3336       Expr **Args = &From;
3337       unsigned NumArgs = 1;
3338       bool ListInitializing = false;
3339       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3340         // But first, see if there is an init-list-constructor that will work.
3341         OverloadingResult Result = IsInitializerListConstructorConversion(
3342             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3343         if (Result != OR_No_Viable_Function)
3344           return Result;
3345         // Never mind.
3346         CandidateSet.clear(
3347             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3348 
3349         // If we're list-initializing, we pass the individual elements as
3350         // arguments, not the entire list.
3351         Args = InitList->getInits();
3352         NumArgs = InitList->getNumInits();
3353         ListInitializing = true;
3354       }
3355 
3356       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3357         auto Info = getConstructorInfo(D);
3358         if (!Info)
3359           continue;
3360 
3361         bool Usable = !Info.Constructor->isInvalidDecl();
3362         if (ListInitializing)
3363           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3364         else
3365           Usable = Usable &&
3366                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3367         if (Usable) {
3368           bool SuppressUserConversions = !ConstructorsOnly;
3369           if (SuppressUserConversions && ListInitializing) {
3370             SuppressUserConversions = false;
3371             if (NumArgs == 1) {
3372               // If the first argument is (a reference to) the target type,
3373               // suppress conversions.
3374               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3375                   S.Context, Info.Constructor, ToType);
3376             }
3377           }
3378           if (Info.ConstructorTmpl)
3379             S.AddTemplateOverloadCandidate(
3380                 Info.ConstructorTmpl, Info.FoundDecl,
3381                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3382                 CandidateSet, SuppressUserConversions,
3383                 /*PartialOverloading*/ false, AllowExplicit);
3384           else
3385             // Allow one user-defined conversion when user specifies a
3386             // From->ToType conversion via an static cast (c-style, etc).
3387             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3388                                    llvm::makeArrayRef(Args, NumArgs),
3389                                    CandidateSet, SuppressUserConversions,
3390                                    /*PartialOverloading*/ false, AllowExplicit);
3391         }
3392       }
3393     }
3394   }
3395 
3396   // Enumerate conversion functions, if we're allowed to.
3397   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3398   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3399     // No conversion functions from incomplete types.
3400   } else if (const RecordType *FromRecordType =
3401                  From->getType()->getAs<RecordType>()) {
3402     if (CXXRecordDecl *FromRecordDecl
3403          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3404       // Add all of the conversion functions as candidates.
3405       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3406       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3407         DeclAccessPair FoundDecl = I.getPair();
3408         NamedDecl *D = FoundDecl.getDecl();
3409         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3410         if (isa<UsingShadowDecl>(D))
3411           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3412 
3413         CXXConversionDecl *Conv;
3414         FunctionTemplateDecl *ConvTemplate;
3415         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3416           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3417         else
3418           Conv = cast<CXXConversionDecl>(D);
3419 
3420         if (AllowExplicit || !Conv->isExplicit()) {
3421           if (ConvTemplate)
3422             S.AddTemplateConversionCandidate(
3423                 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3424                 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3425           else
3426             S.AddConversionCandidate(
3427                 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3428                 AllowObjCConversionOnExplicit, AllowExplicit);
3429         }
3430       }
3431     }
3432   }
3433 
3434   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3435 
3436   OverloadCandidateSet::iterator Best;
3437   switch (auto Result =
3438               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3439   case OR_Success:
3440   case OR_Deleted:
3441     // Record the standard conversion we used and the conversion function.
3442     if (CXXConstructorDecl *Constructor
3443           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3444       // C++ [over.ics.user]p1:
3445       //   If the user-defined conversion is specified by a
3446       //   constructor (12.3.1), the initial standard conversion
3447       //   sequence converts the source type to the type required by
3448       //   the argument of the constructor.
3449       //
3450       QualType ThisType = Constructor->getThisType();
3451       if (isa<InitListExpr>(From)) {
3452         // Initializer lists don't have conversions as such.
3453         User.Before.setAsIdentityConversion();
3454       } else {
3455         if (Best->Conversions[0].isEllipsis())
3456           User.EllipsisConversion = true;
3457         else {
3458           User.Before = Best->Conversions[0].Standard;
3459           User.EllipsisConversion = false;
3460         }
3461       }
3462       User.HadMultipleCandidates = HadMultipleCandidates;
3463       User.ConversionFunction = Constructor;
3464       User.FoundConversionFunction = Best->FoundDecl;
3465       User.After.setAsIdentityConversion();
3466       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3467       User.After.setAllToTypes(ToType);
3468       return Result;
3469     }
3470     if (CXXConversionDecl *Conversion
3471                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3472       // C++ [over.ics.user]p1:
3473       //
3474       //   [...] If the user-defined conversion is specified by a
3475       //   conversion function (12.3.2), the initial standard
3476       //   conversion sequence converts the source type to the
3477       //   implicit object parameter of the conversion function.
3478       User.Before = Best->Conversions[0].Standard;
3479       User.HadMultipleCandidates = HadMultipleCandidates;
3480       User.ConversionFunction = Conversion;
3481       User.FoundConversionFunction = Best->FoundDecl;
3482       User.EllipsisConversion = false;
3483 
3484       // C++ [over.ics.user]p2:
3485       //   The second standard conversion sequence converts the
3486       //   result of the user-defined conversion to the target type
3487       //   for the sequence. Since an implicit conversion sequence
3488       //   is an initialization, the special rules for
3489       //   initialization by user-defined conversion apply when
3490       //   selecting the best user-defined conversion for a
3491       //   user-defined conversion sequence (see 13.3.3 and
3492       //   13.3.3.1).
3493       User.After = Best->FinalConversion;
3494       return Result;
3495     }
3496     llvm_unreachable("Not a constructor or conversion function?");
3497 
3498   case OR_No_Viable_Function:
3499     return OR_No_Viable_Function;
3500 
3501   case OR_Ambiguous:
3502     return OR_Ambiguous;
3503   }
3504 
3505   llvm_unreachable("Invalid OverloadResult!");
3506 }
3507 
3508 bool
3509 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3510   ImplicitConversionSequence ICS;
3511   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3512                                     OverloadCandidateSet::CSK_Normal);
3513   OverloadingResult OvResult =
3514     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3515                             CandidateSet, false, false);
3516 
3517   if (!(OvResult == OR_Ambiguous ||
3518         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3519     return false;
3520 
3521   auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
3522   if (OvResult == OR_Ambiguous)
3523     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3524         << From->getType() << ToType << From->getSourceRange();
3525   else { // OR_No_Viable_Function && !CandidateSet.empty()
3526     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3527                              diag::err_typecheck_nonviable_condition_incomplete,
3528                              From->getType(), From->getSourceRange()))
3529       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3530           << false << From->getType() << From->getSourceRange() << ToType;
3531   }
3532 
3533   CandidateSet.NoteCandidates(
3534                               *this, From, Cands);
3535   return true;
3536 }
3537 
3538 /// Compare the user-defined conversion functions or constructors
3539 /// of two user-defined conversion sequences to determine whether any ordering
3540 /// is possible.
3541 static ImplicitConversionSequence::CompareKind
3542 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3543                            FunctionDecl *Function2) {
3544   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3545     return ImplicitConversionSequence::Indistinguishable;
3546 
3547   // Objective-C++:
3548   //   If both conversion functions are implicitly-declared conversions from
3549   //   a lambda closure type to a function pointer and a block pointer,
3550   //   respectively, always prefer the conversion to a function pointer,
3551   //   because the function pointer is more lightweight and is more likely
3552   //   to keep code working.
3553   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3554   if (!Conv1)
3555     return ImplicitConversionSequence::Indistinguishable;
3556 
3557   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3558   if (!Conv2)
3559     return ImplicitConversionSequence::Indistinguishable;
3560 
3561   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3562     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3563     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3564     if (Block1 != Block2)
3565       return Block1 ? ImplicitConversionSequence::Worse
3566                     : ImplicitConversionSequence::Better;
3567   }
3568 
3569   return ImplicitConversionSequence::Indistinguishable;
3570 }
3571 
3572 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3573     const ImplicitConversionSequence &ICS) {
3574   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3575          (ICS.isUserDefined() &&
3576           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3577 }
3578 
3579 /// CompareImplicitConversionSequences - Compare two implicit
3580 /// conversion sequences to determine whether one is better than the
3581 /// other or if they are indistinguishable (C++ 13.3.3.2).
3582 static ImplicitConversionSequence::CompareKind
3583 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3584                                    const ImplicitConversionSequence& ICS1,
3585                                    const ImplicitConversionSequence& ICS2)
3586 {
3587   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3588   // conversion sequences (as defined in 13.3.3.1)
3589   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3590   //      conversion sequence than a user-defined conversion sequence or
3591   //      an ellipsis conversion sequence, and
3592   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3593   //      conversion sequence than an ellipsis conversion sequence
3594   //      (13.3.3.1.3).
3595   //
3596   // C++0x [over.best.ics]p10:
3597   //   For the purpose of ranking implicit conversion sequences as
3598   //   described in 13.3.3.2, the ambiguous conversion sequence is
3599   //   treated as a user-defined sequence that is indistinguishable
3600   //   from any other user-defined conversion sequence.
3601 
3602   // String literal to 'char *' conversion has been deprecated in C++03. It has
3603   // been removed from C++11. We still accept this conversion, if it happens at
3604   // the best viable function. Otherwise, this conversion is considered worse
3605   // than ellipsis conversion. Consider this as an extension; this is not in the
3606   // standard. For example:
3607   //
3608   // int &f(...);    // #1
3609   // void f(char*);  // #2
3610   // void g() { int &r = f("foo"); }
3611   //
3612   // In C++03, we pick #2 as the best viable function.
3613   // In C++11, we pick #1 as the best viable function, because ellipsis
3614   // conversion is better than string-literal to char* conversion (since there
3615   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3616   // convert arguments, #2 would be the best viable function in C++11.
3617   // If the best viable function has this conversion, a warning will be issued
3618   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3619 
3620   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3621       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3622       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3623     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3624                ? ImplicitConversionSequence::Worse
3625                : ImplicitConversionSequence::Better;
3626 
3627   if (ICS1.getKindRank() < ICS2.getKindRank())
3628     return ImplicitConversionSequence::Better;
3629   if (ICS2.getKindRank() < ICS1.getKindRank())
3630     return ImplicitConversionSequence::Worse;
3631 
3632   // The following checks require both conversion sequences to be of
3633   // the same kind.
3634   if (ICS1.getKind() != ICS2.getKind())
3635     return ImplicitConversionSequence::Indistinguishable;
3636 
3637   ImplicitConversionSequence::CompareKind Result =
3638       ImplicitConversionSequence::Indistinguishable;
3639 
3640   // Two implicit conversion sequences of the same form are
3641   // indistinguishable conversion sequences unless one of the
3642   // following rules apply: (C++ 13.3.3.2p3):
3643 
3644   // List-initialization sequence L1 is a better conversion sequence than
3645   // list-initialization sequence L2 if:
3646   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3647   //   if not that,
3648   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3649   //   and N1 is smaller than N2.,
3650   // even if one of the other rules in this paragraph would otherwise apply.
3651   if (!ICS1.isBad()) {
3652     if (ICS1.isStdInitializerListElement() &&
3653         !ICS2.isStdInitializerListElement())
3654       return ImplicitConversionSequence::Better;
3655     if (!ICS1.isStdInitializerListElement() &&
3656         ICS2.isStdInitializerListElement())
3657       return ImplicitConversionSequence::Worse;
3658   }
3659 
3660   if (ICS1.isStandard())
3661     // Standard conversion sequence S1 is a better conversion sequence than
3662     // standard conversion sequence S2 if [...]
3663     Result = CompareStandardConversionSequences(S, Loc,
3664                                                 ICS1.Standard, ICS2.Standard);
3665   else if (ICS1.isUserDefined()) {
3666     // User-defined conversion sequence U1 is a better conversion
3667     // sequence than another user-defined conversion sequence U2 if
3668     // they contain the same user-defined conversion function or
3669     // constructor and if the second standard conversion sequence of
3670     // U1 is better than the second standard conversion sequence of
3671     // U2 (C++ 13.3.3.2p3).
3672     if (ICS1.UserDefined.ConversionFunction ==
3673           ICS2.UserDefined.ConversionFunction)
3674       Result = CompareStandardConversionSequences(S, Loc,
3675                                                   ICS1.UserDefined.After,
3676                                                   ICS2.UserDefined.After);
3677     else
3678       Result = compareConversionFunctions(S,
3679                                           ICS1.UserDefined.ConversionFunction,
3680                                           ICS2.UserDefined.ConversionFunction);
3681   }
3682 
3683   return Result;
3684 }
3685 
3686 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3687 // determine if one is a proper subset of the other.
3688 static ImplicitConversionSequence::CompareKind
3689 compareStandardConversionSubsets(ASTContext &Context,
3690                                  const StandardConversionSequence& SCS1,
3691                                  const StandardConversionSequence& SCS2) {
3692   ImplicitConversionSequence::CompareKind Result
3693     = ImplicitConversionSequence::Indistinguishable;
3694 
3695   // the identity conversion sequence is considered to be a subsequence of
3696   // any non-identity conversion sequence
3697   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3698     return ImplicitConversionSequence::Better;
3699   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3700     return ImplicitConversionSequence::Worse;
3701 
3702   if (SCS1.Second != SCS2.Second) {
3703     if (SCS1.Second == ICK_Identity)
3704       Result = ImplicitConversionSequence::Better;
3705     else if (SCS2.Second == ICK_Identity)
3706       Result = ImplicitConversionSequence::Worse;
3707     else
3708       return ImplicitConversionSequence::Indistinguishable;
3709   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3710     return ImplicitConversionSequence::Indistinguishable;
3711 
3712   if (SCS1.Third == SCS2.Third) {
3713     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3714                              : ImplicitConversionSequence::Indistinguishable;
3715   }
3716 
3717   if (SCS1.Third == ICK_Identity)
3718     return Result == ImplicitConversionSequence::Worse
3719              ? ImplicitConversionSequence::Indistinguishable
3720              : ImplicitConversionSequence::Better;
3721 
3722   if (SCS2.Third == ICK_Identity)
3723     return Result == ImplicitConversionSequence::Better
3724              ? ImplicitConversionSequence::Indistinguishable
3725              : ImplicitConversionSequence::Worse;
3726 
3727   return ImplicitConversionSequence::Indistinguishable;
3728 }
3729 
3730 /// Determine whether one of the given reference bindings is better
3731 /// than the other based on what kind of bindings they are.
3732 static bool
3733 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3734                              const StandardConversionSequence &SCS2) {
3735   // C++0x [over.ics.rank]p3b4:
3736   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3737   //      implicit object parameter of a non-static member function declared
3738   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3739   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3740   //      lvalue reference to a function lvalue and S2 binds an rvalue
3741   //      reference*.
3742   //
3743   // FIXME: Rvalue references. We're going rogue with the above edits,
3744   // because the semantics in the current C++0x working paper (N3225 at the
3745   // time of this writing) break the standard definition of std::forward
3746   // and std::reference_wrapper when dealing with references to functions.
3747   // Proposed wording changes submitted to CWG for consideration.
3748   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3749       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3750     return false;
3751 
3752   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3753           SCS2.IsLvalueReference) ||
3754          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3755           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3756 }
3757 
3758 /// CompareStandardConversionSequences - Compare two standard
3759 /// conversion sequences to determine whether one is better than the
3760 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3761 static ImplicitConversionSequence::CompareKind
3762 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3763                                    const StandardConversionSequence& SCS1,
3764                                    const StandardConversionSequence& SCS2)
3765 {
3766   // Standard conversion sequence S1 is a better conversion sequence
3767   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3768 
3769   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3770   //     sequences in the canonical form defined by 13.3.3.1.1,
3771   //     excluding any Lvalue Transformation; the identity conversion
3772   //     sequence is considered to be a subsequence of any
3773   //     non-identity conversion sequence) or, if not that,
3774   if (ImplicitConversionSequence::CompareKind CK
3775         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3776     return CK;
3777 
3778   //  -- the rank of S1 is better than the rank of S2 (by the rules
3779   //     defined below), or, if not that,
3780   ImplicitConversionRank Rank1 = SCS1.getRank();
3781   ImplicitConversionRank Rank2 = SCS2.getRank();
3782   if (Rank1 < Rank2)
3783     return ImplicitConversionSequence::Better;
3784   else if (Rank2 < Rank1)
3785     return ImplicitConversionSequence::Worse;
3786 
3787   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3788   // are indistinguishable unless one of the following rules
3789   // applies:
3790 
3791   //   A conversion that is not a conversion of a pointer, or
3792   //   pointer to member, to bool is better than another conversion
3793   //   that is such a conversion.
3794   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3795     return SCS2.isPointerConversionToBool()
3796              ? ImplicitConversionSequence::Better
3797              : ImplicitConversionSequence::Worse;
3798 
3799   // C++ [over.ics.rank]p4b2:
3800   //
3801   //   If class B is derived directly or indirectly from class A,
3802   //   conversion of B* to A* is better than conversion of B* to
3803   //   void*, and conversion of A* to void* is better than conversion
3804   //   of B* to void*.
3805   bool SCS1ConvertsToVoid
3806     = SCS1.isPointerConversionToVoidPointer(S.Context);
3807   bool SCS2ConvertsToVoid
3808     = SCS2.isPointerConversionToVoidPointer(S.Context);
3809   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3810     // Exactly one of the conversion sequences is a conversion to
3811     // a void pointer; it's the worse conversion.
3812     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3813                               : ImplicitConversionSequence::Worse;
3814   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3815     // Neither conversion sequence converts to a void pointer; compare
3816     // their derived-to-base conversions.
3817     if (ImplicitConversionSequence::CompareKind DerivedCK
3818           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3819       return DerivedCK;
3820   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3821              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3822     // Both conversion sequences are conversions to void
3823     // pointers. Compare the source types to determine if there's an
3824     // inheritance relationship in their sources.
3825     QualType FromType1 = SCS1.getFromType();
3826     QualType FromType2 = SCS2.getFromType();
3827 
3828     // Adjust the types we're converting from via the array-to-pointer
3829     // conversion, if we need to.
3830     if (SCS1.First == ICK_Array_To_Pointer)
3831       FromType1 = S.Context.getArrayDecayedType(FromType1);
3832     if (SCS2.First == ICK_Array_To_Pointer)
3833       FromType2 = S.Context.getArrayDecayedType(FromType2);
3834 
3835     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3836     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3837 
3838     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3839       return ImplicitConversionSequence::Better;
3840     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3841       return ImplicitConversionSequence::Worse;
3842 
3843     // Objective-C++: If one interface is more specific than the
3844     // other, it is the better one.
3845     const ObjCObjectPointerType* FromObjCPtr1
3846       = FromType1->getAs<ObjCObjectPointerType>();
3847     const ObjCObjectPointerType* FromObjCPtr2
3848       = FromType2->getAs<ObjCObjectPointerType>();
3849     if (FromObjCPtr1 && FromObjCPtr2) {
3850       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3851                                                           FromObjCPtr2);
3852       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3853                                                            FromObjCPtr1);
3854       if (AssignLeft != AssignRight) {
3855         return AssignLeft? ImplicitConversionSequence::Better
3856                          : ImplicitConversionSequence::Worse;
3857       }
3858     }
3859   }
3860 
3861   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3862   // bullet 3).
3863   if (ImplicitConversionSequence::CompareKind QualCK
3864         = CompareQualificationConversions(S, SCS1, SCS2))
3865     return QualCK;
3866 
3867   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3868     // Check for a better reference binding based on the kind of bindings.
3869     if (isBetterReferenceBindingKind(SCS1, SCS2))
3870       return ImplicitConversionSequence::Better;
3871     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3872       return ImplicitConversionSequence::Worse;
3873 
3874     // C++ [over.ics.rank]p3b4:
3875     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3876     //      which the references refer are the same type except for
3877     //      top-level cv-qualifiers, and the type to which the reference
3878     //      initialized by S2 refers is more cv-qualified than the type
3879     //      to which the reference initialized by S1 refers.
3880     QualType T1 = SCS1.getToType(2);
3881     QualType T2 = SCS2.getToType(2);
3882     T1 = S.Context.getCanonicalType(T1);
3883     T2 = S.Context.getCanonicalType(T2);
3884     Qualifiers T1Quals, T2Quals;
3885     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3886     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3887     if (UnqualT1 == UnqualT2) {
3888       // Objective-C++ ARC: If the references refer to objects with different
3889       // lifetimes, prefer bindings that don't change lifetime.
3890       if (SCS1.ObjCLifetimeConversionBinding !=
3891                                           SCS2.ObjCLifetimeConversionBinding) {
3892         return SCS1.ObjCLifetimeConversionBinding
3893                                            ? ImplicitConversionSequence::Worse
3894                                            : ImplicitConversionSequence::Better;
3895       }
3896 
3897       // If the type is an array type, promote the element qualifiers to the
3898       // type for comparison.
3899       if (isa<ArrayType>(T1) && T1Quals)
3900         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3901       if (isa<ArrayType>(T2) && T2Quals)
3902         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3903       if (T2.isMoreQualifiedThan(T1))
3904         return ImplicitConversionSequence::Better;
3905       else if (T1.isMoreQualifiedThan(T2))
3906         return ImplicitConversionSequence::Worse;
3907     }
3908   }
3909 
3910   // In Microsoft mode, prefer an integral conversion to a
3911   // floating-to-integral conversion if the integral conversion
3912   // is between types of the same size.
3913   // For example:
3914   // void f(float);
3915   // void f(int);
3916   // int main {
3917   //    long a;
3918   //    f(a);
3919   // }
3920   // Here, MSVC will call f(int) instead of generating a compile error
3921   // as clang will do in standard mode.
3922   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3923       SCS2.Second == ICK_Floating_Integral &&
3924       S.Context.getTypeSize(SCS1.getFromType()) ==
3925           S.Context.getTypeSize(SCS1.getToType(2)))
3926     return ImplicitConversionSequence::Better;
3927 
3928   // Prefer a compatible vector conversion over a lax vector conversion
3929   // For example:
3930   //
3931   // typedef float __v4sf __attribute__((__vector_size__(16)));
3932   // void f(vector float);
3933   // void f(vector signed int);
3934   // int main() {
3935   //   __v4sf a;
3936   //   f(a);
3937   // }
3938   // Here, we'd like to choose f(vector float) and not
3939   // report an ambiguous call error
3940   if (SCS1.Second == ICK_Vector_Conversion &&
3941       SCS2.Second == ICK_Vector_Conversion) {
3942     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3943         SCS1.getFromType(), SCS1.getToType(2));
3944     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3945         SCS2.getFromType(), SCS2.getToType(2));
3946 
3947     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3948       return SCS1IsCompatibleVectorConversion
3949                  ? ImplicitConversionSequence::Better
3950                  : ImplicitConversionSequence::Worse;
3951   }
3952 
3953   return ImplicitConversionSequence::Indistinguishable;
3954 }
3955 
3956 /// CompareQualificationConversions - Compares two standard conversion
3957 /// sequences to determine whether they can be ranked based on their
3958 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3959 static ImplicitConversionSequence::CompareKind
3960 CompareQualificationConversions(Sema &S,
3961                                 const StandardConversionSequence& SCS1,
3962                                 const StandardConversionSequence& SCS2) {
3963   // C++ 13.3.3.2p3:
3964   //  -- S1 and S2 differ only in their qualification conversion and
3965   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3966   //     cv-qualification signature of type T1 is a proper subset of
3967   //     the cv-qualification signature of type T2, and S1 is not the
3968   //     deprecated string literal array-to-pointer conversion (4.2).
3969   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3970       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3971     return ImplicitConversionSequence::Indistinguishable;
3972 
3973   // FIXME: the example in the standard doesn't use a qualification
3974   // conversion (!)
3975   QualType T1 = SCS1.getToType(2);
3976   QualType T2 = SCS2.getToType(2);
3977   T1 = S.Context.getCanonicalType(T1);
3978   T2 = S.Context.getCanonicalType(T2);
3979   Qualifiers T1Quals, T2Quals;
3980   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3981   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3982 
3983   // If the types are the same, we won't learn anything by unwrapped
3984   // them.
3985   if (UnqualT1 == UnqualT2)
3986     return ImplicitConversionSequence::Indistinguishable;
3987 
3988   // If the type is an array type, promote the element qualifiers to the type
3989   // for comparison.
3990   if (isa<ArrayType>(T1) && T1Quals)
3991     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3992   if (isa<ArrayType>(T2) && T2Quals)
3993     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3994 
3995   ImplicitConversionSequence::CompareKind Result
3996     = ImplicitConversionSequence::Indistinguishable;
3997 
3998   // Objective-C++ ARC:
3999   //   Prefer qualification conversions not involving a change in lifetime
4000   //   to qualification conversions that do not change lifetime.
4001   if (SCS1.QualificationIncludesObjCLifetime !=
4002                                       SCS2.QualificationIncludesObjCLifetime) {
4003     Result = SCS1.QualificationIncludesObjCLifetime
4004                ? ImplicitConversionSequence::Worse
4005                : ImplicitConversionSequence::Better;
4006   }
4007 
4008   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4009     // Within each iteration of the loop, we check the qualifiers to
4010     // determine if this still looks like a qualification
4011     // conversion. Then, if all is well, we unwrap one more level of
4012     // pointers or pointers-to-members and do it all again
4013     // until there are no more pointers or pointers-to-members left
4014     // to unwrap. This essentially mimics what
4015     // IsQualificationConversion does, but here we're checking for a
4016     // strict subset of qualifiers.
4017     if (T1.getQualifiers().withoutObjCLifetime() ==
4018         T2.getQualifiers().withoutObjCLifetime())
4019       // The qualifiers are the same, so this doesn't tell us anything
4020       // about how the sequences rank.
4021       // ObjC ownership quals are omitted above as they interfere with
4022       // the ARC overload rule.
4023       ;
4024     else if (T2.isMoreQualifiedThan(T1)) {
4025       // T1 has fewer qualifiers, so it could be the better sequence.
4026       if (Result == ImplicitConversionSequence::Worse)
4027         // Neither has qualifiers that are a subset of the other's
4028         // qualifiers.
4029         return ImplicitConversionSequence::Indistinguishable;
4030 
4031       Result = ImplicitConversionSequence::Better;
4032     } else if (T1.isMoreQualifiedThan(T2)) {
4033       // T2 has fewer qualifiers, so it could be the better sequence.
4034       if (Result == ImplicitConversionSequence::Better)
4035         // Neither has qualifiers that are a subset of the other's
4036         // qualifiers.
4037         return ImplicitConversionSequence::Indistinguishable;
4038 
4039       Result = ImplicitConversionSequence::Worse;
4040     } else {
4041       // Qualifiers are disjoint.
4042       return ImplicitConversionSequence::Indistinguishable;
4043     }
4044 
4045     // If the types after this point are equivalent, we're done.
4046     if (S.Context.hasSameUnqualifiedType(T1, T2))
4047       break;
4048   }
4049 
4050   // Check that the winning standard conversion sequence isn't using
4051   // the deprecated string literal array to pointer conversion.
4052   switch (Result) {
4053   case ImplicitConversionSequence::Better:
4054     if (SCS1.DeprecatedStringLiteralToCharPtr)
4055       Result = ImplicitConversionSequence::Indistinguishable;
4056     break;
4057 
4058   case ImplicitConversionSequence::Indistinguishable:
4059     break;
4060 
4061   case ImplicitConversionSequence::Worse:
4062     if (SCS2.DeprecatedStringLiteralToCharPtr)
4063       Result = ImplicitConversionSequence::Indistinguishable;
4064     break;
4065   }
4066 
4067   return Result;
4068 }
4069 
4070 /// CompareDerivedToBaseConversions - Compares two standard conversion
4071 /// sequences to determine whether they can be ranked based on their
4072 /// various kinds of derived-to-base conversions (C++
4073 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4074 /// conversions between Objective-C interface types.
4075 static ImplicitConversionSequence::CompareKind
4076 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4077                                 const StandardConversionSequence& SCS1,
4078                                 const StandardConversionSequence& SCS2) {
4079   QualType FromType1 = SCS1.getFromType();
4080   QualType ToType1 = SCS1.getToType(1);
4081   QualType FromType2 = SCS2.getFromType();
4082   QualType ToType2 = SCS2.getToType(1);
4083 
4084   // Adjust the types we're converting from via the array-to-pointer
4085   // conversion, if we need to.
4086   if (SCS1.First == ICK_Array_To_Pointer)
4087     FromType1 = S.Context.getArrayDecayedType(FromType1);
4088   if (SCS2.First == ICK_Array_To_Pointer)
4089     FromType2 = S.Context.getArrayDecayedType(FromType2);
4090 
4091   // Canonicalize all of the types.
4092   FromType1 = S.Context.getCanonicalType(FromType1);
4093   ToType1 = S.Context.getCanonicalType(ToType1);
4094   FromType2 = S.Context.getCanonicalType(FromType2);
4095   ToType2 = S.Context.getCanonicalType(ToType2);
4096 
4097   // C++ [over.ics.rank]p4b3:
4098   //
4099   //   If class B is derived directly or indirectly from class A and
4100   //   class C is derived directly or indirectly from B,
4101   //
4102   // Compare based on pointer conversions.
4103   if (SCS1.Second == ICK_Pointer_Conversion &&
4104       SCS2.Second == ICK_Pointer_Conversion &&
4105       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4106       FromType1->isPointerType() && FromType2->isPointerType() &&
4107       ToType1->isPointerType() && ToType2->isPointerType()) {
4108     QualType FromPointee1
4109       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4110     QualType ToPointee1
4111       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112     QualType FromPointee2
4113       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114     QualType ToPointee2
4115       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116 
4117     //   -- conversion of C* to B* is better than conversion of C* to A*,
4118     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4119       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4120         return ImplicitConversionSequence::Better;
4121       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4122         return ImplicitConversionSequence::Worse;
4123     }
4124 
4125     //   -- conversion of B* to A* is better than conversion of C* to A*,
4126     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4127       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4128         return ImplicitConversionSequence::Better;
4129       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4130         return ImplicitConversionSequence::Worse;
4131     }
4132   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4133              SCS2.Second == ICK_Pointer_Conversion) {
4134     const ObjCObjectPointerType *FromPtr1
4135       = FromType1->getAs<ObjCObjectPointerType>();
4136     const ObjCObjectPointerType *FromPtr2
4137       = FromType2->getAs<ObjCObjectPointerType>();
4138     const ObjCObjectPointerType *ToPtr1
4139       = ToType1->getAs<ObjCObjectPointerType>();
4140     const ObjCObjectPointerType *ToPtr2
4141       = ToType2->getAs<ObjCObjectPointerType>();
4142 
4143     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4144       // Apply the same conversion ranking rules for Objective-C pointer types
4145       // that we do for C++ pointers to class types. However, we employ the
4146       // Objective-C pseudo-subtyping relationship used for assignment of
4147       // Objective-C pointer types.
4148       bool FromAssignLeft
4149         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4150       bool FromAssignRight
4151         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4152       bool ToAssignLeft
4153         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4154       bool ToAssignRight
4155         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4156 
4157       // A conversion to an a non-id object pointer type or qualified 'id'
4158       // type is better than a conversion to 'id'.
4159       if (ToPtr1->isObjCIdType() &&
4160           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4161         return ImplicitConversionSequence::Worse;
4162       if (ToPtr2->isObjCIdType() &&
4163           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4164         return ImplicitConversionSequence::Better;
4165 
4166       // A conversion to a non-id object pointer type is better than a
4167       // conversion to a qualified 'id' type
4168       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4169         return ImplicitConversionSequence::Worse;
4170       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4171         return ImplicitConversionSequence::Better;
4172 
4173       // A conversion to an a non-Class object pointer type or qualified 'Class'
4174       // type is better than a conversion to 'Class'.
4175       if (ToPtr1->isObjCClassType() &&
4176           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4177         return ImplicitConversionSequence::Worse;
4178       if (ToPtr2->isObjCClassType() &&
4179           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4180         return ImplicitConversionSequence::Better;
4181 
4182       // A conversion to a non-Class object pointer type is better than a
4183       // conversion to a qualified 'Class' type.
4184       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4185         return ImplicitConversionSequence::Worse;
4186       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4187         return ImplicitConversionSequence::Better;
4188 
4189       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4190       if (S.Context.hasSameType(FromType1, FromType2) &&
4191           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4192           (ToAssignLeft != ToAssignRight)) {
4193         if (FromPtr1->isSpecialized()) {
4194           // "conversion of B<A> * to B * is better than conversion of B * to
4195           // C *.
4196           bool IsFirstSame =
4197               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4198           bool IsSecondSame =
4199               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4200           if (IsFirstSame) {
4201             if (!IsSecondSame)
4202               return ImplicitConversionSequence::Better;
4203           } else if (IsSecondSame)
4204             return ImplicitConversionSequence::Worse;
4205         }
4206         return ToAssignLeft? ImplicitConversionSequence::Worse
4207                            : ImplicitConversionSequence::Better;
4208       }
4209 
4210       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4211       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4212           (FromAssignLeft != FromAssignRight))
4213         return FromAssignLeft? ImplicitConversionSequence::Better
4214         : ImplicitConversionSequence::Worse;
4215     }
4216   }
4217 
4218   // Ranking of member-pointer types.
4219   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4220       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4221       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4222     const MemberPointerType * FromMemPointer1 =
4223                                         FromType1->getAs<MemberPointerType>();
4224     const MemberPointerType * ToMemPointer1 =
4225                                           ToType1->getAs<MemberPointerType>();
4226     const MemberPointerType * FromMemPointer2 =
4227                                           FromType2->getAs<MemberPointerType>();
4228     const MemberPointerType * ToMemPointer2 =
4229                                           ToType2->getAs<MemberPointerType>();
4230     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4231     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4232     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4233     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4234     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4235     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4236     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4237     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4238     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4239     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4240       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4241         return ImplicitConversionSequence::Worse;
4242       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4243         return ImplicitConversionSequence::Better;
4244     }
4245     // conversion of B::* to C::* is better than conversion of A::* to C::*
4246     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4247       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4248         return ImplicitConversionSequence::Better;
4249       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4250         return ImplicitConversionSequence::Worse;
4251     }
4252   }
4253 
4254   if (SCS1.Second == ICK_Derived_To_Base) {
4255     //   -- conversion of C to B is better than conversion of C to A,
4256     //   -- binding of an expression of type C to a reference of type
4257     //      B& is better than binding an expression of type C to a
4258     //      reference of type A&,
4259     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4260         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4261       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4262         return ImplicitConversionSequence::Better;
4263       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4264         return ImplicitConversionSequence::Worse;
4265     }
4266 
4267     //   -- conversion of B to A is better than conversion of C to A.
4268     //   -- binding of an expression of type B to a reference of type
4269     //      A& is better than binding an expression of type C to a
4270     //      reference of type A&,
4271     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4272         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4273       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4274         return ImplicitConversionSequence::Better;
4275       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4276         return ImplicitConversionSequence::Worse;
4277     }
4278   }
4279 
4280   return ImplicitConversionSequence::Indistinguishable;
4281 }
4282 
4283 /// Determine whether the given type is valid, e.g., it is not an invalid
4284 /// C++ class.
4285 static bool isTypeValid(QualType T) {
4286   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4287     return !Record->isInvalidDecl();
4288 
4289   return true;
4290 }
4291 
4292 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4293 /// determine whether they are reference-related,
4294 /// reference-compatible, reference-compatible with added
4295 /// qualification, or incompatible, for use in C++ initialization by
4296 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4297 /// type, and the first type (T1) is the pointee type of the reference
4298 /// type being initialized.
4299 Sema::ReferenceCompareResult
4300 Sema::CompareReferenceRelationship(SourceLocation Loc,
4301                                    QualType OrigT1, QualType OrigT2,
4302                                    bool &DerivedToBase,
4303                                    bool &ObjCConversion,
4304                                    bool &ObjCLifetimeConversion) {
4305   assert(!OrigT1->isReferenceType() &&
4306     "T1 must be the pointee type of the reference type");
4307   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4308 
4309   QualType T1 = Context.getCanonicalType(OrigT1);
4310   QualType T2 = Context.getCanonicalType(OrigT2);
4311   Qualifiers T1Quals, T2Quals;
4312   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4313   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4314 
4315   // C++ [dcl.init.ref]p4:
4316   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4317   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4318   //   T1 is a base class of T2.
4319   DerivedToBase = false;
4320   ObjCConversion = false;
4321   ObjCLifetimeConversion = false;
4322   QualType ConvertedT2;
4323   if (UnqualT1 == UnqualT2) {
4324     // Nothing to do.
4325   } else if (isCompleteType(Loc, OrigT2) &&
4326              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4327              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4328     DerivedToBase = true;
4329   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4330            UnqualT2->isObjCObjectOrInterfaceType() &&
4331            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4332     ObjCConversion = true;
4333   else if (UnqualT2->isFunctionType() &&
4334            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4335     // C++1z [dcl.init.ref]p4:
4336     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4337     //   function" and T1 is "function"
4338     //
4339     // We extend this to also apply to 'noreturn', so allow any function
4340     // conversion between function types.
4341     return Ref_Compatible;
4342   else
4343     return Ref_Incompatible;
4344 
4345   // At this point, we know that T1 and T2 are reference-related (at
4346   // least).
4347 
4348   // If the type is an array type, promote the element qualifiers to the type
4349   // for comparison.
4350   if (isa<ArrayType>(T1) && T1Quals)
4351     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4352   if (isa<ArrayType>(T2) && T2Quals)
4353     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4354 
4355   // C++ [dcl.init.ref]p4:
4356   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4357   //   reference-related to T2 and cv1 is the same cv-qualification
4358   //   as, or greater cv-qualification than, cv2. For purposes of
4359   //   overload resolution, cases for which cv1 is greater
4360   //   cv-qualification than cv2 are identified as
4361   //   reference-compatible with added qualification (see 13.3.3.2).
4362   //
4363   // Note that we also require equivalence of Objective-C GC and address-space
4364   // qualifiers when performing these computations, so that e.g., an int in
4365   // address space 1 is not reference-compatible with an int in address
4366   // space 2.
4367   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4368       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4369     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4370       ObjCLifetimeConversion = true;
4371 
4372     T1Quals.removeObjCLifetime();
4373     T2Quals.removeObjCLifetime();
4374   }
4375 
4376   // MS compiler ignores __unaligned qualifier for references; do the same.
4377   T1Quals.removeUnaligned();
4378   T2Quals.removeUnaligned();
4379 
4380   if (T1Quals.compatiblyIncludes(T2Quals))
4381     return Ref_Compatible;
4382   else
4383     return Ref_Related;
4384 }
4385 
4386 /// Look for a user-defined conversion to a value reference-compatible
4387 ///        with DeclType. Return true if something definite is found.
4388 static bool
4389 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4390                          QualType DeclType, SourceLocation DeclLoc,
4391                          Expr *Init, QualType T2, bool AllowRvalues,
4392                          bool AllowExplicit) {
4393   assert(T2->isRecordType() && "Can only find conversions of record types.");
4394   CXXRecordDecl *T2RecordDecl
4395     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4396 
4397   OverloadCandidateSet CandidateSet(
4398       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4399   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4400   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4401     NamedDecl *D = *I;
4402     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4403     if (isa<UsingShadowDecl>(D))
4404       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4405 
4406     FunctionTemplateDecl *ConvTemplate
4407       = dyn_cast<FunctionTemplateDecl>(D);
4408     CXXConversionDecl *Conv;
4409     if (ConvTemplate)
4410       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4411     else
4412       Conv = cast<CXXConversionDecl>(D);
4413 
4414     // If this is an explicit conversion, and we're not allowed to consider
4415     // explicit conversions, skip it.
4416     if (!AllowExplicit && Conv->isExplicit())
4417       continue;
4418 
4419     if (AllowRvalues) {
4420       bool DerivedToBase = false;
4421       bool ObjCConversion = false;
4422       bool ObjCLifetimeConversion = false;
4423 
4424       // If we are initializing an rvalue reference, don't permit conversion
4425       // functions that return lvalues.
4426       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4427         const ReferenceType *RefType
4428           = Conv->getConversionType()->getAs<LValueReferenceType>();
4429         if (RefType && !RefType->getPointeeType()->isFunctionType())
4430           continue;
4431       }
4432 
4433       if (!ConvTemplate &&
4434           S.CompareReferenceRelationship(
4435             DeclLoc,
4436             Conv->getConversionType().getNonReferenceType()
4437               .getUnqualifiedType(),
4438             DeclType.getNonReferenceType().getUnqualifiedType(),
4439             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4440           Sema::Ref_Incompatible)
4441         continue;
4442     } else {
4443       // If the conversion function doesn't return a reference type,
4444       // it can't be considered for this conversion. An rvalue reference
4445       // is only acceptable if its referencee is a function type.
4446 
4447       const ReferenceType *RefType =
4448         Conv->getConversionType()->getAs<ReferenceType>();
4449       if (!RefType ||
4450           (!RefType->isLValueReferenceType() &&
4451            !RefType->getPointeeType()->isFunctionType()))
4452         continue;
4453     }
4454 
4455     if (ConvTemplate)
4456       S.AddTemplateConversionCandidate(
4457           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4458           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4459     else
4460       S.AddConversionCandidate(
4461           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4462           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4463   }
4464 
4465   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4466 
4467   OverloadCandidateSet::iterator Best;
4468   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4469   case OR_Success:
4470     // C++ [over.ics.ref]p1:
4471     //
4472     //   [...] If the parameter binds directly to the result of
4473     //   applying a conversion function to the argument
4474     //   expression, the implicit conversion sequence is a
4475     //   user-defined conversion sequence (13.3.3.1.2), with the
4476     //   second standard conversion sequence either an identity
4477     //   conversion or, if the conversion function returns an
4478     //   entity of a type that is a derived class of the parameter
4479     //   type, a derived-to-base Conversion.
4480     if (!Best->FinalConversion.DirectBinding)
4481       return false;
4482 
4483     ICS.setUserDefined();
4484     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4485     ICS.UserDefined.After = Best->FinalConversion;
4486     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4487     ICS.UserDefined.ConversionFunction = Best->Function;
4488     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4489     ICS.UserDefined.EllipsisConversion = false;
4490     assert(ICS.UserDefined.After.ReferenceBinding &&
4491            ICS.UserDefined.After.DirectBinding &&
4492            "Expected a direct reference binding!");
4493     return true;
4494 
4495   case OR_Ambiguous:
4496     ICS.setAmbiguous();
4497     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4498          Cand != CandidateSet.end(); ++Cand)
4499       if (Cand->Viable)
4500         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4501     return true;
4502 
4503   case OR_No_Viable_Function:
4504   case OR_Deleted:
4505     // There was no suitable conversion, or we found a deleted
4506     // conversion; continue with other checks.
4507     return false;
4508   }
4509 
4510   llvm_unreachable("Invalid OverloadResult!");
4511 }
4512 
4513 /// Compute an implicit conversion sequence for reference
4514 /// initialization.
4515 static ImplicitConversionSequence
4516 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4517                  SourceLocation DeclLoc,
4518                  bool SuppressUserConversions,
4519                  bool AllowExplicit) {
4520   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4521 
4522   // Most paths end in a failed conversion.
4523   ImplicitConversionSequence ICS;
4524   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4525 
4526   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4527   QualType T2 = Init->getType();
4528 
4529   // If the initializer is the address of an overloaded function, try
4530   // to resolve the overloaded function. If all goes well, T2 is the
4531   // type of the resulting function.
4532   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4533     DeclAccessPair Found;
4534     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4535                                                                 false, Found))
4536       T2 = Fn->getType();
4537   }
4538 
4539   // Compute some basic properties of the types and the initializer.
4540   bool isRValRef = DeclType->isRValueReferenceType();
4541   bool DerivedToBase = false;
4542   bool ObjCConversion = false;
4543   bool ObjCLifetimeConversion = false;
4544   Expr::Classification InitCategory = Init->Classify(S.Context);
4545   Sema::ReferenceCompareResult RefRelationship
4546     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4547                                      ObjCConversion, ObjCLifetimeConversion);
4548 
4549 
4550   // C++0x [dcl.init.ref]p5:
4551   //   A reference to type "cv1 T1" is initialized by an expression
4552   //   of type "cv2 T2" as follows:
4553 
4554   //     -- If reference is an lvalue reference and the initializer expression
4555   if (!isRValRef) {
4556     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4557     //        reference-compatible with "cv2 T2," or
4558     //
4559     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4560     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4561       // C++ [over.ics.ref]p1:
4562       //   When a parameter of reference type binds directly (8.5.3)
4563       //   to an argument expression, the implicit conversion sequence
4564       //   is the identity conversion, unless the argument expression
4565       //   has a type that is a derived class of the parameter type,
4566       //   in which case the implicit conversion sequence is a
4567       //   derived-to-base Conversion (13.3.3.1).
4568       ICS.setStandard();
4569       ICS.Standard.First = ICK_Identity;
4570       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4571                          : ObjCConversion? ICK_Compatible_Conversion
4572                          : ICK_Identity;
4573       ICS.Standard.Third = ICK_Identity;
4574       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4575       ICS.Standard.setToType(0, T2);
4576       ICS.Standard.setToType(1, T1);
4577       ICS.Standard.setToType(2, T1);
4578       ICS.Standard.ReferenceBinding = true;
4579       ICS.Standard.DirectBinding = true;
4580       ICS.Standard.IsLvalueReference = !isRValRef;
4581       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4582       ICS.Standard.BindsToRvalue = false;
4583       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4584       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4585       ICS.Standard.CopyConstructor = nullptr;
4586       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4587 
4588       // Nothing more to do: the inaccessibility/ambiguity check for
4589       // derived-to-base conversions is suppressed when we're
4590       // computing the implicit conversion sequence (C++
4591       // [over.best.ics]p2).
4592       return ICS;
4593     }
4594 
4595     //       -- has a class type (i.e., T2 is a class type), where T1 is
4596     //          not reference-related to T2, and can be implicitly
4597     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4598     //          is reference-compatible with "cv3 T3" 92) (this
4599     //          conversion is selected by enumerating the applicable
4600     //          conversion functions (13.3.1.6) and choosing the best
4601     //          one through overload resolution (13.3)),
4602     if (!SuppressUserConversions && T2->isRecordType() &&
4603         S.isCompleteType(DeclLoc, T2) &&
4604         RefRelationship == Sema::Ref_Incompatible) {
4605       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4606                                    Init, T2, /*AllowRvalues=*/false,
4607                                    AllowExplicit))
4608         return ICS;
4609     }
4610   }
4611 
4612   //     -- Otherwise, the reference shall be an lvalue reference to a
4613   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4614   //        shall be an rvalue reference.
4615   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4616     return ICS;
4617 
4618   //       -- If the initializer expression
4619   //
4620   //            -- is an xvalue, class prvalue, array prvalue or function
4621   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4622   if (RefRelationship == Sema::Ref_Compatible &&
4623       (InitCategory.isXValue() ||
4624        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4625        (InitCategory.isLValue() && T2->isFunctionType()))) {
4626     ICS.setStandard();
4627     ICS.Standard.First = ICK_Identity;
4628     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4629                       : ObjCConversion? ICK_Compatible_Conversion
4630                       : ICK_Identity;
4631     ICS.Standard.Third = ICK_Identity;
4632     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4633     ICS.Standard.setToType(0, T2);
4634     ICS.Standard.setToType(1, T1);
4635     ICS.Standard.setToType(2, T1);
4636     ICS.Standard.ReferenceBinding = true;
4637     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4638     // binding unless we're binding to a class prvalue.
4639     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4640     // allow the use of rvalue references in C++98/03 for the benefit of
4641     // standard library implementors; therefore, we need the xvalue check here.
4642     ICS.Standard.DirectBinding =
4643       S.getLangOpts().CPlusPlus11 ||
4644       !(InitCategory.isPRValue() || T2->isRecordType());
4645     ICS.Standard.IsLvalueReference = !isRValRef;
4646     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4647     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4648     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4649     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4650     ICS.Standard.CopyConstructor = nullptr;
4651     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4652     return ICS;
4653   }
4654 
4655   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4656   //               reference-related to T2, and can be implicitly converted to
4657   //               an xvalue, class prvalue, or function lvalue of type
4658   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4659   //               "cv3 T3",
4660   //
4661   //          then the reference is bound to the value of the initializer
4662   //          expression in the first case and to the result of the conversion
4663   //          in the second case (or, in either case, to an appropriate base
4664   //          class subobject).
4665   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4667       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4668                                Init, T2, /*AllowRvalues=*/true,
4669                                AllowExplicit)) {
4670     // In the second case, if the reference is an rvalue reference
4671     // and the second standard conversion sequence of the
4672     // user-defined conversion sequence includes an lvalue-to-rvalue
4673     // conversion, the program is ill-formed.
4674     if (ICS.isUserDefined() && isRValRef &&
4675         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4676       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4677 
4678     return ICS;
4679   }
4680 
4681   // A temporary of function type cannot be created; don't even try.
4682   if (T1->isFunctionType())
4683     return ICS;
4684 
4685   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4686   //          initialized from the initializer expression using the
4687   //          rules for a non-reference copy initialization (8.5). The
4688   //          reference is then bound to the temporary. If T1 is
4689   //          reference-related to T2, cv1 must be the same
4690   //          cv-qualification as, or greater cv-qualification than,
4691   //          cv2; otherwise, the program is ill-formed.
4692   if (RefRelationship == Sema::Ref_Related) {
4693     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4694     // we would be reference-compatible or reference-compatible with
4695     // added qualification. But that wasn't the case, so the reference
4696     // initialization fails.
4697     //
4698     // Note that we only want to check address spaces and cvr-qualifiers here.
4699     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4700     Qualifiers T1Quals = T1.getQualifiers();
4701     Qualifiers T2Quals = T2.getQualifiers();
4702     T1Quals.removeObjCGCAttr();
4703     T1Quals.removeObjCLifetime();
4704     T2Quals.removeObjCGCAttr();
4705     T2Quals.removeObjCLifetime();
4706     // MS compiler ignores __unaligned qualifier for references; do the same.
4707     T1Quals.removeUnaligned();
4708     T2Quals.removeUnaligned();
4709     if (!T1Quals.compatiblyIncludes(T2Quals))
4710       return ICS;
4711   }
4712 
4713   // If at least one of the types is a class type, the types are not
4714   // related, and we aren't allowed any user conversions, the
4715   // reference binding fails. This case is important for breaking
4716   // recursion, since TryImplicitConversion below will attempt to
4717   // create a temporary through the use of a copy constructor.
4718   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4719       (T1->isRecordType() || T2->isRecordType()))
4720     return ICS;
4721 
4722   // If T1 is reference-related to T2 and the reference is an rvalue
4723   // reference, the initializer expression shall not be an lvalue.
4724   if (RefRelationship >= Sema::Ref_Related &&
4725       isRValRef && Init->Classify(S.Context).isLValue())
4726     return ICS;
4727 
4728   // C++ [over.ics.ref]p2:
4729   //   When a parameter of reference type is not bound directly to
4730   //   an argument expression, the conversion sequence is the one
4731   //   required to convert the argument expression to the
4732   //   underlying type of the reference according to
4733   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4734   //   to copy-initializing a temporary of the underlying type with
4735   //   the argument expression. Any difference in top-level
4736   //   cv-qualification is subsumed by the initialization itself
4737   //   and does not constitute a conversion.
4738   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4739                               /*AllowExplicit=*/false,
4740                               /*InOverloadResolution=*/false,
4741                               /*CStyle=*/false,
4742                               /*AllowObjCWritebackConversion=*/false,
4743                               /*AllowObjCConversionOnExplicit=*/false);
4744 
4745   // Of course, that's still a reference binding.
4746   if (ICS.isStandard()) {
4747     ICS.Standard.ReferenceBinding = true;
4748     ICS.Standard.IsLvalueReference = !isRValRef;
4749     ICS.Standard.BindsToFunctionLvalue = false;
4750     ICS.Standard.BindsToRvalue = true;
4751     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4752     ICS.Standard.ObjCLifetimeConversionBinding = false;
4753   } else if (ICS.isUserDefined()) {
4754     const ReferenceType *LValRefType =
4755         ICS.UserDefined.ConversionFunction->getReturnType()
4756             ->getAs<LValueReferenceType>();
4757 
4758     // C++ [over.ics.ref]p3:
4759     //   Except for an implicit object parameter, for which see 13.3.1, a
4760     //   standard conversion sequence cannot be formed if it requires [...]
4761     //   binding an rvalue reference to an lvalue other than a function
4762     //   lvalue.
4763     // Note that the function case is not possible here.
4764     if (DeclType->isRValueReferenceType() && LValRefType) {
4765       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4766       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4767       // reference to an rvalue!
4768       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4769       return ICS;
4770     }
4771 
4772     ICS.UserDefined.After.ReferenceBinding = true;
4773     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4774     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4775     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4776     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4777     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4778   }
4779 
4780   return ICS;
4781 }
4782 
4783 static ImplicitConversionSequence
4784 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4785                       bool SuppressUserConversions,
4786                       bool InOverloadResolution,
4787                       bool AllowObjCWritebackConversion,
4788                       bool AllowExplicit = false);
4789 
4790 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4791 /// initializer list From.
4792 static ImplicitConversionSequence
4793 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4794                   bool SuppressUserConversions,
4795                   bool InOverloadResolution,
4796                   bool AllowObjCWritebackConversion) {
4797   // C++11 [over.ics.list]p1:
4798   //   When an argument is an initializer list, it is not an expression and
4799   //   special rules apply for converting it to a parameter type.
4800 
4801   ImplicitConversionSequence Result;
4802   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4803 
4804   // We need a complete type for what follows. Incomplete types can never be
4805   // initialized from init lists.
4806   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4807     return Result;
4808 
4809   // Per DR1467:
4810   //   If the parameter type is a class X and the initializer list has a single
4811   //   element of type cv U, where U is X or a class derived from X, the
4812   //   implicit conversion sequence is the one required to convert the element
4813   //   to the parameter type.
4814   //
4815   //   Otherwise, if the parameter type is a character array [... ]
4816   //   and the initializer list has a single element that is an
4817   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4818   //   implicit conversion sequence is the identity conversion.
4819   if (From->getNumInits() == 1) {
4820     if (ToType->isRecordType()) {
4821       QualType InitType = From->getInit(0)->getType();
4822       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4823           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4824         return TryCopyInitialization(S, From->getInit(0), ToType,
4825                                      SuppressUserConversions,
4826                                      InOverloadResolution,
4827                                      AllowObjCWritebackConversion);
4828     }
4829     // FIXME: Check the other conditions here: array of character type,
4830     // initializer is a string literal.
4831     if (ToType->isArrayType()) {
4832       InitializedEntity Entity =
4833         InitializedEntity::InitializeParameter(S.Context, ToType,
4834                                                /*Consumed=*/false);
4835       if (S.CanPerformCopyInitialization(Entity, From)) {
4836         Result.setStandard();
4837         Result.Standard.setAsIdentityConversion();
4838         Result.Standard.setFromType(ToType);
4839         Result.Standard.setAllToTypes(ToType);
4840         return Result;
4841       }
4842     }
4843   }
4844 
4845   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4846   // C++11 [over.ics.list]p2:
4847   //   If the parameter type is std::initializer_list<X> or "array of X" and
4848   //   all the elements can be implicitly converted to X, the implicit
4849   //   conversion sequence is the worst conversion necessary to convert an
4850   //   element of the list to X.
4851   //
4852   // C++14 [over.ics.list]p3:
4853   //   Otherwise, if the parameter type is "array of N X", if the initializer
4854   //   list has exactly N elements or if it has fewer than N elements and X is
4855   //   default-constructible, and if all the elements of the initializer list
4856   //   can be implicitly converted to X, the implicit conversion sequence is
4857   //   the worst conversion necessary to convert an element of the list to X.
4858   //
4859   // FIXME: We're missing a lot of these checks.
4860   bool toStdInitializerList = false;
4861   QualType X;
4862   if (ToType->isArrayType())
4863     X = S.Context.getAsArrayType(ToType)->getElementType();
4864   else
4865     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4866   if (!X.isNull()) {
4867     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4868       Expr *Init = From->getInit(i);
4869       ImplicitConversionSequence ICS =
4870           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4871                                 InOverloadResolution,
4872                                 AllowObjCWritebackConversion);
4873       // If a single element isn't convertible, fail.
4874       if (ICS.isBad()) {
4875         Result = ICS;
4876         break;
4877       }
4878       // Otherwise, look for the worst conversion.
4879       if (Result.isBad() || CompareImplicitConversionSequences(
4880                                 S, From->getBeginLoc(), ICS, Result) ==
4881                                 ImplicitConversionSequence::Worse)
4882         Result = ICS;
4883     }
4884 
4885     // For an empty list, we won't have computed any conversion sequence.
4886     // Introduce the identity conversion sequence.
4887     if (From->getNumInits() == 0) {
4888       Result.setStandard();
4889       Result.Standard.setAsIdentityConversion();
4890       Result.Standard.setFromType(ToType);
4891       Result.Standard.setAllToTypes(ToType);
4892     }
4893 
4894     Result.setStdInitializerListElement(toStdInitializerList);
4895     return Result;
4896   }
4897 
4898   // C++14 [over.ics.list]p4:
4899   // C++11 [over.ics.list]p3:
4900   //   Otherwise, if the parameter is a non-aggregate class X and overload
4901   //   resolution chooses a single best constructor [...] the implicit
4902   //   conversion sequence is a user-defined conversion sequence. If multiple
4903   //   constructors are viable but none is better than the others, the
4904   //   implicit conversion sequence is a user-defined conversion sequence.
4905   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4906     // This function can deal with initializer lists.
4907     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4908                                     /*AllowExplicit=*/false,
4909                                     InOverloadResolution, /*CStyle=*/false,
4910                                     AllowObjCWritebackConversion,
4911                                     /*AllowObjCConversionOnExplicit=*/false);
4912   }
4913 
4914   // C++14 [over.ics.list]p5:
4915   // C++11 [over.ics.list]p4:
4916   //   Otherwise, if the parameter has an aggregate type which can be
4917   //   initialized from the initializer list [...] the implicit conversion
4918   //   sequence is a user-defined conversion sequence.
4919   if (ToType->isAggregateType()) {
4920     // Type is an aggregate, argument is an init list. At this point it comes
4921     // down to checking whether the initialization works.
4922     // FIXME: Find out whether this parameter is consumed or not.
4923     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4924     // need to call into the initialization code here; overload resolution
4925     // should not be doing that.
4926     InitializedEntity Entity =
4927         InitializedEntity::InitializeParameter(S.Context, ToType,
4928                                                /*Consumed=*/false);
4929     if (S.CanPerformCopyInitialization(Entity, From)) {
4930       Result.setUserDefined();
4931       Result.UserDefined.Before.setAsIdentityConversion();
4932       // Initializer lists don't have a type.
4933       Result.UserDefined.Before.setFromType(QualType());
4934       Result.UserDefined.Before.setAllToTypes(QualType());
4935 
4936       Result.UserDefined.After.setAsIdentityConversion();
4937       Result.UserDefined.After.setFromType(ToType);
4938       Result.UserDefined.After.setAllToTypes(ToType);
4939       Result.UserDefined.ConversionFunction = nullptr;
4940     }
4941     return Result;
4942   }
4943 
4944   // C++14 [over.ics.list]p6:
4945   // C++11 [over.ics.list]p5:
4946   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4947   if (ToType->isReferenceType()) {
4948     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4949     // mention initializer lists in any way. So we go by what list-
4950     // initialization would do and try to extrapolate from that.
4951 
4952     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4953 
4954     // If the initializer list has a single element that is reference-related
4955     // to the parameter type, we initialize the reference from that.
4956     if (From->getNumInits() == 1) {
4957       Expr *Init = From->getInit(0);
4958 
4959       QualType T2 = Init->getType();
4960 
4961       // If the initializer is the address of an overloaded function, try
4962       // to resolve the overloaded function. If all goes well, T2 is the
4963       // type of the resulting function.
4964       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4965         DeclAccessPair Found;
4966         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4967                                    Init, ToType, false, Found))
4968           T2 = Fn->getType();
4969       }
4970 
4971       // Compute some basic properties of the types and the initializer.
4972       bool dummy1 = false;
4973       bool dummy2 = false;
4974       bool dummy3 = false;
4975       Sema::ReferenceCompareResult RefRelationship =
4976           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4977                                          dummy2, dummy3);
4978 
4979       if (RefRelationship >= Sema::Ref_Related) {
4980         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4981                                 SuppressUserConversions,
4982                                 /*AllowExplicit=*/false);
4983       }
4984     }
4985 
4986     // Otherwise, we bind the reference to a temporary created from the
4987     // initializer list.
4988     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4989                                InOverloadResolution,
4990                                AllowObjCWritebackConversion);
4991     if (Result.isFailure())
4992       return Result;
4993     assert(!Result.isEllipsis() &&
4994            "Sub-initialization cannot result in ellipsis conversion.");
4995 
4996     // Can we even bind to a temporary?
4997     if (ToType->isRValueReferenceType() ||
4998         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4999       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5000                                             Result.UserDefined.After;
5001       SCS.ReferenceBinding = true;
5002       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5003       SCS.BindsToRvalue = true;
5004       SCS.BindsToFunctionLvalue = false;
5005       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5006       SCS.ObjCLifetimeConversionBinding = false;
5007     } else
5008       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5009                     From, ToType);
5010     return Result;
5011   }
5012 
5013   // C++14 [over.ics.list]p7:
5014   // C++11 [over.ics.list]p6:
5015   //   Otherwise, if the parameter type is not a class:
5016   if (!ToType->isRecordType()) {
5017     //    - if the initializer list has one element that is not itself an
5018     //      initializer list, the implicit conversion sequence is the one
5019     //      required to convert the element to the parameter type.
5020     unsigned NumInits = From->getNumInits();
5021     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5022       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5023                                      SuppressUserConversions,
5024                                      InOverloadResolution,
5025                                      AllowObjCWritebackConversion);
5026     //    - if the initializer list has no elements, the implicit conversion
5027     //      sequence is the identity conversion.
5028     else if (NumInits == 0) {
5029       Result.setStandard();
5030       Result.Standard.setAsIdentityConversion();
5031       Result.Standard.setFromType(ToType);
5032       Result.Standard.setAllToTypes(ToType);
5033     }
5034     return Result;
5035   }
5036 
5037   // C++14 [over.ics.list]p8:
5038   // C++11 [over.ics.list]p7:
5039   //   In all cases other than those enumerated above, no conversion is possible
5040   return Result;
5041 }
5042 
5043 /// TryCopyInitialization - Try to copy-initialize a value of type
5044 /// ToType from the expression From. Return the implicit conversion
5045 /// sequence required to pass this argument, which may be a bad
5046 /// conversion sequence (meaning that the argument cannot be passed to
5047 /// a parameter of this type). If @p SuppressUserConversions, then we
5048 /// do not permit any user-defined conversion sequences.
5049 static ImplicitConversionSequence
5050 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5051                       bool SuppressUserConversions,
5052                       bool InOverloadResolution,
5053                       bool AllowObjCWritebackConversion,
5054                       bool AllowExplicit) {
5055   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5056     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5057                              InOverloadResolution,AllowObjCWritebackConversion);
5058 
5059   if (ToType->isReferenceType())
5060     return TryReferenceInit(S, From, ToType,
5061                             /*FIXME:*/ From->getBeginLoc(),
5062                             SuppressUserConversions, AllowExplicit);
5063 
5064   return TryImplicitConversion(S, From, ToType,
5065                                SuppressUserConversions,
5066                                /*AllowExplicit=*/false,
5067                                InOverloadResolution,
5068                                /*CStyle=*/false,
5069                                AllowObjCWritebackConversion,
5070                                /*AllowObjCConversionOnExplicit=*/false);
5071 }
5072 
5073 static bool TryCopyInitialization(const CanQualType FromQTy,
5074                                   const CanQualType ToQTy,
5075                                   Sema &S,
5076                                   SourceLocation Loc,
5077                                   ExprValueKind FromVK) {
5078   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5079   ImplicitConversionSequence ICS =
5080     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5081 
5082   return !ICS.isBad();
5083 }
5084 
5085 /// TryObjectArgumentInitialization - Try to initialize the object
5086 /// parameter of the given member function (@c Method) from the
5087 /// expression @p From.
5088 static ImplicitConversionSequence
5089 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5090                                 Expr::Classification FromClassification,
5091                                 CXXMethodDecl *Method,
5092                                 CXXRecordDecl *ActingContext) {
5093   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5094   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5095   //                 const volatile object.
5096   Qualifiers Quals = Method->getMethodQualifiers();
5097   if (isa<CXXDestructorDecl>(Method)) {
5098     Quals.addConst();
5099     Quals.addVolatile();
5100   }
5101 
5102   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5103 
5104   // Set up the conversion sequence as a "bad" conversion, to allow us
5105   // to exit early.
5106   ImplicitConversionSequence ICS;
5107 
5108   // We need to have an object of class type.
5109   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5110     FromType = PT->getPointeeType();
5111 
5112     // When we had a pointer, it's implicitly dereferenced, so we
5113     // better have an lvalue.
5114     assert(FromClassification.isLValue());
5115   }
5116 
5117   assert(FromType->isRecordType());
5118 
5119   // C++0x [over.match.funcs]p4:
5120   //   For non-static member functions, the type of the implicit object
5121   //   parameter is
5122   //
5123   //     - "lvalue reference to cv X" for functions declared without a
5124   //        ref-qualifier or with the & ref-qualifier
5125   //     - "rvalue reference to cv X" for functions declared with the &&
5126   //        ref-qualifier
5127   //
5128   // where X is the class of which the function is a member and cv is the
5129   // cv-qualification on the member function declaration.
5130   //
5131   // However, when finding an implicit conversion sequence for the argument, we
5132   // are not allowed to perform user-defined conversions
5133   // (C++ [over.match.funcs]p5). We perform a simplified version of
5134   // reference binding here, that allows class rvalues to bind to
5135   // non-constant references.
5136 
5137   // First check the qualifiers.
5138   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5139   if (ImplicitParamType.getCVRQualifiers()
5140                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5141       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5142     ICS.setBad(BadConversionSequence::bad_qualifiers,
5143                FromType, ImplicitParamType);
5144     return ICS;
5145   }
5146 
5147   if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5148     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5149     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5150     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5151       ICS.setBad(BadConversionSequence::bad_qualifiers,
5152                  FromType, ImplicitParamType);
5153       return ICS;
5154     }
5155   }
5156 
5157   // Check that we have either the same type or a derived type. It
5158   // affects the conversion rank.
5159   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5160   ImplicitConversionKind SecondKind;
5161   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5162     SecondKind = ICK_Identity;
5163   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5164     SecondKind = ICK_Derived_To_Base;
5165   else {
5166     ICS.setBad(BadConversionSequence::unrelated_class,
5167                FromType, ImplicitParamType);
5168     return ICS;
5169   }
5170 
5171   // Check the ref-qualifier.
5172   switch (Method->getRefQualifier()) {
5173   case RQ_None:
5174     // Do nothing; we don't care about lvalueness or rvalueness.
5175     break;
5176 
5177   case RQ_LValue:
5178     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5179       // non-const lvalue reference cannot bind to an rvalue
5180       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5181                  ImplicitParamType);
5182       return ICS;
5183     }
5184     break;
5185 
5186   case RQ_RValue:
5187     if (!FromClassification.isRValue()) {
5188       // rvalue reference cannot bind to an lvalue
5189       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5190                  ImplicitParamType);
5191       return ICS;
5192     }
5193     break;
5194   }
5195 
5196   // Success. Mark this as a reference binding.
5197   ICS.setStandard();
5198   ICS.Standard.setAsIdentityConversion();
5199   ICS.Standard.Second = SecondKind;
5200   ICS.Standard.setFromType(FromType);
5201   ICS.Standard.setAllToTypes(ImplicitParamType);
5202   ICS.Standard.ReferenceBinding = true;
5203   ICS.Standard.DirectBinding = true;
5204   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5205   ICS.Standard.BindsToFunctionLvalue = false;
5206   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5207   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5208     = (Method->getRefQualifier() == RQ_None);
5209   return ICS;
5210 }
5211 
5212 /// PerformObjectArgumentInitialization - Perform initialization of
5213 /// the implicit object parameter for the given Method with the given
5214 /// expression.
5215 ExprResult
5216 Sema::PerformObjectArgumentInitialization(Expr *From,
5217                                           NestedNameSpecifier *Qualifier,
5218                                           NamedDecl *FoundDecl,
5219                                           CXXMethodDecl *Method) {
5220   QualType FromRecordType, DestType;
5221   QualType ImplicitParamRecordType  =
5222     Method->getThisType()->getAs<PointerType>()->getPointeeType();
5223 
5224   Expr::Classification FromClassification;
5225   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5226     FromRecordType = PT->getPointeeType();
5227     DestType = Method->getThisType();
5228     FromClassification = Expr::Classification::makeSimpleLValue();
5229   } else {
5230     FromRecordType = From->getType();
5231     DestType = ImplicitParamRecordType;
5232     FromClassification = From->Classify(Context);
5233 
5234     // When performing member access on an rvalue, materialize a temporary.
5235     if (From->isRValue()) {
5236       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5237                                             Method->getRefQualifier() !=
5238                                                 RefQualifierKind::RQ_RValue);
5239     }
5240   }
5241 
5242   // Note that we always use the true parent context when performing
5243   // the actual argument initialization.
5244   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5245       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5246       Method->getParent());
5247   if (ICS.isBad()) {
5248     switch (ICS.Bad.Kind) {
5249     case BadConversionSequence::bad_qualifiers: {
5250       Qualifiers FromQs = FromRecordType.getQualifiers();
5251       Qualifiers ToQs = DestType.getQualifiers();
5252       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5253       if (CVR) {
5254         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5255             << Method->getDeclName() << FromRecordType << (CVR - 1)
5256             << From->getSourceRange();
5257         Diag(Method->getLocation(), diag::note_previous_decl)
5258           << Method->getDeclName();
5259         return ExprError();
5260       }
5261       break;
5262     }
5263 
5264     case BadConversionSequence::lvalue_ref_to_rvalue:
5265     case BadConversionSequence::rvalue_ref_to_lvalue: {
5266       bool IsRValueQualified =
5267         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5268       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5269           << Method->getDeclName() << FromClassification.isRValue()
5270           << IsRValueQualified;
5271       Diag(Method->getLocation(), diag::note_previous_decl)
5272         << Method->getDeclName();
5273       return ExprError();
5274     }
5275 
5276     case BadConversionSequence::no_conversion:
5277     case BadConversionSequence::unrelated_class:
5278       break;
5279     }
5280 
5281     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5282            << ImplicitParamRecordType << FromRecordType
5283            << From->getSourceRange();
5284   }
5285 
5286   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5287     ExprResult FromRes =
5288       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5289     if (FromRes.isInvalid())
5290       return ExprError();
5291     From = FromRes.get();
5292   }
5293 
5294   if (!Context.hasSameType(From->getType(), DestType)) {
5295     CastKind CK;
5296     if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
5297       CK = CK_AddressSpaceConversion;
5298     else
5299       CK = CK_NoOp;
5300     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5301   }
5302   return From;
5303 }
5304 
5305 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5306 /// expression From to bool (C++0x [conv]p3).
5307 static ImplicitConversionSequence
5308 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5309   return TryImplicitConversion(S, From, S.Context.BoolTy,
5310                                /*SuppressUserConversions=*/false,
5311                                /*AllowExplicit=*/true,
5312                                /*InOverloadResolution=*/false,
5313                                /*CStyle=*/false,
5314                                /*AllowObjCWritebackConversion=*/false,
5315                                /*AllowObjCConversionOnExplicit=*/false);
5316 }
5317 
5318 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5319 /// of the expression From to bool (C++0x [conv]p3).
5320 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5321   if (checkPlaceholderForOverload(*this, From))
5322     return ExprError();
5323 
5324   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5325   if (!ICS.isBad())
5326     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5327 
5328   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5329     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5330            << From->getType() << From->getSourceRange();
5331   return ExprError();
5332 }
5333 
5334 /// Check that the specified conversion is permitted in a converted constant
5335 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5336 /// is acceptable.
5337 static bool CheckConvertedConstantConversions(Sema &S,
5338                                               StandardConversionSequence &SCS) {
5339   // Since we know that the target type is an integral or unscoped enumeration
5340   // type, most conversion kinds are impossible. All possible First and Third
5341   // conversions are fine.
5342   switch (SCS.Second) {
5343   case ICK_Identity:
5344   case ICK_Function_Conversion:
5345   case ICK_Integral_Promotion:
5346   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5347   case ICK_Zero_Queue_Conversion:
5348     return true;
5349 
5350   case ICK_Boolean_Conversion:
5351     // Conversion from an integral or unscoped enumeration type to bool is
5352     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5353     // conversion, so we allow it in a converted constant expression.
5354     //
5355     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5356     // a lot of popular code. We should at least add a warning for this
5357     // (non-conforming) extension.
5358     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5359            SCS.getToType(2)->isBooleanType();
5360 
5361   case ICK_Pointer_Conversion:
5362   case ICK_Pointer_Member:
5363     // C++1z: null pointer conversions and null member pointer conversions are
5364     // only permitted if the source type is std::nullptr_t.
5365     return SCS.getFromType()->isNullPtrType();
5366 
5367   case ICK_Floating_Promotion:
5368   case ICK_Complex_Promotion:
5369   case ICK_Floating_Conversion:
5370   case ICK_Complex_Conversion:
5371   case ICK_Floating_Integral:
5372   case ICK_Compatible_Conversion:
5373   case ICK_Derived_To_Base:
5374   case ICK_Vector_Conversion:
5375   case ICK_Vector_Splat:
5376   case ICK_Complex_Real:
5377   case ICK_Block_Pointer_Conversion:
5378   case ICK_TransparentUnionConversion:
5379   case ICK_Writeback_Conversion:
5380   case ICK_Zero_Event_Conversion:
5381   case ICK_C_Only_Conversion:
5382   case ICK_Incompatible_Pointer_Conversion:
5383     return false;
5384 
5385   case ICK_Lvalue_To_Rvalue:
5386   case ICK_Array_To_Pointer:
5387   case ICK_Function_To_Pointer:
5388     llvm_unreachable("found a first conversion kind in Second");
5389 
5390   case ICK_Qualification:
5391     llvm_unreachable("found a third conversion kind in Second");
5392 
5393   case ICK_Num_Conversion_Kinds:
5394     break;
5395   }
5396 
5397   llvm_unreachable("unknown conversion kind");
5398 }
5399 
5400 /// CheckConvertedConstantExpression - Check that the expression From is a
5401 /// converted constant expression of type T, perform the conversion and produce
5402 /// the converted expression, per C++11 [expr.const]p3.
5403 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5404                                                    QualType T, APValue &Value,
5405                                                    Sema::CCEKind CCE,
5406                                                    bool RequireInt) {
5407   assert(S.getLangOpts().CPlusPlus11 &&
5408          "converted constant expression outside C++11");
5409 
5410   if (checkPlaceholderForOverload(S, From))
5411     return ExprError();
5412 
5413   // C++1z [expr.const]p3:
5414   //  A converted constant expression of type T is an expression,
5415   //  implicitly converted to type T, where the converted
5416   //  expression is a constant expression and the implicit conversion
5417   //  sequence contains only [... list of conversions ...].
5418   // C++1z [stmt.if]p2:
5419   //  If the if statement is of the form if constexpr, the value of the
5420   //  condition shall be a contextually converted constant expression of type
5421   //  bool.
5422   ImplicitConversionSequence ICS =
5423       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5424           ? TryContextuallyConvertToBool(S, From)
5425           : TryCopyInitialization(S, From, T,
5426                                   /*SuppressUserConversions=*/false,
5427                                   /*InOverloadResolution=*/false,
5428                                   /*AllowObjCWritebackConversion=*/false,
5429                                   /*AllowExplicit=*/false);
5430   StandardConversionSequence *SCS = nullptr;
5431   switch (ICS.getKind()) {
5432   case ImplicitConversionSequence::StandardConversion:
5433     SCS = &ICS.Standard;
5434     break;
5435   case ImplicitConversionSequence::UserDefinedConversion:
5436     // We are converting to a non-class type, so the Before sequence
5437     // must be trivial.
5438     SCS = &ICS.UserDefined.After;
5439     break;
5440   case ImplicitConversionSequence::AmbiguousConversion:
5441   case ImplicitConversionSequence::BadConversion:
5442     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5443       return S.Diag(From->getBeginLoc(),
5444                     diag::err_typecheck_converted_constant_expression)
5445              << From->getType() << From->getSourceRange() << T;
5446     return ExprError();
5447 
5448   case ImplicitConversionSequence::EllipsisConversion:
5449     llvm_unreachable("ellipsis conversion in converted constant expression");
5450   }
5451 
5452   // Check that we would only use permitted conversions.
5453   if (!CheckConvertedConstantConversions(S, *SCS)) {
5454     return S.Diag(From->getBeginLoc(),
5455                   diag::err_typecheck_converted_constant_expression_disallowed)
5456            << From->getType() << From->getSourceRange() << T;
5457   }
5458   // [...] and where the reference binding (if any) binds directly.
5459   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5460     return S.Diag(From->getBeginLoc(),
5461                   diag::err_typecheck_converted_constant_expression_indirect)
5462            << From->getType() << From->getSourceRange() << T;
5463   }
5464 
5465   ExprResult Result =
5466       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5467   if (Result.isInvalid())
5468     return Result;
5469 
5470   // Check for a narrowing implicit conversion.
5471   APValue PreNarrowingValue;
5472   QualType PreNarrowingType;
5473   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5474                                 PreNarrowingType)) {
5475   case NK_Dependent_Narrowing:
5476     // Implicit conversion to a narrower type, but the expression is
5477     // value-dependent so we can't tell whether it's actually narrowing.
5478   case NK_Variable_Narrowing:
5479     // Implicit conversion to a narrower type, and the value is not a constant
5480     // expression. We'll diagnose this in a moment.
5481   case NK_Not_Narrowing:
5482     break;
5483 
5484   case NK_Constant_Narrowing:
5485     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5486         << CCE << /*Constant*/ 1
5487         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5488     break;
5489 
5490   case NK_Type_Narrowing:
5491     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5492         << CCE << /*Constant*/ 0 << From->getType() << T;
5493     break;
5494   }
5495 
5496   if (Result.get()->isValueDependent()) {
5497     Value = APValue();
5498     return Result;
5499   }
5500 
5501   // Check the expression is a constant expression.
5502   SmallVector<PartialDiagnosticAt, 8> Notes;
5503   Expr::EvalResult Eval;
5504   Eval.Diag = &Notes;
5505   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5506                                    ? Expr::EvaluateForMangling
5507                                    : Expr::EvaluateForCodeGen;
5508 
5509   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5510       (RequireInt && !Eval.Val.isInt())) {
5511     // The expression can't be folded, so we can't keep it at this position in
5512     // the AST.
5513     Result = ExprError();
5514   } else {
5515     Value = Eval.Val;
5516 
5517     if (Notes.empty()) {
5518       // It's a constant expression.
5519       return ConstantExpr::Create(S.Context, Result.get(), Value);
5520     }
5521   }
5522 
5523   // It's not a constant expression. Produce an appropriate diagnostic.
5524   if (Notes.size() == 1 &&
5525       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5526     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5527   else {
5528     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5529         << CCE << From->getSourceRange();
5530     for (unsigned I = 0; I < Notes.size(); ++I)
5531       S.Diag(Notes[I].first, Notes[I].second);
5532   }
5533   return ExprError();
5534 }
5535 
5536 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5537                                                   APValue &Value, CCEKind CCE) {
5538   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5539 }
5540 
5541 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5542                                                   llvm::APSInt &Value,
5543                                                   CCEKind CCE) {
5544   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5545 
5546   APValue V;
5547   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5548   if (!R.isInvalid() && !R.get()->isValueDependent())
5549     Value = V.getInt();
5550   return R;
5551 }
5552 
5553 
5554 /// dropPointerConversions - If the given standard conversion sequence
5555 /// involves any pointer conversions, remove them.  This may change
5556 /// the result type of the conversion sequence.
5557 static void dropPointerConversion(StandardConversionSequence &SCS) {
5558   if (SCS.Second == ICK_Pointer_Conversion) {
5559     SCS.Second = ICK_Identity;
5560     SCS.Third = ICK_Identity;
5561     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5562   }
5563 }
5564 
5565 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5566 /// convert the expression From to an Objective-C pointer type.
5567 static ImplicitConversionSequence
5568 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5569   // Do an implicit conversion to 'id'.
5570   QualType Ty = S.Context.getObjCIdType();
5571   ImplicitConversionSequence ICS
5572     = TryImplicitConversion(S, From, Ty,
5573                             // FIXME: Are these flags correct?
5574                             /*SuppressUserConversions=*/false,
5575                             /*AllowExplicit=*/true,
5576                             /*InOverloadResolution=*/false,
5577                             /*CStyle=*/false,
5578                             /*AllowObjCWritebackConversion=*/false,
5579                             /*AllowObjCConversionOnExplicit=*/true);
5580 
5581   // Strip off any final conversions to 'id'.
5582   switch (ICS.getKind()) {
5583   case ImplicitConversionSequence::BadConversion:
5584   case ImplicitConversionSequence::AmbiguousConversion:
5585   case ImplicitConversionSequence::EllipsisConversion:
5586     break;
5587 
5588   case ImplicitConversionSequence::UserDefinedConversion:
5589     dropPointerConversion(ICS.UserDefined.After);
5590     break;
5591 
5592   case ImplicitConversionSequence::StandardConversion:
5593     dropPointerConversion(ICS.Standard);
5594     break;
5595   }
5596 
5597   return ICS;
5598 }
5599 
5600 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5601 /// conversion of the expression From to an Objective-C pointer type.
5602 /// Returns a valid but null ExprResult if no conversion sequence exists.
5603 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5604   if (checkPlaceholderForOverload(*this, From))
5605     return ExprError();
5606 
5607   QualType Ty = Context.getObjCIdType();
5608   ImplicitConversionSequence ICS =
5609     TryContextuallyConvertToObjCPointer(*this, From);
5610   if (!ICS.isBad())
5611     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5612   return ExprResult();
5613 }
5614 
5615 /// Determine whether the provided type is an integral type, or an enumeration
5616 /// type of a permitted flavor.
5617 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5618   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5619                                  : T->isIntegralOrUnscopedEnumerationType();
5620 }
5621 
5622 static ExprResult
5623 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5624                             Sema::ContextualImplicitConverter &Converter,
5625                             QualType T, UnresolvedSetImpl &ViableConversions) {
5626 
5627   if (Converter.Suppress)
5628     return ExprError();
5629 
5630   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5631   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5632     CXXConversionDecl *Conv =
5633         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5634     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5635     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5636   }
5637   return From;
5638 }
5639 
5640 static bool
5641 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5642                            Sema::ContextualImplicitConverter &Converter,
5643                            QualType T, bool HadMultipleCandidates,
5644                            UnresolvedSetImpl &ExplicitConversions) {
5645   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5646     DeclAccessPair Found = ExplicitConversions[0];
5647     CXXConversionDecl *Conversion =
5648         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5649 
5650     // The user probably meant to invoke the given explicit
5651     // conversion; use it.
5652     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5653     std::string TypeStr;
5654     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5655 
5656     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5657         << FixItHint::CreateInsertion(From->getBeginLoc(),
5658                                       "static_cast<" + TypeStr + ">(")
5659         << FixItHint::CreateInsertion(
5660                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5661     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5662 
5663     // If we aren't in a SFINAE context, build a call to the
5664     // explicit conversion function.
5665     if (SemaRef.isSFINAEContext())
5666       return true;
5667 
5668     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5669     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5670                                                        HadMultipleCandidates);
5671     if (Result.isInvalid())
5672       return true;
5673     // Record usage of conversion in an implicit cast.
5674     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5675                                     CK_UserDefinedConversion, Result.get(),
5676                                     nullptr, Result.get()->getValueKind());
5677   }
5678   return false;
5679 }
5680 
5681 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5682                              Sema::ContextualImplicitConverter &Converter,
5683                              QualType T, bool HadMultipleCandidates,
5684                              DeclAccessPair &Found) {
5685   CXXConversionDecl *Conversion =
5686       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5687   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5688 
5689   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5690   if (!Converter.SuppressConversion) {
5691     if (SemaRef.isSFINAEContext())
5692       return true;
5693 
5694     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5695         << From->getSourceRange();
5696   }
5697 
5698   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5699                                                      HadMultipleCandidates);
5700   if (Result.isInvalid())
5701     return true;
5702   // Record usage of conversion in an implicit cast.
5703   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5704                                   CK_UserDefinedConversion, Result.get(),
5705                                   nullptr, Result.get()->getValueKind());
5706   return false;
5707 }
5708 
5709 static ExprResult finishContextualImplicitConversion(
5710     Sema &SemaRef, SourceLocation Loc, Expr *From,
5711     Sema::ContextualImplicitConverter &Converter) {
5712   if (!Converter.match(From->getType()) && !Converter.Suppress)
5713     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5714         << From->getSourceRange();
5715 
5716   return SemaRef.DefaultLvalueConversion(From);
5717 }
5718 
5719 static void
5720 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5721                                   UnresolvedSetImpl &ViableConversions,
5722                                   OverloadCandidateSet &CandidateSet) {
5723   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5724     DeclAccessPair FoundDecl = ViableConversions[I];
5725     NamedDecl *D = FoundDecl.getDecl();
5726     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5727     if (isa<UsingShadowDecl>(D))
5728       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5729 
5730     CXXConversionDecl *Conv;
5731     FunctionTemplateDecl *ConvTemplate;
5732     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5733       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5734     else
5735       Conv = cast<CXXConversionDecl>(D);
5736 
5737     if (ConvTemplate)
5738       SemaRef.AddTemplateConversionCandidate(
5739           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5740           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5741     else
5742       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5743                                      ToType, CandidateSet,
5744                                      /*AllowObjCConversionOnExplicit=*/false,
5745                                      /*AllowExplicit*/ true);
5746   }
5747 }
5748 
5749 /// Attempt to convert the given expression to a type which is accepted
5750 /// by the given converter.
5751 ///
5752 /// This routine will attempt to convert an expression of class type to a
5753 /// type accepted by the specified converter. In C++11 and before, the class
5754 /// must have a single non-explicit conversion function converting to a matching
5755 /// type. In C++1y, there can be multiple such conversion functions, but only
5756 /// one target type.
5757 ///
5758 /// \param Loc The source location of the construct that requires the
5759 /// conversion.
5760 ///
5761 /// \param From The expression we're converting from.
5762 ///
5763 /// \param Converter Used to control and diagnose the conversion process.
5764 ///
5765 /// \returns The expression, converted to an integral or enumeration type if
5766 /// successful.
5767 ExprResult Sema::PerformContextualImplicitConversion(
5768     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5769   // We can't perform any more checking for type-dependent expressions.
5770   if (From->isTypeDependent())
5771     return From;
5772 
5773   // Process placeholders immediately.
5774   if (From->hasPlaceholderType()) {
5775     ExprResult result = CheckPlaceholderExpr(From);
5776     if (result.isInvalid())
5777       return result;
5778     From = result.get();
5779   }
5780 
5781   // If the expression already has a matching type, we're golden.
5782   QualType T = From->getType();
5783   if (Converter.match(T))
5784     return DefaultLvalueConversion(From);
5785 
5786   // FIXME: Check for missing '()' if T is a function type?
5787 
5788   // We can only perform contextual implicit conversions on objects of class
5789   // type.
5790   const RecordType *RecordTy = T->getAs<RecordType>();
5791   if (!RecordTy || !getLangOpts().CPlusPlus) {
5792     if (!Converter.Suppress)
5793       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5794     return From;
5795   }
5796 
5797   // We must have a complete class type.
5798   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5799     ContextualImplicitConverter &Converter;
5800     Expr *From;
5801 
5802     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5803         : Converter(Converter), From(From) {}
5804 
5805     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5806       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5807     }
5808   } IncompleteDiagnoser(Converter, From);
5809 
5810   if (Converter.Suppress ? !isCompleteType(Loc, T)
5811                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5812     return From;
5813 
5814   // Look for a conversion to an integral or enumeration type.
5815   UnresolvedSet<4>
5816       ViableConversions; // These are *potentially* viable in C++1y.
5817   UnresolvedSet<4> ExplicitConversions;
5818   const auto &Conversions =
5819       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5820 
5821   bool HadMultipleCandidates =
5822       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5823 
5824   // To check that there is only one target type, in C++1y:
5825   QualType ToType;
5826   bool HasUniqueTargetType = true;
5827 
5828   // Collect explicit or viable (potentially in C++1y) conversions.
5829   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5830     NamedDecl *D = (*I)->getUnderlyingDecl();
5831     CXXConversionDecl *Conversion;
5832     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5833     if (ConvTemplate) {
5834       if (getLangOpts().CPlusPlus14)
5835         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5836       else
5837         continue; // C++11 does not consider conversion operator templates(?).
5838     } else
5839       Conversion = cast<CXXConversionDecl>(D);
5840 
5841     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5842            "Conversion operator templates are considered potentially "
5843            "viable in C++1y");
5844 
5845     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5846     if (Converter.match(CurToType) || ConvTemplate) {
5847 
5848       if (Conversion->isExplicit()) {
5849         // FIXME: For C++1y, do we need this restriction?
5850         // cf. diagnoseNoViableConversion()
5851         if (!ConvTemplate)
5852           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5853       } else {
5854         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5855           if (ToType.isNull())
5856             ToType = CurToType.getUnqualifiedType();
5857           else if (HasUniqueTargetType &&
5858                    (CurToType.getUnqualifiedType() != ToType))
5859             HasUniqueTargetType = false;
5860         }
5861         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5862       }
5863     }
5864   }
5865 
5866   if (getLangOpts().CPlusPlus14) {
5867     // C++1y [conv]p6:
5868     // ... An expression e of class type E appearing in such a context
5869     // is said to be contextually implicitly converted to a specified
5870     // type T and is well-formed if and only if e can be implicitly
5871     // converted to a type T that is determined as follows: E is searched
5872     // for conversion functions whose return type is cv T or reference to
5873     // cv T such that T is allowed by the context. There shall be
5874     // exactly one such T.
5875 
5876     // If no unique T is found:
5877     if (ToType.isNull()) {
5878       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5879                                      HadMultipleCandidates,
5880                                      ExplicitConversions))
5881         return ExprError();
5882       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5883     }
5884 
5885     // If more than one unique Ts are found:
5886     if (!HasUniqueTargetType)
5887       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5888                                          ViableConversions);
5889 
5890     // If one unique T is found:
5891     // First, build a candidate set from the previously recorded
5892     // potentially viable conversions.
5893     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5894     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5895                                       CandidateSet);
5896 
5897     // Then, perform overload resolution over the candidate set.
5898     OverloadCandidateSet::iterator Best;
5899     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5900     case OR_Success: {
5901       // Apply this conversion.
5902       DeclAccessPair Found =
5903           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5904       if (recordConversion(*this, Loc, From, Converter, T,
5905                            HadMultipleCandidates, Found))
5906         return ExprError();
5907       break;
5908     }
5909     case OR_Ambiguous:
5910       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5911                                          ViableConversions);
5912     case OR_No_Viable_Function:
5913       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5914                                      HadMultipleCandidates,
5915                                      ExplicitConversions))
5916         return ExprError();
5917       LLVM_FALLTHROUGH;
5918     case OR_Deleted:
5919       // We'll complain below about a non-integral condition type.
5920       break;
5921     }
5922   } else {
5923     switch (ViableConversions.size()) {
5924     case 0: {
5925       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5926                                      HadMultipleCandidates,
5927                                      ExplicitConversions))
5928         return ExprError();
5929 
5930       // We'll complain below about a non-integral condition type.
5931       break;
5932     }
5933     case 1: {
5934       // Apply this conversion.
5935       DeclAccessPair Found = ViableConversions[0];
5936       if (recordConversion(*this, Loc, From, Converter, T,
5937                            HadMultipleCandidates, Found))
5938         return ExprError();
5939       break;
5940     }
5941     default:
5942       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5943                                          ViableConversions);
5944     }
5945   }
5946 
5947   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5948 }
5949 
5950 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5951 /// an acceptable non-member overloaded operator for a call whose
5952 /// arguments have types T1 (and, if non-empty, T2). This routine
5953 /// implements the check in C++ [over.match.oper]p3b2 concerning
5954 /// enumeration types.
5955 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5956                                                    FunctionDecl *Fn,
5957                                                    ArrayRef<Expr *> Args) {
5958   QualType T1 = Args[0]->getType();
5959   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5960 
5961   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5962     return true;
5963 
5964   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5965     return true;
5966 
5967   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5968   if (Proto->getNumParams() < 1)
5969     return false;
5970 
5971   if (T1->isEnumeralType()) {
5972     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5973     if (Context.hasSameUnqualifiedType(T1, ArgType))
5974       return true;
5975   }
5976 
5977   if (Proto->getNumParams() < 2)
5978     return false;
5979 
5980   if (!T2.isNull() && T2->isEnumeralType()) {
5981     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5982     if (Context.hasSameUnqualifiedType(T2, ArgType))
5983       return true;
5984   }
5985 
5986   return false;
5987 }
5988 
5989 /// AddOverloadCandidate - Adds the given function to the set of
5990 /// candidate functions, using the given function call arguments.  If
5991 /// @p SuppressUserConversions, then don't allow user-defined
5992 /// conversions via constructors or conversion operators.
5993 ///
5994 /// \param PartialOverloading true if we are performing "partial" overloading
5995 /// based on an incomplete set of function arguments. This feature is used by
5996 /// code completion.
5997 void Sema::AddOverloadCandidate(
5998     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5999     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6000     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6001     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) {
6002   const FunctionProtoType *Proto
6003     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6004   assert(Proto && "Functions without a prototype cannot be overloaded");
6005   assert(!Function->getDescribedFunctionTemplate() &&
6006          "Use AddTemplateOverloadCandidate for function templates");
6007 
6008   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6009     if (!isa<CXXConstructorDecl>(Method)) {
6010       // If we get here, it's because we're calling a member function
6011       // that is named without a member access expression (e.g.,
6012       // "this->f") that was either written explicitly or created
6013       // implicitly. This can happen with a qualified call to a member
6014       // function, e.g., X::f(). We use an empty type for the implied
6015       // object argument (C++ [over.call.func]p3), and the acting context
6016       // is irrelevant.
6017       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6018                          Expr::Classification::makeSimpleLValue(), Args,
6019                          CandidateSet, SuppressUserConversions,
6020                          PartialOverloading, EarlyConversions);
6021       return;
6022     }
6023     // We treat a constructor like a non-member function, since its object
6024     // argument doesn't participate in overload resolution.
6025   }
6026 
6027   if (!CandidateSet.isNewCandidate(Function))
6028     return;
6029 
6030   // C++ [over.match.oper]p3:
6031   //   if no operand has a class type, only those non-member functions in the
6032   //   lookup set that have a first parameter of type T1 or "reference to
6033   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6034   //   is a right operand) a second parameter of type T2 or "reference to
6035   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6036   //   candidate functions.
6037   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6038       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6039     return;
6040 
6041   // C++11 [class.copy]p11: [DR1402]
6042   //   A defaulted move constructor that is defined as deleted is ignored by
6043   //   overload resolution.
6044   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6045   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6046       Constructor->isMoveConstructor())
6047     return;
6048 
6049   // Overload resolution is always an unevaluated context.
6050   EnterExpressionEvaluationContext Unevaluated(
6051       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6052 
6053   // Add this candidate
6054   OverloadCandidate &Candidate =
6055       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6056   Candidate.FoundDecl = FoundDecl;
6057   Candidate.Function = Function;
6058   Candidate.Viable = true;
6059   Candidate.IsSurrogate = false;
6060   Candidate.IsADLCandidate = IsADLCandidate;
6061   Candidate.IgnoreObjectArgument = false;
6062   Candidate.ExplicitCallArguments = Args.size();
6063 
6064   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6065       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6066     Candidate.Viable = false;
6067     Candidate.FailureKind = ovl_non_default_multiversion_function;
6068     return;
6069   }
6070 
6071   if (Constructor) {
6072     // C++ [class.copy]p3:
6073     //   A member function template is never instantiated to perform the copy
6074     //   of a class object to an object of its class type.
6075     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6076     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6077         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6078          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6079                        ClassType))) {
6080       Candidate.Viable = false;
6081       Candidate.FailureKind = ovl_fail_illegal_constructor;
6082       return;
6083     }
6084 
6085     // C++ [over.match.funcs]p8: (proposed DR resolution)
6086     //   A constructor inherited from class type C that has a first parameter
6087     //   of type "reference to P" (including such a constructor instantiated
6088     //   from a template) is excluded from the set of candidate functions when
6089     //   constructing an object of type cv D if the argument list has exactly
6090     //   one argument and D is reference-related to P and P is reference-related
6091     //   to C.
6092     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6093     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6094         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6095       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6096       QualType C = Context.getRecordType(Constructor->getParent());
6097       QualType D = Context.getRecordType(Shadow->getParent());
6098       SourceLocation Loc = Args.front()->getExprLoc();
6099       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6100           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6101         Candidate.Viable = false;
6102         Candidate.FailureKind = ovl_fail_inhctor_slice;
6103         return;
6104       }
6105     }
6106 
6107     // Check that the constructor is capable of constructing an object in the
6108     // destination address space.
6109     if (!Qualifiers::isAddressSpaceSupersetOf(
6110             Constructor->getMethodQualifiers().getAddressSpace(),
6111             CandidateSet.getDestAS())) {
6112       Candidate.Viable = false;
6113       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6114     }
6115   }
6116 
6117   unsigned NumParams = Proto->getNumParams();
6118 
6119   // (C++ 13.3.2p2): A candidate function having fewer than m
6120   // parameters is viable only if it has an ellipsis in its parameter
6121   // list (8.3.5).
6122   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6123       !Proto->isVariadic()) {
6124     Candidate.Viable = false;
6125     Candidate.FailureKind = ovl_fail_too_many_arguments;
6126     return;
6127   }
6128 
6129   // (C++ 13.3.2p2): A candidate function having more than m parameters
6130   // is viable only if the (m+1)st parameter has a default argument
6131   // (8.3.6). For the purposes of overload resolution, the
6132   // parameter list is truncated on the right, so that there are
6133   // exactly m parameters.
6134   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6135   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6136     // Not enough arguments.
6137     Candidate.Viable = false;
6138     Candidate.FailureKind = ovl_fail_too_few_arguments;
6139     return;
6140   }
6141 
6142   // (CUDA B.1): Check for invalid calls between targets.
6143   if (getLangOpts().CUDA)
6144     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6145       // Skip the check for callers that are implicit members, because in this
6146       // case we may not yet know what the member's target is; the target is
6147       // inferred for the member automatically, based on the bases and fields of
6148       // the class.
6149       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6150         Candidate.Viable = false;
6151         Candidate.FailureKind = ovl_fail_bad_target;
6152         return;
6153       }
6154 
6155   // Determine the implicit conversion sequences for each of the
6156   // arguments.
6157   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6158     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6159       // We already formed a conversion sequence for this parameter during
6160       // template argument deduction.
6161     } else if (ArgIdx < NumParams) {
6162       // (C++ 13.3.2p3): for F to be a viable function, there shall
6163       // exist for each argument an implicit conversion sequence
6164       // (13.3.3.1) that converts that argument to the corresponding
6165       // parameter of F.
6166       QualType ParamType = Proto->getParamType(ArgIdx);
6167       Candidate.Conversions[ArgIdx] = TryCopyInitialization(
6168           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6169           /*InOverloadResolution=*/true,
6170           /*AllowObjCWritebackConversion=*/
6171           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6172       if (Candidate.Conversions[ArgIdx].isBad()) {
6173         Candidate.Viable = false;
6174         Candidate.FailureKind = ovl_fail_bad_conversion;
6175         return;
6176       }
6177     } else {
6178       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6179       // argument for which there is no corresponding parameter is
6180       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6181       Candidate.Conversions[ArgIdx].setEllipsis();
6182     }
6183   }
6184 
6185   if (!AllowExplicit) {
6186     ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6187     if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6188       Candidate.Viable = false;
6189       Candidate.FailureKind = ovl_fail_explicit_resolved;
6190       return;
6191     }
6192   }
6193 
6194   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6195     Candidate.Viable = false;
6196     Candidate.FailureKind = ovl_fail_enable_if;
6197     Candidate.DeductionFailure.Data = FailedAttr;
6198     return;
6199   }
6200 
6201   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6202     Candidate.Viable = false;
6203     Candidate.FailureKind = ovl_fail_ext_disabled;
6204     return;
6205   }
6206 }
6207 
6208 ObjCMethodDecl *
6209 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6210                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6211   if (Methods.size() <= 1)
6212     return nullptr;
6213 
6214   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6215     bool Match = true;
6216     ObjCMethodDecl *Method = Methods[b];
6217     unsigned NumNamedArgs = Sel.getNumArgs();
6218     // Method might have more arguments than selector indicates. This is due
6219     // to addition of c-style arguments in method.
6220     if (Method->param_size() > NumNamedArgs)
6221       NumNamedArgs = Method->param_size();
6222     if (Args.size() < NumNamedArgs)
6223       continue;
6224 
6225     for (unsigned i = 0; i < NumNamedArgs; i++) {
6226       // We can't do any type-checking on a type-dependent argument.
6227       if (Args[i]->isTypeDependent()) {
6228         Match = false;
6229         break;
6230       }
6231 
6232       ParmVarDecl *param = Method->parameters()[i];
6233       Expr *argExpr = Args[i];
6234       assert(argExpr && "SelectBestMethod(): missing expression");
6235 
6236       // Strip the unbridged-cast placeholder expression off unless it's
6237       // a consumed argument.
6238       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6239           !param->hasAttr<CFConsumedAttr>())
6240         argExpr = stripARCUnbridgedCast(argExpr);
6241 
6242       // If the parameter is __unknown_anytype, move on to the next method.
6243       if (param->getType() == Context.UnknownAnyTy) {
6244         Match = false;
6245         break;
6246       }
6247 
6248       ImplicitConversionSequence ConversionState
6249         = TryCopyInitialization(*this, argExpr, param->getType(),
6250                                 /*SuppressUserConversions*/false,
6251                                 /*InOverloadResolution=*/true,
6252                                 /*AllowObjCWritebackConversion=*/
6253                                 getLangOpts().ObjCAutoRefCount,
6254                                 /*AllowExplicit*/false);
6255       // This function looks for a reasonably-exact match, so we consider
6256       // incompatible pointer conversions to be a failure here.
6257       if (ConversionState.isBad() ||
6258           (ConversionState.isStandard() &&
6259            ConversionState.Standard.Second ==
6260                ICK_Incompatible_Pointer_Conversion)) {
6261         Match = false;
6262         break;
6263       }
6264     }
6265     // Promote additional arguments to variadic methods.
6266     if (Match && Method->isVariadic()) {
6267       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6268         if (Args[i]->isTypeDependent()) {
6269           Match = false;
6270           break;
6271         }
6272         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6273                                                           nullptr);
6274         if (Arg.isInvalid()) {
6275           Match = false;
6276           break;
6277         }
6278       }
6279     } else {
6280       // Check for extra arguments to non-variadic methods.
6281       if (Args.size() != NumNamedArgs)
6282         Match = false;
6283       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6284         // Special case when selectors have no argument. In this case, select
6285         // one with the most general result type of 'id'.
6286         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6287           QualType ReturnT = Methods[b]->getReturnType();
6288           if (ReturnT->isObjCIdType())
6289             return Methods[b];
6290         }
6291       }
6292     }
6293 
6294     if (Match)
6295       return Method;
6296   }
6297   return nullptr;
6298 }
6299 
6300 static bool
6301 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6302                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6303                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6304                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6305   if (ThisArg) {
6306     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6307     assert(!isa<CXXConstructorDecl>(Method) &&
6308            "Shouldn't have `this` for ctors!");
6309     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6310     ExprResult R = S.PerformObjectArgumentInitialization(
6311         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6312     if (R.isInvalid())
6313       return false;
6314     ConvertedThis = R.get();
6315   } else {
6316     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6317       (void)MD;
6318       assert((MissingImplicitThis || MD->isStatic() ||
6319               isa<CXXConstructorDecl>(MD)) &&
6320              "Expected `this` for non-ctor instance methods");
6321     }
6322     ConvertedThis = nullptr;
6323   }
6324 
6325   // Ignore any variadic arguments. Converting them is pointless, since the
6326   // user can't refer to them in the function condition.
6327   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6328 
6329   // Convert the arguments.
6330   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6331     ExprResult R;
6332     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6333                                         S.Context, Function->getParamDecl(I)),
6334                                     SourceLocation(), Args[I]);
6335 
6336     if (R.isInvalid())
6337       return false;
6338 
6339     ConvertedArgs.push_back(R.get());
6340   }
6341 
6342   if (Trap.hasErrorOccurred())
6343     return false;
6344 
6345   // Push default arguments if needed.
6346   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6347     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6348       ParmVarDecl *P = Function->getParamDecl(i);
6349       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6350                          ? P->getUninstantiatedDefaultArg()
6351                          : P->getDefaultArg();
6352       // This can only happen in code completion, i.e. when PartialOverloading
6353       // is true.
6354       if (!DefArg)
6355         return false;
6356       ExprResult R =
6357           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6358                                           S.Context, Function->getParamDecl(i)),
6359                                       SourceLocation(), DefArg);
6360       if (R.isInvalid())
6361         return false;
6362       ConvertedArgs.push_back(R.get());
6363     }
6364 
6365     if (Trap.hasErrorOccurred())
6366       return false;
6367   }
6368   return true;
6369 }
6370 
6371 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6372                                   bool MissingImplicitThis) {
6373   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6374   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6375     return nullptr;
6376 
6377   SFINAETrap Trap(*this);
6378   SmallVector<Expr *, 16> ConvertedArgs;
6379   // FIXME: We should look into making enable_if late-parsed.
6380   Expr *DiscardedThis;
6381   if (!convertArgsForAvailabilityChecks(
6382           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6383           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6384     return *EnableIfAttrs.begin();
6385 
6386   for (auto *EIA : EnableIfAttrs) {
6387     APValue Result;
6388     // FIXME: This doesn't consider value-dependent cases, because doing so is
6389     // very difficult. Ideally, we should handle them more gracefully.
6390     if (EIA->getCond()->isValueDependent() ||
6391         !EIA->getCond()->EvaluateWithSubstitution(
6392             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6393       return EIA;
6394 
6395     if (!Result.isInt() || !Result.getInt().getBoolValue())
6396       return EIA;
6397   }
6398   return nullptr;
6399 }
6400 
6401 template <typename CheckFn>
6402 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6403                                         bool ArgDependent, SourceLocation Loc,
6404                                         CheckFn &&IsSuccessful) {
6405   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6406   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6407     if (ArgDependent == DIA->getArgDependent())
6408       Attrs.push_back(DIA);
6409   }
6410 
6411   // Common case: No diagnose_if attributes, so we can quit early.
6412   if (Attrs.empty())
6413     return false;
6414 
6415   auto WarningBegin = std::stable_partition(
6416       Attrs.begin(), Attrs.end(),
6417       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6418 
6419   // Note that diagnose_if attributes are late-parsed, so they appear in the
6420   // correct order (unlike enable_if attributes).
6421   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6422                                IsSuccessful);
6423   if (ErrAttr != WarningBegin) {
6424     const DiagnoseIfAttr *DIA = *ErrAttr;
6425     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6426     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6427         << DIA->getParent() << DIA->getCond()->getSourceRange();
6428     return true;
6429   }
6430 
6431   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6432     if (IsSuccessful(DIA)) {
6433       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6434       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6435           << DIA->getParent() << DIA->getCond()->getSourceRange();
6436     }
6437 
6438   return false;
6439 }
6440 
6441 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6442                                                const Expr *ThisArg,
6443                                                ArrayRef<const Expr *> Args,
6444                                                SourceLocation Loc) {
6445   return diagnoseDiagnoseIfAttrsWith(
6446       *this, Function, /*ArgDependent=*/true, Loc,
6447       [&](const DiagnoseIfAttr *DIA) {
6448         APValue Result;
6449         // It's sane to use the same Args for any redecl of this function, since
6450         // EvaluateWithSubstitution only cares about the position of each
6451         // argument in the arg list, not the ParmVarDecl* it maps to.
6452         if (!DIA->getCond()->EvaluateWithSubstitution(
6453                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6454           return false;
6455         return Result.isInt() && Result.getInt().getBoolValue();
6456       });
6457 }
6458 
6459 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6460                                                  SourceLocation Loc) {
6461   return diagnoseDiagnoseIfAttrsWith(
6462       *this, ND, /*ArgDependent=*/false, Loc,
6463       [&](const DiagnoseIfAttr *DIA) {
6464         bool Result;
6465         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6466                Result;
6467       });
6468 }
6469 
6470 /// Add all of the function declarations in the given function set to
6471 /// the overload candidate set.
6472 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6473                                  ArrayRef<Expr *> Args,
6474                                  OverloadCandidateSet &CandidateSet,
6475                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6476                                  bool SuppressUserConversions,
6477                                  bool PartialOverloading,
6478                                  bool FirstArgumentIsBase) {
6479   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6480     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6481     ArrayRef<Expr *> FunctionArgs = Args;
6482 
6483     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6484     FunctionDecl *FD =
6485         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6486 
6487     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6488       QualType ObjectType;
6489       Expr::Classification ObjectClassification;
6490       if (Args.size() > 0) {
6491         if (Expr *E = Args[0]) {
6492           // Use the explicit base to restrict the lookup:
6493           ObjectType = E->getType();
6494           // Pointers in the object arguments are implicitly dereferenced, so we
6495           // always classify them as l-values.
6496           if (!ObjectType.isNull() && ObjectType->isPointerType())
6497             ObjectClassification = Expr::Classification::makeSimpleLValue();
6498           else
6499             ObjectClassification = E->Classify(Context);
6500         } // .. else there is an implicit base.
6501         FunctionArgs = Args.slice(1);
6502       }
6503       if (FunTmpl) {
6504         AddMethodTemplateCandidate(
6505             FunTmpl, F.getPair(),
6506             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6507             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6508             FunctionArgs, CandidateSet, SuppressUserConversions,
6509             PartialOverloading);
6510       } else {
6511         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6512                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6513                            ObjectClassification, FunctionArgs, CandidateSet,
6514                            SuppressUserConversions, PartialOverloading);
6515       }
6516     } else {
6517       // This branch handles both standalone functions and static methods.
6518 
6519       // Slice the first argument (which is the base) when we access
6520       // static method as non-static.
6521       if (Args.size() > 0 &&
6522           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6523                         !isa<CXXConstructorDecl>(FD)))) {
6524         assert(cast<CXXMethodDecl>(FD)->isStatic());
6525         FunctionArgs = Args.slice(1);
6526       }
6527       if (FunTmpl) {
6528         AddTemplateOverloadCandidate(
6529             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6530             CandidateSet, SuppressUserConversions, PartialOverloading);
6531       } else {
6532         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6533                              SuppressUserConversions, PartialOverloading);
6534       }
6535     }
6536   }
6537 }
6538 
6539 /// AddMethodCandidate - Adds a named decl (which is some kind of
6540 /// method) as a method candidate to the given overload set.
6541 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6542                               QualType ObjectType,
6543                               Expr::Classification ObjectClassification,
6544                               ArrayRef<Expr *> Args,
6545                               OverloadCandidateSet& CandidateSet,
6546                               bool SuppressUserConversions) {
6547   NamedDecl *Decl = FoundDecl.getDecl();
6548   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6549 
6550   if (isa<UsingShadowDecl>(Decl))
6551     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6552 
6553   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6554     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6555            "Expected a member function template");
6556     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6557                                /*ExplicitArgs*/ nullptr, ObjectType,
6558                                ObjectClassification, Args, CandidateSet,
6559                                SuppressUserConversions);
6560   } else {
6561     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6562                        ObjectType, ObjectClassification, Args, CandidateSet,
6563                        SuppressUserConversions);
6564   }
6565 }
6566 
6567 /// AddMethodCandidate - Adds the given C++ member function to the set
6568 /// of candidate functions, using the given function call arguments
6569 /// and the object argument (@c Object). For example, in a call
6570 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6571 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6572 /// allow user-defined conversions via constructors or conversion
6573 /// operators.
6574 void
6575 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6576                          CXXRecordDecl *ActingContext, QualType ObjectType,
6577                          Expr::Classification ObjectClassification,
6578                          ArrayRef<Expr *> Args,
6579                          OverloadCandidateSet &CandidateSet,
6580                          bool SuppressUserConversions,
6581                          bool PartialOverloading,
6582                          ConversionSequenceList EarlyConversions) {
6583   const FunctionProtoType *Proto
6584     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6585   assert(Proto && "Methods without a prototype cannot be overloaded");
6586   assert(!isa<CXXConstructorDecl>(Method) &&
6587          "Use AddOverloadCandidate for constructors");
6588 
6589   if (!CandidateSet.isNewCandidate(Method))
6590     return;
6591 
6592   // C++11 [class.copy]p23: [DR1402]
6593   //   A defaulted move assignment operator that is defined as deleted is
6594   //   ignored by overload resolution.
6595   if (Method->isDefaulted() && Method->isDeleted() &&
6596       Method->isMoveAssignmentOperator())
6597     return;
6598 
6599   // Overload resolution is always an unevaluated context.
6600   EnterExpressionEvaluationContext Unevaluated(
6601       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6602 
6603   // Add this candidate
6604   OverloadCandidate &Candidate =
6605       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6606   Candidate.FoundDecl = FoundDecl;
6607   Candidate.Function = Method;
6608   Candidate.IsSurrogate = false;
6609   Candidate.IgnoreObjectArgument = false;
6610   Candidate.ExplicitCallArguments = Args.size();
6611 
6612   unsigned NumParams = Proto->getNumParams();
6613 
6614   // (C++ 13.3.2p2): A candidate function having fewer than m
6615   // parameters is viable only if it has an ellipsis in its parameter
6616   // list (8.3.5).
6617   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6618       !Proto->isVariadic()) {
6619     Candidate.Viable = false;
6620     Candidate.FailureKind = ovl_fail_too_many_arguments;
6621     return;
6622   }
6623 
6624   // (C++ 13.3.2p2): A candidate function having more than m parameters
6625   // is viable only if the (m+1)st parameter has a default argument
6626   // (8.3.6). For the purposes of overload resolution, the
6627   // parameter list is truncated on the right, so that there are
6628   // exactly m parameters.
6629   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6630   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6631     // Not enough arguments.
6632     Candidate.Viable = false;
6633     Candidate.FailureKind = ovl_fail_too_few_arguments;
6634     return;
6635   }
6636 
6637   Candidate.Viable = true;
6638 
6639   if (Method->isStatic() || ObjectType.isNull())
6640     // The implicit object argument is ignored.
6641     Candidate.IgnoreObjectArgument = true;
6642   else {
6643     // Determine the implicit conversion sequence for the object
6644     // parameter.
6645     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6646         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6647         Method, ActingContext);
6648     if (Candidate.Conversions[0].isBad()) {
6649       Candidate.Viable = false;
6650       Candidate.FailureKind = ovl_fail_bad_conversion;
6651       return;
6652     }
6653   }
6654 
6655   // (CUDA B.1): Check for invalid calls between targets.
6656   if (getLangOpts().CUDA)
6657     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6658       if (!IsAllowedCUDACall(Caller, Method)) {
6659         Candidate.Viable = false;
6660         Candidate.FailureKind = ovl_fail_bad_target;
6661         return;
6662       }
6663 
6664   // Determine the implicit conversion sequences for each of the
6665   // arguments.
6666   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6667     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6668       // We already formed a conversion sequence for this parameter during
6669       // template argument deduction.
6670     } else if (ArgIdx < NumParams) {
6671       // (C++ 13.3.2p3): for F to be a viable function, there shall
6672       // exist for each argument an implicit conversion sequence
6673       // (13.3.3.1) that converts that argument to the corresponding
6674       // parameter of F.
6675       QualType ParamType = Proto->getParamType(ArgIdx);
6676       Candidate.Conversions[ArgIdx + 1]
6677         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6678                                 SuppressUserConversions,
6679                                 /*InOverloadResolution=*/true,
6680                                 /*AllowObjCWritebackConversion=*/
6681                                   getLangOpts().ObjCAutoRefCount);
6682       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6683         Candidate.Viable = false;
6684         Candidate.FailureKind = ovl_fail_bad_conversion;
6685         return;
6686       }
6687     } else {
6688       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6689       // argument for which there is no corresponding parameter is
6690       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6691       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6692     }
6693   }
6694 
6695   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6696     Candidate.Viable = false;
6697     Candidate.FailureKind = ovl_fail_enable_if;
6698     Candidate.DeductionFailure.Data = FailedAttr;
6699     return;
6700   }
6701 
6702   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6703       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6704     Candidate.Viable = false;
6705     Candidate.FailureKind = ovl_non_default_multiversion_function;
6706   }
6707 }
6708 
6709 /// Add a C++ member function template as a candidate to the candidate
6710 /// set, using template argument deduction to produce an appropriate member
6711 /// function template specialization.
6712 void
6713 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6714                                  DeclAccessPair FoundDecl,
6715                                  CXXRecordDecl *ActingContext,
6716                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6717                                  QualType ObjectType,
6718                                  Expr::Classification ObjectClassification,
6719                                  ArrayRef<Expr *> Args,
6720                                  OverloadCandidateSet& CandidateSet,
6721                                  bool SuppressUserConversions,
6722                                  bool PartialOverloading) {
6723   if (!CandidateSet.isNewCandidate(MethodTmpl))
6724     return;
6725 
6726   // C++ [over.match.funcs]p7:
6727   //   In each case where a candidate is a function template, candidate
6728   //   function template specializations are generated using template argument
6729   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6730   //   candidate functions in the usual way.113) A given name can refer to one
6731   //   or more function templates and also to a set of overloaded non-template
6732   //   functions. In such a case, the candidate functions generated from each
6733   //   function template are combined with the set of non-template candidate
6734   //   functions.
6735   TemplateDeductionInfo Info(CandidateSet.getLocation());
6736   FunctionDecl *Specialization = nullptr;
6737   ConversionSequenceList Conversions;
6738   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6739           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6740           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6741             return CheckNonDependentConversions(
6742                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6743                 SuppressUserConversions, ActingContext, ObjectType,
6744                 ObjectClassification);
6745           })) {
6746     OverloadCandidate &Candidate =
6747         CandidateSet.addCandidate(Conversions.size(), Conversions);
6748     Candidate.FoundDecl = FoundDecl;
6749     Candidate.Function = MethodTmpl->getTemplatedDecl();
6750     Candidate.Viable = false;
6751     Candidate.IsSurrogate = false;
6752     Candidate.IgnoreObjectArgument =
6753         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6754         ObjectType.isNull();
6755     Candidate.ExplicitCallArguments = Args.size();
6756     if (Result == TDK_NonDependentConversionFailure)
6757       Candidate.FailureKind = ovl_fail_bad_conversion;
6758     else {
6759       Candidate.FailureKind = ovl_fail_bad_deduction;
6760       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6761                                                             Info);
6762     }
6763     return;
6764   }
6765 
6766   // Add the function template specialization produced by template argument
6767   // deduction as a candidate.
6768   assert(Specialization && "Missing member function template specialization?");
6769   assert(isa<CXXMethodDecl>(Specialization) &&
6770          "Specialization is not a member function?");
6771   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6772                      ActingContext, ObjectType, ObjectClassification, Args,
6773                      CandidateSet, SuppressUserConversions, PartialOverloading,
6774                      Conversions);
6775 }
6776 
6777 /// Add a C++ function template specialization as a candidate
6778 /// in the candidate set, using template argument deduction to produce
6779 /// an appropriate function template specialization.
6780 void Sema::AddTemplateOverloadCandidate(
6781     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6782     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6783     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6784     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) {
6785   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6786     return;
6787 
6788   // C++ [over.match.funcs]p7:
6789   //   In each case where a candidate is a function template, candidate
6790   //   function template specializations are generated using template argument
6791   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6792   //   candidate functions in the usual way.113) A given name can refer to one
6793   //   or more function templates and also to a set of overloaded non-template
6794   //   functions. In such a case, the candidate functions generated from each
6795   //   function template are combined with the set of non-template candidate
6796   //   functions.
6797   TemplateDeductionInfo Info(CandidateSet.getLocation());
6798   FunctionDecl *Specialization = nullptr;
6799   ConversionSequenceList Conversions;
6800   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6801           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6802           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6803             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6804                                                 Args, CandidateSet, Conversions,
6805                                                 SuppressUserConversions);
6806           })) {
6807     OverloadCandidate &Candidate =
6808         CandidateSet.addCandidate(Conversions.size(), Conversions);
6809     Candidate.FoundDecl = FoundDecl;
6810     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6811     Candidate.Viable = false;
6812     Candidate.IsSurrogate = false;
6813     Candidate.IsADLCandidate = IsADLCandidate;
6814     // Ignore the object argument if there is one, since we don't have an object
6815     // type.
6816     Candidate.IgnoreObjectArgument =
6817         isa<CXXMethodDecl>(Candidate.Function) &&
6818         !isa<CXXConstructorDecl>(Candidate.Function);
6819     Candidate.ExplicitCallArguments = Args.size();
6820     if (Result == TDK_NonDependentConversionFailure)
6821       Candidate.FailureKind = ovl_fail_bad_conversion;
6822     else {
6823       Candidate.FailureKind = ovl_fail_bad_deduction;
6824       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6825                                                             Info);
6826     }
6827     return;
6828   }
6829 
6830   // Add the function template specialization produced by template argument
6831   // deduction as a candidate.
6832   assert(Specialization && "Missing function template specialization?");
6833   AddOverloadCandidate(
6834       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6835       PartialOverloading, AllowExplicit,
6836       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions);
6837 }
6838 
6839 /// Check that implicit conversion sequences can be formed for each argument
6840 /// whose corresponding parameter has a non-dependent type, per DR1391's
6841 /// [temp.deduct.call]p10.
6842 bool Sema::CheckNonDependentConversions(
6843     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6844     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6845     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6846     CXXRecordDecl *ActingContext, QualType ObjectType,
6847     Expr::Classification ObjectClassification) {
6848   // FIXME: The cases in which we allow explicit conversions for constructor
6849   // arguments never consider calling a constructor template. It's not clear
6850   // that is correct.
6851   const bool AllowExplicit = false;
6852 
6853   auto *FD = FunctionTemplate->getTemplatedDecl();
6854   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6855   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6856   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6857 
6858   Conversions =
6859       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6860 
6861   // Overload resolution is always an unevaluated context.
6862   EnterExpressionEvaluationContext Unevaluated(
6863       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6864 
6865   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6866   // require that, but this check should never result in a hard error, and
6867   // overload resolution is permitted to sidestep instantiations.
6868   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6869       !ObjectType.isNull()) {
6870     Conversions[0] = TryObjectArgumentInitialization(
6871         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6872         Method, ActingContext);
6873     if (Conversions[0].isBad())
6874       return true;
6875   }
6876 
6877   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6878        ++I) {
6879     QualType ParamType = ParamTypes[I];
6880     if (!ParamType->isDependentType()) {
6881       Conversions[ThisConversions + I]
6882         = TryCopyInitialization(*this, Args[I], ParamType,
6883                                 SuppressUserConversions,
6884                                 /*InOverloadResolution=*/true,
6885                                 /*AllowObjCWritebackConversion=*/
6886                                   getLangOpts().ObjCAutoRefCount,
6887                                 AllowExplicit);
6888       if (Conversions[ThisConversions + I].isBad())
6889         return true;
6890     }
6891   }
6892 
6893   return false;
6894 }
6895 
6896 /// Determine whether this is an allowable conversion from the result
6897 /// of an explicit conversion operator to the expected type, per C++
6898 /// [over.match.conv]p1 and [over.match.ref]p1.
6899 ///
6900 /// \param ConvType The return type of the conversion function.
6901 ///
6902 /// \param ToType The type we are converting to.
6903 ///
6904 /// \param AllowObjCPointerConversion Allow a conversion from one
6905 /// Objective-C pointer to another.
6906 ///
6907 /// \returns true if the conversion is allowable, false otherwise.
6908 static bool isAllowableExplicitConversion(Sema &S,
6909                                           QualType ConvType, QualType ToType,
6910                                           bool AllowObjCPointerConversion) {
6911   QualType ToNonRefType = ToType.getNonReferenceType();
6912 
6913   // Easy case: the types are the same.
6914   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6915     return true;
6916 
6917   // Allow qualification conversions.
6918   bool ObjCLifetimeConversion;
6919   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6920                                   ObjCLifetimeConversion))
6921     return true;
6922 
6923   // If we're not allowed to consider Objective-C pointer conversions,
6924   // we're done.
6925   if (!AllowObjCPointerConversion)
6926     return false;
6927 
6928   // Is this an Objective-C pointer conversion?
6929   bool IncompatibleObjC = false;
6930   QualType ConvertedType;
6931   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6932                                    IncompatibleObjC);
6933 }
6934 
6935 /// AddConversionCandidate - Add a C++ conversion function as a
6936 /// candidate in the candidate set (C++ [over.match.conv],
6937 /// C++ [over.match.copy]). From is the expression we're converting from,
6938 /// and ToType is the type that we're eventually trying to convert to
6939 /// (which may or may not be the same type as the type that the
6940 /// conversion function produces).
6941 void Sema::AddConversionCandidate(
6942     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
6943     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
6944     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
6945     bool AllowExplicit, bool AllowResultConversion) {
6946   assert(!Conversion->getDescribedFunctionTemplate() &&
6947          "Conversion function templates use AddTemplateConversionCandidate");
6948   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6949   if (!CandidateSet.isNewCandidate(Conversion))
6950     return;
6951 
6952   // If the conversion function has an undeduced return type, trigger its
6953   // deduction now.
6954   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6955     if (DeduceReturnType(Conversion, From->getExprLoc()))
6956       return;
6957     ConvType = Conversion->getConversionType().getNonReferenceType();
6958   }
6959 
6960   // If we don't allow any conversion of the result type, ignore conversion
6961   // functions that don't convert to exactly (possibly cv-qualified) T.
6962   if (!AllowResultConversion &&
6963       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6964     return;
6965 
6966   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6967   // operator is only a candidate if its return type is the target type or
6968   // can be converted to the target type with a qualification conversion.
6969   if (Conversion->isExplicit() &&
6970       !isAllowableExplicitConversion(*this, ConvType, ToType,
6971                                      AllowObjCConversionOnExplicit))
6972     return;
6973 
6974   // Overload resolution is always an unevaluated context.
6975   EnterExpressionEvaluationContext Unevaluated(
6976       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6977 
6978   // Add this candidate
6979   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6980   Candidate.FoundDecl = FoundDecl;
6981   Candidate.Function = Conversion;
6982   Candidate.IsSurrogate = false;
6983   Candidate.IgnoreObjectArgument = false;
6984   Candidate.FinalConversion.setAsIdentityConversion();
6985   Candidate.FinalConversion.setFromType(ConvType);
6986   Candidate.FinalConversion.setAllToTypes(ToType);
6987   Candidate.Viable = true;
6988   Candidate.ExplicitCallArguments = 1;
6989 
6990   // C++ [over.match.funcs]p4:
6991   //   For conversion functions, the function is considered to be a member of
6992   //   the class of the implicit implied object argument for the purpose of
6993   //   defining the type of the implicit object parameter.
6994   //
6995   // Determine the implicit conversion sequence for the implicit
6996   // object parameter.
6997   QualType ImplicitParamType = From->getType();
6998   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6999     ImplicitParamType = FromPtrType->getPointeeType();
7000   CXXRecordDecl *ConversionContext
7001     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
7002 
7003   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7004       *this, CandidateSet.getLocation(), From->getType(),
7005       From->Classify(Context), Conversion, ConversionContext);
7006 
7007   if (Candidate.Conversions[0].isBad()) {
7008     Candidate.Viable = false;
7009     Candidate.FailureKind = ovl_fail_bad_conversion;
7010     return;
7011   }
7012 
7013   // We won't go through a user-defined type conversion function to convert a
7014   // derived to base as such conversions are given Conversion Rank. They only
7015   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7016   QualType FromCanon
7017     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7018   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7019   if (FromCanon == ToCanon ||
7020       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7021     Candidate.Viable = false;
7022     Candidate.FailureKind = ovl_fail_trivial_conversion;
7023     return;
7024   }
7025 
7026   // To determine what the conversion from the result of calling the
7027   // conversion function to the type we're eventually trying to
7028   // convert to (ToType), we need to synthesize a call to the
7029   // conversion function and attempt copy initialization from it. This
7030   // makes sure that we get the right semantics with respect to
7031   // lvalues/rvalues and the type. Fortunately, we can allocate this
7032   // call on the stack and we don't need its arguments to be
7033   // well-formed.
7034   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7035                             VK_LValue, From->getBeginLoc());
7036   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7037                                 Context.getPointerType(Conversion->getType()),
7038                                 CK_FunctionToPointerDecay,
7039                                 &ConversionRef, VK_RValue);
7040 
7041   QualType ConversionType = Conversion->getConversionType();
7042   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7043     Candidate.Viable = false;
7044     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7045     return;
7046   }
7047 
7048   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7049 
7050   // Note that it is safe to allocate CallExpr on the stack here because
7051   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7052   // allocator).
7053   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7054 
7055   llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7056       Buffer;
7057   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7058       Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7059 
7060   ImplicitConversionSequence ICS =
7061       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7062                             /*SuppressUserConversions=*/true,
7063                             /*InOverloadResolution=*/false,
7064                             /*AllowObjCWritebackConversion=*/false);
7065 
7066   switch (ICS.getKind()) {
7067   case ImplicitConversionSequence::StandardConversion:
7068     Candidate.FinalConversion = ICS.Standard;
7069 
7070     // C++ [over.ics.user]p3:
7071     //   If the user-defined conversion is specified by a specialization of a
7072     //   conversion function template, the second standard conversion sequence
7073     //   shall have exact match rank.
7074     if (Conversion->getPrimaryTemplate() &&
7075         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7076       Candidate.Viable = false;
7077       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7078       return;
7079     }
7080 
7081     // C++0x [dcl.init.ref]p5:
7082     //    In the second case, if the reference is an rvalue reference and
7083     //    the second standard conversion sequence of the user-defined
7084     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7085     //    program is ill-formed.
7086     if (ToType->isRValueReferenceType() &&
7087         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7088       Candidate.Viable = false;
7089       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7090       return;
7091     }
7092     break;
7093 
7094   case ImplicitConversionSequence::BadConversion:
7095     Candidate.Viable = false;
7096     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7097     return;
7098 
7099   default:
7100     llvm_unreachable(
7101            "Can only end up with a standard conversion sequence or failure");
7102   }
7103 
7104   if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7105                             ExplicitSpecKind::ResolvedFalse) {
7106     Candidate.Viable = false;
7107     Candidate.FailureKind = ovl_fail_explicit_resolved;
7108     return;
7109   }
7110 
7111   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7112     Candidate.Viable = false;
7113     Candidate.FailureKind = ovl_fail_enable_if;
7114     Candidate.DeductionFailure.Data = FailedAttr;
7115     return;
7116   }
7117 
7118   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7119       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7120     Candidate.Viable = false;
7121     Candidate.FailureKind = ovl_non_default_multiversion_function;
7122   }
7123 }
7124 
7125 /// Adds a conversion function template specialization
7126 /// candidate to the overload set, using template argument deduction
7127 /// to deduce the template arguments of the conversion function
7128 /// template from the type that we are converting to (C++
7129 /// [temp.deduct.conv]).
7130 void Sema::AddTemplateConversionCandidate(
7131     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7132     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7133     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7134     bool AllowExplicit, bool AllowResultConversion) {
7135   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7136          "Only conversion function templates permitted here");
7137 
7138   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7139     return;
7140 
7141   TemplateDeductionInfo Info(CandidateSet.getLocation());
7142   CXXConversionDecl *Specialization = nullptr;
7143   if (TemplateDeductionResult Result
7144         = DeduceTemplateArguments(FunctionTemplate, ToType,
7145                                   Specialization, Info)) {
7146     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7147     Candidate.FoundDecl = FoundDecl;
7148     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7149     Candidate.Viable = false;
7150     Candidate.FailureKind = ovl_fail_bad_deduction;
7151     Candidate.IsSurrogate = false;
7152     Candidate.IgnoreObjectArgument = false;
7153     Candidate.ExplicitCallArguments = 1;
7154     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7155                                                           Info);
7156     return;
7157   }
7158 
7159   // Add the conversion function template specialization produced by
7160   // template argument deduction as a candidate.
7161   assert(Specialization && "Missing function template specialization?");
7162   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7163                          CandidateSet, AllowObjCConversionOnExplicit,
7164                          AllowExplicit, AllowResultConversion);
7165 }
7166 
7167 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7168 /// converts the given @c Object to a function pointer via the
7169 /// conversion function @c Conversion, and then attempts to call it
7170 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7171 /// the type of function that we'll eventually be calling.
7172 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7173                                  DeclAccessPair FoundDecl,
7174                                  CXXRecordDecl *ActingContext,
7175                                  const FunctionProtoType *Proto,
7176                                  Expr *Object,
7177                                  ArrayRef<Expr *> Args,
7178                                  OverloadCandidateSet& CandidateSet) {
7179   if (!CandidateSet.isNewCandidate(Conversion))
7180     return;
7181 
7182   // Overload resolution is always an unevaluated context.
7183   EnterExpressionEvaluationContext Unevaluated(
7184       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7185 
7186   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7187   Candidate.FoundDecl = FoundDecl;
7188   Candidate.Function = nullptr;
7189   Candidate.Surrogate = Conversion;
7190   Candidate.Viable = true;
7191   Candidate.IsSurrogate = true;
7192   Candidate.IgnoreObjectArgument = false;
7193   Candidate.ExplicitCallArguments = Args.size();
7194 
7195   // Determine the implicit conversion sequence for the implicit
7196   // object parameter.
7197   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7198       *this, CandidateSet.getLocation(), Object->getType(),
7199       Object->Classify(Context), Conversion, ActingContext);
7200   if (ObjectInit.isBad()) {
7201     Candidate.Viable = false;
7202     Candidate.FailureKind = ovl_fail_bad_conversion;
7203     Candidate.Conversions[0] = ObjectInit;
7204     return;
7205   }
7206 
7207   // The first conversion is actually a user-defined conversion whose
7208   // first conversion is ObjectInit's standard conversion (which is
7209   // effectively a reference binding). Record it as such.
7210   Candidate.Conversions[0].setUserDefined();
7211   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7212   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7213   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7214   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7215   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7216   Candidate.Conversions[0].UserDefined.After
7217     = Candidate.Conversions[0].UserDefined.Before;
7218   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7219 
7220   // Find the
7221   unsigned NumParams = Proto->getNumParams();
7222 
7223   // (C++ 13.3.2p2): A candidate function having fewer than m
7224   // parameters is viable only if it has an ellipsis in its parameter
7225   // list (8.3.5).
7226   if (Args.size() > NumParams && !Proto->isVariadic()) {
7227     Candidate.Viable = false;
7228     Candidate.FailureKind = ovl_fail_too_many_arguments;
7229     return;
7230   }
7231 
7232   // Function types don't have any default arguments, so just check if
7233   // we have enough arguments.
7234   if (Args.size() < NumParams) {
7235     // Not enough arguments.
7236     Candidate.Viable = false;
7237     Candidate.FailureKind = ovl_fail_too_few_arguments;
7238     return;
7239   }
7240 
7241   // Determine the implicit conversion sequences for each of the
7242   // arguments.
7243   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7244     if (ArgIdx < NumParams) {
7245       // (C++ 13.3.2p3): for F to be a viable function, there shall
7246       // exist for each argument an implicit conversion sequence
7247       // (13.3.3.1) that converts that argument to the corresponding
7248       // parameter of F.
7249       QualType ParamType = Proto->getParamType(ArgIdx);
7250       Candidate.Conversions[ArgIdx + 1]
7251         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7252                                 /*SuppressUserConversions=*/false,
7253                                 /*InOverloadResolution=*/false,
7254                                 /*AllowObjCWritebackConversion=*/
7255                                   getLangOpts().ObjCAutoRefCount);
7256       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7257         Candidate.Viable = false;
7258         Candidate.FailureKind = ovl_fail_bad_conversion;
7259         return;
7260       }
7261     } else {
7262       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7263       // argument for which there is no corresponding parameter is
7264       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7265       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7266     }
7267   }
7268 
7269   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7270     Candidate.Viable = false;
7271     Candidate.FailureKind = ovl_fail_enable_if;
7272     Candidate.DeductionFailure.Data = FailedAttr;
7273     return;
7274   }
7275 }
7276 
7277 /// Add overload candidates for overloaded operators that are
7278 /// member functions.
7279 ///
7280 /// Add the overloaded operator candidates that are member functions
7281 /// for the operator Op that was used in an operator expression such
7282 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7283 /// CandidateSet will store the added overload candidates. (C++
7284 /// [over.match.oper]).
7285 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7286                                        SourceLocation OpLoc,
7287                                        ArrayRef<Expr *> Args,
7288                                        OverloadCandidateSet& CandidateSet,
7289                                        SourceRange OpRange) {
7290   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7291 
7292   // C++ [over.match.oper]p3:
7293   //   For a unary operator @ with an operand of a type whose
7294   //   cv-unqualified version is T1, and for a binary operator @ with
7295   //   a left operand of a type whose cv-unqualified version is T1 and
7296   //   a right operand of a type whose cv-unqualified version is T2,
7297   //   three sets of candidate functions, designated member
7298   //   candidates, non-member candidates and built-in candidates, are
7299   //   constructed as follows:
7300   QualType T1 = Args[0]->getType();
7301 
7302   //     -- If T1 is a complete class type or a class currently being
7303   //        defined, the set of member candidates is the result of the
7304   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7305   //        the set of member candidates is empty.
7306   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7307     // Complete the type if it can be completed.
7308     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7309       return;
7310     // If the type is neither complete nor being defined, bail out now.
7311     if (!T1Rec->getDecl()->getDefinition())
7312       return;
7313 
7314     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7315     LookupQualifiedName(Operators, T1Rec->getDecl());
7316     Operators.suppressDiagnostics();
7317 
7318     for (LookupResult::iterator Oper = Operators.begin(),
7319                              OperEnd = Operators.end();
7320          Oper != OperEnd;
7321          ++Oper)
7322       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7323                          Args[0]->Classify(Context), Args.slice(1),
7324                          CandidateSet, /*SuppressUserConversion=*/false);
7325   }
7326 }
7327 
7328 /// AddBuiltinCandidate - Add a candidate for a built-in
7329 /// operator. ResultTy and ParamTys are the result and parameter types
7330 /// of the built-in candidate, respectively. Args and NumArgs are the
7331 /// arguments being passed to the candidate. IsAssignmentOperator
7332 /// should be true when this built-in candidate is an assignment
7333 /// operator. NumContextualBoolArguments is the number of arguments
7334 /// (at the beginning of the argument list) that will be contextually
7335 /// converted to bool.
7336 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7337                                OverloadCandidateSet& CandidateSet,
7338                                bool IsAssignmentOperator,
7339                                unsigned NumContextualBoolArguments) {
7340   // Overload resolution is always an unevaluated context.
7341   EnterExpressionEvaluationContext Unevaluated(
7342       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7343 
7344   // Add this candidate
7345   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7346   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7347   Candidate.Function = nullptr;
7348   Candidate.IsSurrogate = false;
7349   Candidate.IgnoreObjectArgument = false;
7350   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7351 
7352   // Determine the implicit conversion sequences for each of the
7353   // arguments.
7354   Candidate.Viable = true;
7355   Candidate.ExplicitCallArguments = Args.size();
7356   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7357     // C++ [over.match.oper]p4:
7358     //   For the built-in assignment operators, conversions of the
7359     //   left operand are restricted as follows:
7360     //     -- no temporaries are introduced to hold the left operand, and
7361     //     -- no user-defined conversions are applied to the left
7362     //        operand to achieve a type match with the left-most
7363     //        parameter of a built-in candidate.
7364     //
7365     // We block these conversions by turning off user-defined
7366     // conversions, since that is the only way that initialization of
7367     // a reference to a non-class type can occur from something that
7368     // is not of the same type.
7369     if (ArgIdx < NumContextualBoolArguments) {
7370       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7371              "Contextual conversion to bool requires bool type");
7372       Candidate.Conversions[ArgIdx]
7373         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7374     } else {
7375       Candidate.Conversions[ArgIdx]
7376         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7377                                 ArgIdx == 0 && IsAssignmentOperator,
7378                                 /*InOverloadResolution=*/false,
7379                                 /*AllowObjCWritebackConversion=*/
7380                                   getLangOpts().ObjCAutoRefCount);
7381     }
7382     if (Candidate.Conversions[ArgIdx].isBad()) {
7383       Candidate.Viable = false;
7384       Candidate.FailureKind = ovl_fail_bad_conversion;
7385       break;
7386     }
7387   }
7388 }
7389 
7390 namespace {
7391 
7392 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7393 /// candidate operator functions for built-in operators (C++
7394 /// [over.built]). The types are separated into pointer types and
7395 /// enumeration types.
7396 class BuiltinCandidateTypeSet  {
7397   /// TypeSet - A set of types.
7398   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7399                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7400 
7401   /// PointerTypes - The set of pointer types that will be used in the
7402   /// built-in candidates.
7403   TypeSet PointerTypes;
7404 
7405   /// MemberPointerTypes - The set of member pointer types that will be
7406   /// used in the built-in candidates.
7407   TypeSet MemberPointerTypes;
7408 
7409   /// EnumerationTypes - The set of enumeration types that will be
7410   /// used in the built-in candidates.
7411   TypeSet EnumerationTypes;
7412 
7413   /// The set of vector types that will be used in the built-in
7414   /// candidates.
7415   TypeSet VectorTypes;
7416 
7417   /// A flag indicating non-record types are viable candidates
7418   bool HasNonRecordTypes;
7419 
7420   /// A flag indicating whether either arithmetic or enumeration types
7421   /// were present in the candidate set.
7422   bool HasArithmeticOrEnumeralTypes;
7423 
7424   /// A flag indicating whether the nullptr type was present in the
7425   /// candidate set.
7426   bool HasNullPtrType;
7427 
7428   /// Sema - The semantic analysis instance where we are building the
7429   /// candidate type set.
7430   Sema &SemaRef;
7431 
7432   /// Context - The AST context in which we will build the type sets.
7433   ASTContext &Context;
7434 
7435   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7436                                                const Qualifiers &VisibleQuals);
7437   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7438 
7439 public:
7440   /// iterator - Iterates through the types that are part of the set.
7441   typedef TypeSet::iterator iterator;
7442 
7443   BuiltinCandidateTypeSet(Sema &SemaRef)
7444     : HasNonRecordTypes(false),
7445       HasArithmeticOrEnumeralTypes(false),
7446       HasNullPtrType(false),
7447       SemaRef(SemaRef),
7448       Context(SemaRef.Context) { }
7449 
7450   void AddTypesConvertedFrom(QualType Ty,
7451                              SourceLocation Loc,
7452                              bool AllowUserConversions,
7453                              bool AllowExplicitConversions,
7454                              const Qualifiers &VisibleTypeConversionsQuals);
7455 
7456   /// pointer_begin - First pointer type found;
7457   iterator pointer_begin() { return PointerTypes.begin(); }
7458 
7459   /// pointer_end - Past the last pointer type found;
7460   iterator pointer_end() { return PointerTypes.end(); }
7461 
7462   /// member_pointer_begin - First member pointer type found;
7463   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7464 
7465   /// member_pointer_end - Past the last member pointer type found;
7466   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7467 
7468   /// enumeration_begin - First enumeration type found;
7469   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7470 
7471   /// enumeration_end - Past the last enumeration type found;
7472   iterator enumeration_end() { return EnumerationTypes.end(); }
7473 
7474   iterator vector_begin() { return VectorTypes.begin(); }
7475   iterator vector_end() { return VectorTypes.end(); }
7476 
7477   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7478   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7479   bool hasNullPtrType() const { return HasNullPtrType; }
7480 };
7481 
7482 } // end anonymous namespace
7483 
7484 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7485 /// the set of pointer types along with any more-qualified variants of
7486 /// that type. For example, if @p Ty is "int const *", this routine
7487 /// will add "int const *", "int const volatile *", "int const
7488 /// restrict *", and "int const volatile restrict *" to the set of
7489 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7490 /// false otherwise.
7491 ///
7492 /// FIXME: what to do about extended qualifiers?
7493 bool
7494 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7495                                              const Qualifiers &VisibleQuals) {
7496 
7497   // Insert this type.
7498   if (!PointerTypes.insert(Ty))
7499     return false;
7500 
7501   QualType PointeeTy;
7502   const PointerType *PointerTy = Ty->getAs<PointerType>();
7503   bool buildObjCPtr = false;
7504   if (!PointerTy) {
7505     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7506     PointeeTy = PTy->getPointeeType();
7507     buildObjCPtr = true;
7508   } else {
7509     PointeeTy = PointerTy->getPointeeType();
7510   }
7511 
7512   // Don't add qualified variants of arrays. For one, they're not allowed
7513   // (the qualifier would sink to the element type), and for another, the
7514   // only overload situation where it matters is subscript or pointer +- int,
7515   // and those shouldn't have qualifier variants anyway.
7516   if (PointeeTy->isArrayType())
7517     return true;
7518 
7519   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7520   bool hasVolatile = VisibleQuals.hasVolatile();
7521   bool hasRestrict = VisibleQuals.hasRestrict();
7522 
7523   // Iterate through all strict supersets of BaseCVR.
7524   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7525     if ((CVR | BaseCVR) != CVR) continue;
7526     // Skip over volatile if no volatile found anywhere in the types.
7527     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7528 
7529     // Skip over restrict if no restrict found anywhere in the types, or if
7530     // the type cannot be restrict-qualified.
7531     if ((CVR & Qualifiers::Restrict) &&
7532         (!hasRestrict ||
7533          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7534       continue;
7535 
7536     // Build qualified pointee type.
7537     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7538 
7539     // Build qualified pointer type.
7540     QualType QPointerTy;
7541     if (!buildObjCPtr)
7542       QPointerTy = Context.getPointerType(QPointeeTy);
7543     else
7544       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7545 
7546     // Insert qualified pointer type.
7547     PointerTypes.insert(QPointerTy);
7548   }
7549 
7550   return true;
7551 }
7552 
7553 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7554 /// to the set of pointer types along with any more-qualified variants of
7555 /// that type. For example, if @p Ty is "int const *", this routine
7556 /// will add "int const *", "int const volatile *", "int const
7557 /// restrict *", and "int const volatile restrict *" to the set of
7558 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7559 /// false otherwise.
7560 ///
7561 /// FIXME: what to do about extended qualifiers?
7562 bool
7563 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7564     QualType Ty) {
7565   // Insert this type.
7566   if (!MemberPointerTypes.insert(Ty))
7567     return false;
7568 
7569   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7570   assert(PointerTy && "type was not a member pointer type!");
7571 
7572   QualType PointeeTy = PointerTy->getPointeeType();
7573   // Don't add qualified variants of arrays. For one, they're not allowed
7574   // (the qualifier would sink to the element type), and for another, the
7575   // only overload situation where it matters is subscript or pointer +- int,
7576   // and those shouldn't have qualifier variants anyway.
7577   if (PointeeTy->isArrayType())
7578     return true;
7579   const Type *ClassTy = PointerTy->getClass();
7580 
7581   // Iterate through all strict supersets of the pointee type's CVR
7582   // qualifiers.
7583   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7584   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7585     if ((CVR | BaseCVR) != CVR) continue;
7586 
7587     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7588     MemberPointerTypes.insert(
7589       Context.getMemberPointerType(QPointeeTy, ClassTy));
7590   }
7591 
7592   return true;
7593 }
7594 
7595 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7596 /// Ty can be implicit converted to the given set of @p Types. We're
7597 /// primarily interested in pointer types and enumeration types. We also
7598 /// take member pointer types, for the conditional operator.
7599 /// AllowUserConversions is true if we should look at the conversion
7600 /// functions of a class type, and AllowExplicitConversions if we
7601 /// should also include the explicit conversion functions of a class
7602 /// type.
7603 void
7604 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7605                                                SourceLocation Loc,
7606                                                bool AllowUserConversions,
7607                                                bool AllowExplicitConversions,
7608                                                const Qualifiers &VisibleQuals) {
7609   // Only deal with canonical types.
7610   Ty = Context.getCanonicalType(Ty);
7611 
7612   // Look through reference types; they aren't part of the type of an
7613   // expression for the purposes of conversions.
7614   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7615     Ty = RefTy->getPointeeType();
7616 
7617   // If we're dealing with an array type, decay to the pointer.
7618   if (Ty->isArrayType())
7619     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7620 
7621   // Otherwise, we don't care about qualifiers on the type.
7622   Ty = Ty.getLocalUnqualifiedType();
7623 
7624   // Flag if we ever add a non-record type.
7625   const RecordType *TyRec = Ty->getAs<RecordType>();
7626   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7627 
7628   // Flag if we encounter an arithmetic type.
7629   HasArithmeticOrEnumeralTypes =
7630     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7631 
7632   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7633     PointerTypes.insert(Ty);
7634   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7635     // Insert our type, and its more-qualified variants, into the set
7636     // of types.
7637     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7638       return;
7639   } else if (Ty->isMemberPointerType()) {
7640     // Member pointers are far easier, since the pointee can't be converted.
7641     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7642       return;
7643   } else if (Ty->isEnumeralType()) {
7644     HasArithmeticOrEnumeralTypes = true;
7645     EnumerationTypes.insert(Ty);
7646   } else if (Ty->isVectorType()) {
7647     // We treat vector types as arithmetic types in many contexts as an
7648     // extension.
7649     HasArithmeticOrEnumeralTypes = true;
7650     VectorTypes.insert(Ty);
7651   } else if (Ty->isNullPtrType()) {
7652     HasNullPtrType = true;
7653   } else if (AllowUserConversions && TyRec) {
7654     // No conversion functions in incomplete types.
7655     if (!SemaRef.isCompleteType(Loc, Ty))
7656       return;
7657 
7658     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7659     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7660       if (isa<UsingShadowDecl>(D))
7661         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7662 
7663       // Skip conversion function templates; they don't tell us anything
7664       // about which builtin types we can convert to.
7665       if (isa<FunctionTemplateDecl>(D))
7666         continue;
7667 
7668       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7669       if (AllowExplicitConversions || !Conv->isExplicit()) {
7670         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7671                               VisibleQuals);
7672       }
7673     }
7674   }
7675 }
7676 /// Helper function for adjusting address spaces for the pointer or reference
7677 /// operands of builtin operators depending on the argument.
7678 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7679                                                         Expr *Arg) {
7680   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7681 }
7682 
7683 /// Helper function for AddBuiltinOperatorCandidates() that adds
7684 /// the volatile- and non-volatile-qualified assignment operators for the
7685 /// given type to the candidate set.
7686 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7687                                                    QualType T,
7688                                                    ArrayRef<Expr *> Args,
7689                                     OverloadCandidateSet &CandidateSet) {
7690   QualType ParamTypes[2];
7691 
7692   // T& operator=(T&, T)
7693   ParamTypes[0] = S.Context.getLValueReferenceType(
7694       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7695   ParamTypes[1] = T;
7696   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7697                         /*IsAssignmentOperator=*/true);
7698 
7699   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7700     // volatile T& operator=(volatile T&, T)
7701     ParamTypes[0] = S.Context.getLValueReferenceType(
7702         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7703                                                 Args[0]));
7704     ParamTypes[1] = T;
7705     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7706                           /*IsAssignmentOperator=*/true);
7707   }
7708 }
7709 
7710 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7711 /// if any, found in visible type conversion functions found in ArgExpr's type.
7712 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7713     Qualifiers VRQuals;
7714     const RecordType *TyRec;
7715     if (const MemberPointerType *RHSMPType =
7716         ArgExpr->getType()->getAs<MemberPointerType>())
7717       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7718     else
7719       TyRec = ArgExpr->getType()->getAs<RecordType>();
7720     if (!TyRec) {
7721       // Just to be safe, assume the worst case.
7722       VRQuals.addVolatile();
7723       VRQuals.addRestrict();
7724       return VRQuals;
7725     }
7726 
7727     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7728     if (!ClassDecl->hasDefinition())
7729       return VRQuals;
7730 
7731     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7732       if (isa<UsingShadowDecl>(D))
7733         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7734       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7735         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7736         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7737           CanTy = ResTypeRef->getPointeeType();
7738         // Need to go down the pointer/mempointer chain and add qualifiers
7739         // as see them.
7740         bool done = false;
7741         while (!done) {
7742           if (CanTy.isRestrictQualified())
7743             VRQuals.addRestrict();
7744           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7745             CanTy = ResTypePtr->getPointeeType();
7746           else if (const MemberPointerType *ResTypeMPtr =
7747                 CanTy->getAs<MemberPointerType>())
7748             CanTy = ResTypeMPtr->getPointeeType();
7749           else
7750             done = true;
7751           if (CanTy.isVolatileQualified())
7752             VRQuals.addVolatile();
7753           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7754             return VRQuals;
7755         }
7756       }
7757     }
7758     return VRQuals;
7759 }
7760 
7761 namespace {
7762 
7763 /// Helper class to manage the addition of builtin operator overload
7764 /// candidates. It provides shared state and utility methods used throughout
7765 /// the process, as well as a helper method to add each group of builtin
7766 /// operator overloads from the standard to a candidate set.
7767 class BuiltinOperatorOverloadBuilder {
7768   // Common instance state available to all overload candidate addition methods.
7769   Sema &S;
7770   ArrayRef<Expr *> Args;
7771   Qualifiers VisibleTypeConversionsQuals;
7772   bool HasArithmeticOrEnumeralCandidateType;
7773   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7774   OverloadCandidateSet &CandidateSet;
7775 
7776   static constexpr int ArithmeticTypesCap = 24;
7777   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7778 
7779   // Define some indices used to iterate over the arithemetic types in
7780   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7781   // types are that preserved by promotion (C++ [over.built]p2).
7782   unsigned FirstIntegralType,
7783            LastIntegralType;
7784   unsigned FirstPromotedIntegralType,
7785            LastPromotedIntegralType;
7786   unsigned FirstPromotedArithmeticType,
7787            LastPromotedArithmeticType;
7788   unsigned NumArithmeticTypes;
7789 
7790   void InitArithmeticTypes() {
7791     // Start of promoted types.
7792     FirstPromotedArithmeticType = 0;
7793     ArithmeticTypes.push_back(S.Context.FloatTy);
7794     ArithmeticTypes.push_back(S.Context.DoubleTy);
7795     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7796     if (S.Context.getTargetInfo().hasFloat128Type())
7797       ArithmeticTypes.push_back(S.Context.Float128Ty);
7798 
7799     // Start of integral types.
7800     FirstIntegralType = ArithmeticTypes.size();
7801     FirstPromotedIntegralType = ArithmeticTypes.size();
7802     ArithmeticTypes.push_back(S.Context.IntTy);
7803     ArithmeticTypes.push_back(S.Context.LongTy);
7804     ArithmeticTypes.push_back(S.Context.LongLongTy);
7805     if (S.Context.getTargetInfo().hasInt128Type())
7806       ArithmeticTypes.push_back(S.Context.Int128Ty);
7807     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7808     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7809     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7810     if (S.Context.getTargetInfo().hasInt128Type())
7811       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7812     LastPromotedIntegralType = ArithmeticTypes.size();
7813     LastPromotedArithmeticType = ArithmeticTypes.size();
7814     // End of promoted types.
7815 
7816     ArithmeticTypes.push_back(S.Context.BoolTy);
7817     ArithmeticTypes.push_back(S.Context.CharTy);
7818     ArithmeticTypes.push_back(S.Context.WCharTy);
7819     if (S.Context.getLangOpts().Char8)
7820       ArithmeticTypes.push_back(S.Context.Char8Ty);
7821     ArithmeticTypes.push_back(S.Context.Char16Ty);
7822     ArithmeticTypes.push_back(S.Context.Char32Ty);
7823     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7824     ArithmeticTypes.push_back(S.Context.ShortTy);
7825     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7826     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7827     LastIntegralType = ArithmeticTypes.size();
7828     NumArithmeticTypes = ArithmeticTypes.size();
7829     // End of integral types.
7830     // FIXME: What about complex? What about half?
7831 
7832     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7833            "Enough inline storage for all arithmetic types.");
7834   }
7835 
7836   /// Helper method to factor out the common pattern of adding overloads
7837   /// for '++' and '--' builtin operators.
7838   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7839                                            bool HasVolatile,
7840                                            bool HasRestrict) {
7841     QualType ParamTypes[2] = {
7842       S.Context.getLValueReferenceType(CandidateTy),
7843       S.Context.IntTy
7844     };
7845 
7846     // Non-volatile version.
7847     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7848 
7849     // Use a heuristic to reduce number of builtin candidates in the set:
7850     // add volatile version only if there are conversions to a volatile type.
7851     if (HasVolatile) {
7852       ParamTypes[0] =
7853         S.Context.getLValueReferenceType(
7854           S.Context.getVolatileType(CandidateTy));
7855       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7856     }
7857 
7858     // Add restrict version only if there are conversions to a restrict type
7859     // and our candidate type is a non-restrict-qualified pointer.
7860     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7861         !CandidateTy.isRestrictQualified()) {
7862       ParamTypes[0]
7863         = S.Context.getLValueReferenceType(
7864             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7865       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7866 
7867       if (HasVolatile) {
7868         ParamTypes[0]
7869           = S.Context.getLValueReferenceType(
7870               S.Context.getCVRQualifiedType(CandidateTy,
7871                                             (Qualifiers::Volatile |
7872                                              Qualifiers::Restrict)));
7873         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7874       }
7875     }
7876 
7877   }
7878 
7879 public:
7880   BuiltinOperatorOverloadBuilder(
7881     Sema &S, ArrayRef<Expr *> Args,
7882     Qualifiers VisibleTypeConversionsQuals,
7883     bool HasArithmeticOrEnumeralCandidateType,
7884     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7885     OverloadCandidateSet &CandidateSet)
7886     : S(S), Args(Args),
7887       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7888       HasArithmeticOrEnumeralCandidateType(
7889         HasArithmeticOrEnumeralCandidateType),
7890       CandidateTypes(CandidateTypes),
7891       CandidateSet(CandidateSet) {
7892 
7893     InitArithmeticTypes();
7894   }
7895 
7896   // Increment is deprecated for bool since C++17.
7897   //
7898   // C++ [over.built]p3:
7899   //
7900   //   For every pair (T, VQ), where T is an arithmetic type other
7901   //   than bool, and VQ is either volatile or empty, there exist
7902   //   candidate operator functions of the form
7903   //
7904   //       VQ T&      operator++(VQ T&);
7905   //       T          operator++(VQ T&, int);
7906   //
7907   // C++ [over.built]p4:
7908   //
7909   //   For every pair (T, VQ), where T is an arithmetic type other
7910   //   than bool, and VQ is either volatile or empty, there exist
7911   //   candidate operator functions of the form
7912   //
7913   //       VQ T&      operator--(VQ T&);
7914   //       T          operator--(VQ T&, int);
7915   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7916     if (!HasArithmeticOrEnumeralCandidateType)
7917       return;
7918 
7919     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7920       const auto TypeOfT = ArithmeticTypes[Arith];
7921       if (TypeOfT == S.Context.BoolTy) {
7922         if (Op == OO_MinusMinus)
7923           continue;
7924         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7925           continue;
7926       }
7927       addPlusPlusMinusMinusStyleOverloads(
7928         TypeOfT,
7929         VisibleTypeConversionsQuals.hasVolatile(),
7930         VisibleTypeConversionsQuals.hasRestrict());
7931     }
7932   }
7933 
7934   // C++ [over.built]p5:
7935   //
7936   //   For every pair (T, VQ), where T is a cv-qualified or
7937   //   cv-unqualified object type, and VQ is either volatile or
7938   //   empty, there exist candidate operator functions of the form
7939   //
7940   //       T*VQ&      operator++(T*VQ&);
7941   //       T*VQ&      operator--(T*VQ&);
7942   //       T*         operator++(T*VQ&, int);
7943   //       T*         operator--(T*VQ&, int);
7944   void addPlusPlusMinusMinusPointerOverloads() {
7945     for (BuiltinCandidateTypeSet::iterator
7946               Ptr = CandidateTypes[0].pointer_begin(),
7947            PtrEnd = CandidateTypes[0].pointer_end();
7948          Ptr != PtrEnd; ++Ptr) {
7949       // Skip pointer types that aren't pointers to object types.
7950       if (!(*Ptr)->getPointeeType()->isObjectType())
7951         continue;
7952 
7953       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7954         (!(*Ptr).isVolatileQualified() &&
7955          VisibleTypeConversionsQuals.hasVolatile()),
7956         (!(*Ptr).isRestrictQualified() &&
7957          VisibleTypeConversionsQuals.hasRestrict()));
7958     }
7959   }
7960 
7961   // C++ [over.built]p6:
7962   //   For every cv-qualified or cv-unqualified object type T, there
7963   //   exist candidate operator functions of the form
7964   //
7965   //       T&         operator*(T*);
7966   //
7967   // C++ [over.built]p7:
7968   //   For every function type T that does not have cv-qualifiers or a
7969   //   ref-qualifier, there exist candidate operator functions of the form
7970   //       T&         operator*(T*);
7971   void addUnaryStarPointerOverloads() {
7972     for (BuiltinCandidateTypeSet::iterator
7973               Ptr = CandidateTypes[0].pointer_begin(),
7974            PtrEnd = CandidateTypes[0].pointer_end();
7975          Ptr != PtrEnd; ++Ptr) {
7976       QualType ParamTy = *Ptr;
7977       QualType PointeeTy = ParamTy->getPointeeType();
7978       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7979         continue;
7980 
7981       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7982         if (Proto->getMethodQuals() || Proto->getRefQualifier())
7983           continue;
7984 
7985       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7986     }
7987   }
7988 
7989   // C++ [over.built]p9:
7990   //  For every promoted arithmetic type T, there exist candidate
7991   //  operator functions of the form
7992   //
7993   //       T         operator+(T);
7994   //       T         operator-(T);
7995   void addUnaryPlusOrMinusArithmeticOverloads() {
7996     if (!HasArithmeticOrEnumeralCandidateType)
7997       return;
7998 
7999     for (unsigned Arith = FirstPromotedArithmeticType;
8000          Arith < LastPromotedArithmeticType; ++Arith) {
8001       QualType ArithTy = ArithmeticTypes[Arith];
8002       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8003     }
8004 
8005     // Extension: We also add these operators for vector types.
8006     for (BuiltinCandidateTypeSet::iterator
8007               Vec = CandidateTypes[0].vector_begin(),
8008            VecEnd = CandidateTypes[0].vector_end();
8009          Vec != VecEnd; ++Vec) {
8010       QualType VecTy = *Vec;
8011       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8012     }
8013   }
8014 
8015   // C++ [over.built]p8:
8016   //   For every type T, there exist candidate operator functions of
8017   //   the form
8018   //
8019   //       T*         operator+(T*);
8020   void addUnaryPlusPointerOverloads() {
8021     for (BuiltinCandidateTypeSet::iterator
8022               Ptr = CandidateTypes[0].pointer_begin(),
8023            PtrEnd = CandidateTypes[0].pointer_end();
8024          Ptr != PtrEnd; ++Ptr) {
8025       QualType ParamTy = *Ptr;
8026       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8027     }
8028   }
8029 
8030   // C++ [over.built]p10:
8031   //   For every promoted integral type T, there exist candidate
8032   //   operator functions of the form
8033   //
8034   //        T         operator~(T);
8035   void addUnaryTildePromotedIntegralOverloads() {
8036     if (!HasArithmeticOrEnumeralCandidateType)
8037       return;
8038 
8039     for (unsigned Int = FirstPromotedIntegralType;
8040          Int < LastPromotedIntegralType; ++Int) {
8041       QualType IntTy = ArithmeticTypes[Int];
8042       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8043     }
8044 
8045     // Extension: We also add this operator for vector types.
8046     for (BuiltinCandidateTypeSet::iterator
8047               Vec = CandidateTypes[0].vector_begin(),
8048            VecEnd = CandidateTypes[0].vector_end();
8049          Vec != VecEnd; ++Vec) {
8050       QualType VecTy = *Vec;
8051       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8052     }
8053   }
8054 
8055   // C++ [over.match.oper]p16:
8056   //   For every pointer to member type T or type std::nullptr_t, there
8057   //   exist candidate operator functions of the form
8058   //
8059   //        bool operator==(T,T);
8060   //        bool operator!=(T,T);
8061   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8062     /// Set of (canonical) types that we've already handled.
8063     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8064 
8065     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8066       for (BuiltinCandidateTypeSet::iterator
8067                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8068              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8069            MemPtr != MemPtrEnd;
8070            ++MemPtr) {
8071         // Don't add the same builtin candidate twice.
8072         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8073           continue;
8074 
8075         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8076         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8077       }
8078 
8079       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8080         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8081         if (AddedTypes.insert(NullPtrTy).second) {
8082           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8083           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8084         }
8085       }
8086     }
8087   }
8088 
8089   // C++ [over.built]p15:
8090   //
8091   //   For every T, where T is an enumeration type or a pointer type,
8092   //   there exist candidate operator functions of the form
8093   //
8094   //        bool       operator<(T, T);
8095   //        bool       operator>(T, T);
8096   //        bool       operator<=(T, T);
8097   //        bool       operator>=(T, T);
8098   //        bool       operator==(T, T);
8099   //        bool       operator!=(T, T);
8100   //           R       operator<=>(T, T)
8101   void addGenericBinaryPointerOrEnumeralOverloads() {
8102     // C++ [over.match.oper]p3:
8103     //   [...]the built-in candidates include all of the candidate operator
8104     //   functions defined in 13.6 that, compared to the given operator, [...]
8105     //   do not have the same parameter-type-list as any non-template non-member
8106     //   candidate.
8107     //
8108     // Note that in practice, this only affects enumeration types because there
8109     // aren't any built-in candidates of record type, and a user-defined operator
8110     // must have an operand of record or enumeration type. Also, the only other
8111     // overloaded operator with enumeration arguments, operator=,
8112     // cannot be overloaded for enumeration types, so this is the only place
8113     // where we must suppress candidates like this.
8114     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8115       UserDefinedBinaryOperators;
8116 
8117     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8118       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8119           CandidateTypes[ArgIdx].enumeration_end()) {
8120         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8121                                          CEnd = CandidateSet.end();
8122              C != CEnd; ++C) {
8123           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8124             continue;
8125 
8126           if (C->Function->isFunctionTemplateSpecialization())
8127             continue;
8128 
8129           QualType FirstParamType =
8130             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8131           QualType SecondParamType =
8132             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8133 
8134           // Skip if either parameter isn't of enumeral type.
8135           if (!FirstParamType->isEnumeralType() ||
8136               !SecondParamType->isEnumeralType())
8137             continue;
8138 
8139           // Add this operator to the set of known user-defined operators.
8140           UserDefinedBinaryOperators.insert(
8141             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8142                            S.Context.getCanonicalType(SecondParamType)));
8143         }
8144       }
8145     }
8146 
8147     /// Set of (canonical) types that we've already handled.
8148     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8149 
8150     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8151       for (BuiltinCandidateTypeSet::iterator
8152                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8153              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8154            Ptr != PtrEnd; ++Ptr) {
8155         // Don't add the same builtin candidate twice.
8156         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8157           continue;
8158 
8159         QualType ParamTypes[2] = { *Ptr, *Ptr };
8160         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8161       }
8162       for (BuiltinCandidateTypeSet::iterator
8163                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8164              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8165            Enum != EnumEnd; ++Enum) {
8166         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8167 
8168         // Don't add the same builtin candidate twice, or if a user defined
8169         // candidate exists.
8170         if (!AddedTypes.insert(CanonType).second ||
8171             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8172                                                             CanonType)))
8173           continue;
8174         QualType ParamTypes[2] = { *Enum, *Enum };
8175         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8176       }
8177     }
8178   }
8179 
8180   // C++ [over.built]p13:
8181   //
8182   //   For every cv-qualified or cv-unqualified object type T
8183   //   there exist candidate operator functions of the form
8184   //
8185   //      T*         operator+(T*, ptrdiff_t);
8186   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8187   //      T*         operator-(T*, ptrdiff_t);
8188   //      T*         operator+(ptrdiff_t, T*);
8189   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8190   //
8191   // C++ [over.built]p14:
8192   //
8193   //   For every T, where T is a pointer to object type, there
8194   //   exist candidate operator functions of the form
8195   //
8196   //      ptrdiff_t  operator-(T, T);
8197   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8198     /// Set of (canonical) types that we've already handled.
8199     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8200 
8201     for (int Arg = 0; Arg < 2; ++Arg) {
8202       QualType AsymmetricParamTypes[2] = {
8203         S.Context.getPointerDiffType(),
8204         S.Context.getPointerDiffType(),
8205       };
8206       for (BuiltinCandidateTypeSet::iterator
8207                 Ptr = CandidateTypes[Arg].pointer_begin(),
8208              PtrEnd = CandidateTypes[Arg].pointer_end();
8209            Ptr != PtrEnd; ++Ptr) {
8210         QualType PointeeTy = (*Ptr)->getPointeeType();
8211         if (!PointeeTy->isObjectType())
8212           continue;
8213 
8214         AsymmetricParamTypes[Arg] = *Ptr;
8215         if (Arg == 0 || Op == OO_Plus) {
8216           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8217           // T* operator+(ptrdiff_t, T*);
8218           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8219         }
8220         if (Op == OO_Minus) {
8221           // ptrdiff_t operator-(T, T);
8222           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8223             continue;
8224 
8225           QualType ParamTypes[2] = { *Ptr, *Ptr };
8226           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8227         }
8228       }
8229     }
8230   }
8231 
8232   // C++ [over.built]p12:
8233   //
8234   //   For every pair of promoted arithmetic types L and R, there
8235   //   exist candidate operator functions of the form
8236   //
8237   //        LR         operator*(L, R);
8238   //        LR         operator/(L, R);
8239   //        LR         operator+(L, R);
8240   //        LR         operator-(L, R);
8241   //        bool       operator<(L, R);
8242   //        bool       operator>(L, R);
8243   //        bool       operator<=(L, R);
8244   //        bool       operator>=(L, R);
8245   //        bool       operator==(L, R);
8246   //        bool       operator!=(L, R);
8247   //
8248   //   where LR is the result of the usual arithmetic conversions
8249   //   between types L and R.
8250   //
8251   // C++ [over.built]p24:
8252   //
8253   //   For every pair of promoted arithmetic types L and R, there exist
8254   //   candidate operator functions of the form
8255   //
8256   //        LR       operator?(bool, L, R);
8257   //
8258   //   where LR is the result of the usual arithmetic conversions
8259   //   between types L and R.
8260   // Our candidates ignore the first parameter.
8261   void addGenericBinaryArithmeticOverloads() {
8262     if (!HasArithmeticOrEnumeralCandidateType)
8263       return;
8264 
8265     for (unsigned Left = FirstPromotedArithmeticType;
8266          Left < LastPromotedArithmeticType; ++Left) {
8267       for (unsigned Right = FirstPromotedArithmeticType;
8268            Right < LastPromotedArithmeticType; ++Right) {
8269         QualType LandR[2] = { ArithmeticTypes[Left],
8270                               ArithmeticTypes[Right] };
8271         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8272       }
8273     }
8274 
8275     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8276     // conditional operator for vector types.
8277     for (BuiltinCandidateTypeSet::iterator
8278               Vec1 = CandidateTypes[0].vector_begin(),
8279            Vec1End = CandidateTypes[0].vector_end();
8280          Vec1 != Vec1End; ++Vec1) {
8281       for (BuiltinCandidateTypeSet::iterator
8282                 Vec2 = CandidateTypes[1].vector_begin(),
8283              Vec2End = CandidateTypes[1].vector_end();
8284            Vec2 != Vec2End; ++Vec2) {
8285         QualType LandR[2] = { *Vec1, *Vec2 };
8286         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8287       }
8288     }
8289   }
8290 
8291   // C++2a [over.built]p14:
8292   //
8293   //   For every integral type T there exists a candidate operator function
8294   //   of the form
8295   //
8296   //        std::strong_ordering operator<=>(T, T)
8297   //
8298   // C++2a [over.built]p15:
8299   //
8300   //   For every pair of floating-point types L and R, there exists a candidate
8301   //   operator function of the form
8302   //
8303   //       std::partial_ordering operator<=>(L, R);
8304   //
8305   // FIXME: The current specification for integral types doesn't play nice with
8306   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8307   // comparisons. Under the current spec this can lead to ambiguity during
8308   // overload resolution. For example:
8309   //
8310   //   enum A : int {a};
8311   //   auto x = (a <=> (long)42);
8312   //
8313   //   error: call is ambiguous for arguments 'A' and 'long'.
8314   //   note: candidate operator<=>(int, int)
8315   //   note: candidate operator<=>(long, long)
8316   //
8317   // To avoid this error, this function deviates from the specification and adds
8318   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8319   // arithmetic types (the same as the generic relational overloads).
8320   //
8321   // For now this function acts as a placeholder.
8322   void addThreeWayArithmeticOverloads() {
8323     addGenericBinaryArithmeticOverloads();
8324   }
8325 
8326   // C++ [over.built]p17:
8327   //
8328   //   For every pair of promoted integral types L and R, there
8329   //   exist candidate operator functions of the form
8330   //
8331   //      LR         operator%(L, R);
8332   //      LR         operator&(L, R);
8333   //      LR         operator^(L, R);
8334   //      LR         operator|(L, R);
8335   //      L          operator<<(L, R);
8336   //      L          operator>>(L, R);
8337   //
8338   //   where LR is the result of the usual arithmetic conversions
8339   //   between types L and R.
8340   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8341     if (!HasArithmeticOrEnumeralCandidateType)
8342       return;
8343 
8344     for (unsigned Left = FirstPromotedIntegralType;
8345          Left < LastPromotedIntegralType; ++Left) {
8346       for (unsigned Right = FirstPromotedIntegralType;
8347            Right < LastPromotedIntegralType; ++Right) {
8348         QualType LandR[2] = { ArithmeticTypes[Left],
8349                               ArithmeticTypes[Right] };
8350         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8351       }
8352     }
8353   }
8354 
8355   // C++ [over.built]p20:
8356   //
8357   //   For every pair (T, VQ), where T is an enumeration or
8358   //   pointer to member type and VQ is either volatile or
8359   //   empty, there exist candidate operator functions of the form
8360   //
8361   //        VQ T&      operator=(VQ T&, T);
8362   void addAssignmentMemberPointerOrEnumeralOverloads() {
8363     /// Set of (canonical) types that we've already handled.
8364     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8365 
8366     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8367       for (BuiltinCandidateTypeSet::iterator
8368                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8369              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8370            Enum != EnumEnd; ++Enum) {
8371         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8372           continue;
8373 
8374         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8375       }
8376 
8377       for (BuiltinCandidateTypeSet::iterator
8378                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8379              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8380            MemPtr != MemPtrEnd; ++MemPtr) {
8381         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8382           continue;
8383 
8384         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8385       }
8386     }
8387   }
8388 
8389   // C++ [over.built]p19:
8390   //
8391   //   For every pair (T, VQ), where T is any type and VQ is either
8392   //   volatile or empty, there exist candidate operator functions
8393   //   of the form
8394   //
8395   //        T*VQ&      operator=(T*VQ&, T*);
8396   //
8397   // C++ [over.built]p21:
8398   //
8399   //   For every pair (T, VQ), where T is a cv-qualified or
8400   //   cv-unqualified object type and VQ is either volatile or
8401   //   empty, there exist candidate operator functions of the form
8402   //
8403   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8404   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8405   void addAssignmentPointerOverloads(bool isEqualOp) {
8406     /// Set of (canonical) types that we've already handled.
8407     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8408 
8409     for (BuiltinCandidateTypeSet::iterator
8410               Ptr = CandidateTypes[0].pointer_begin(),
8411            PtrEnd = CandidateTypes[0].pointer_end();
8412          Ptr != PtrEnd; ++Ptr) {
8413       // If this is operator=, keep track of the builtin candidates we added.
8414       if (isEqualOp)
8415         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8416       else if (!(*Ptr)->getPointeeType()->isObjectType())
8417         continue;
8418 
8419       // non-volatile version
8420       QualType ParamTypes[2] = {
8421         S.Context.getLValueReferenceType(*Ptr),
8422         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8423       };
8424       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8425                             /*IsAssignmentOperator=*/ isEqualOp);
8426 
8427       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8428                           VisibleTypeConversionsQuals.hasVolatile();
8429       if (NeedVolatile) {
8430         // volatile version
8431         ParamTypes[0] =
8432           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8433         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8434                               /*IsAssignmentOperator=*/isEqualOp);
8435       }
8436 
8437       if (!(*Ptr).isRestrictQualified() &&
8438           VisibleTypeConversionsQuals.hasRestrict()) {
8439         // restrict version
8440         ParamTypes[0]
8441           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8442         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8443                               /*IsAssignmentOperator=*/isEqualOp);
8444 
8445         if (NeedVolatile) {
8446           // volatile restrict version
8447           ParamTypes[0]
8448             = S.Context.getLValueReferenceType(
8449                 S.Context.getCVRQualifiedType(*Ptr,
8450                                               (Qualifiers::Volatile |
8451                                                Qualifiers::Restrict)));
8452           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8453                                 /*IsAssignmentOperator=*/isEqualOp);
8454         }
8455       }
8456     }
8457 
8458     if (isEqualOp) {
8459       for (BuiltinCandidateTypeSet::iterator
8460                 Ptr = CandidateTypes[1].pointer_begin(),
8461              PtrEnd = CandidateTypes[1].pointer_end();
8462            Ptr != PtrEnd; ++Ptr) {
8463         // Make sure we don't add the same candidate twice.
8464         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8465           continue;
8466 
8467         QualType ParamTypes[2] = {
8468           S.Context.getLValueReferenceType(*Ptr),
8469           *Ptr,
8470         };
8471 
8472         // non-volatile version
8473         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8474                               /*IsAssignmentOperator=*/true);
8475 
8476         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8477                            VisibleTypeConversionsQuals.hasVolatile();
8478         if (NeedVolatile) {
8479           // volatile version
8480           ParamTypes[0] =
8481             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8482           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8483                                 /*IsAssignmentOperator=*/true);
8484         }
8485 
8486         if (!(*Ptr).isRestrictQualified() &&
8487             VisibleTypeConversionsQuals.hasRestrict()) {
8488           // restrict version
8489           ParamTypes[0]
8490             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8491           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8492                                 /*IsAssignmentOperator=*/true);
8493 
8494           if (NeedVolatile) {
8495             // volatile restrict version
8496             ParamTypes[0]
8497               = S.Context.getLValueReferenceType(
8498                   S.Context.getCVRQualifiedType(*Ptr,
8499                                                 (Qualifiers::Volatile |
8500                                                  Qualifiers::Restrict)));
8501             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8502                                   /*IsAssignmentOperator=*/true);
8503           }
8504         }
8505       }
8506     }
8507   }
8508 
8509   // C++ [over.built]p18:
8510   //
8511   //   For every triple (L, VQ, R), where L is an arithmetic type,
8512   //   VQ is either volatile or empty, and R is a promoted
8513   //   arithmetic type, there exist candidate operator functions of
8514   //   the form
8515   //
8516   //        VQ L&      operator=(VQ L&, R);
8517   //        VQ L&      operator*=(VQ L&, R);
8518   //        VQ L&      operator/=(VQ L&, R);
8519   //        VQ L&      operator+=(VQ L&, R);
8520   //        VQ L&      operator-=(VQ L&, R);
8521   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8522     if (!HasArithmeticOrEnumeralCandidateType)
8523       return;
8524 
8525     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8526       for (unsigned Right = FirstPromotedArithmeticType;
8527            Right < LastPromotedArithmeticType; ++Right) {
8528         QualType ParamTypes[2];
8529         ParamTypes[1] = ArithmeticTypes[Right];
8530         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8531             S, ArithmeticTypes[Left], Args[0]);
8532         // Add this built-in operator as a candidate (VQ is empty).
8533         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8534         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8535                               /*IsAssignmentOperator=*/isEqualOp);
8536 
8537         // Add this built-in operator as a candidate (VQ is 'volatile').
8538         if (VisibleTypeConversionsQuals.hasVolatile()) {
8539           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8540           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8541           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8542                                 /*IsAssignmentOperator=*/isEqualOp);
8543         }
8544       }
8545     }
8546 
8547     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8548     for (BuiltinCandidateTypeSet::iterator
8549               Vec1 = CandidateTypes[0].vector_begin(),
8550            Vec1End = CandidateTypes[0].vector_end();
8551          Vec1 != Vec1End; ++Vec1) {
8552       for (BuiltinCandidateTypeSet::iterator
8553                 Vec2 = CandidateTypes[1].vector_begin(),
8554              Vec2End = CandidateTypes[1].vector_end();
8555            Vec2 != Vec2End; ++Vec2) {
8556         QualType ParamTypes[2];
8557         ParamTypes[1] = *Vec2;
8558         // Add this built-in operator as a candidate (VQ is empty).
8559         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8560         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8561                               /*IsAssignmentOperator=*/isEqualOp);
8562 
8563         // Add this built-in operator as a candidate (VQ is 'volatile').
8564         if (VisibleTypeConversionsQuals.hasVolatile()) {
8565           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8566           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8567           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8568                                 /*IsAssignmentOperator=*/isEqualOp);
8569         }
8570       }
8571     }
8572   }
8573 
8574   // C++ [over.built]p22:
8575   //
8576   //   For every triple (L, VQ, R), where L is an integral type, VQ
8577   //   is either volatile or empty, and R is a promoted integral
8578   //   type, there exist candidate operator functions of the form
8579   //
8580   //        VQ L&       operator%=(VQ L&, R);
8581   //        VQ L&       operator<<=(VQ L&, R);
8582   //        VQ L&       operator>>=(VQ L&, R);
8583   //        VQ L&       operator&=(VQ L&, R);
8584   //        VQ L&       operator^=(VQ L&, R);
8585   //        VQ L&       operator|=(VQ L&, R);
8586   void addAssignmentIntegralOverloads() {
8587     if (!HasArithmeticOrEnumeralCandidateType)
8588       return;
8589 
8590     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8591       for (unsigned Right = FirstPromotedIntegralType;
8592            Right < LastPromotedIntegralType; ++Right) {
8593         QualType ParamTypes[2];
8594         ParamTypes[1] = ArithmeticTypes[Right];
8595         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8596             S, ArithmeticTypes[Left], Args[0]);
8597         // Add this built-in operator as a candidate (VQ is empty).
8598         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8599         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8600         if (VisibleTypeConversionsQuals.hasVolatile()) {
8601           // Add this built-in operator as a candidate (VQ is 'volatile').
8602           ParamTypes[0] = LeftBaseTy;
8603           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8604           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8605           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8606         }
8607       }
8608     }
8609   }
8610 
8611   // C++ [over.operator]p23:
8612   //
8613   //   There also exist candidate operator functions of the form
8614   //
8615   //        bool        operator!(bool);
8616   //        bool        operator&&(bool, bool);
8617   //        bool        operator||(bool, bool);
8618   void addExclaimOverload() {
8619     QualType ParamTy = S.Context.BoolTy;
8620     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8621                           /*IsAssignmentOperator=*/false,
8622                           /*NumContextualBoolArguments=*/1);
8623   }
8624   void addAmpAmpOrPipePipeOverload() {
8625     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8626     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8627                           /*IsAssignmentOperator=*/false,
8628                           /*NumContextualBoolArguments=*/2);
8629   }
8630 
8631   // C++ [over.built]p13:
8632   //
8633   //   For every cv-qualified or cv-unqualified object type T there
8634   //   exist candidate operator functions of the form
8635   //
8636   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8637   //        T&         operator[](T*, ptrdiff_t);
8638   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8639   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8640   //        T&         operator[](ptrdiff_t, T*);
8641   void addSubscriptOverloads() {
8642     for (BuiltinCandidateTypeSet::iterator
8643               Ptr = CandidateTypes[0].pointer_begin(),
8644            PtrEnd = CandidateTypes[0].pointer_end();
8645          Ptr != PtrEnd; ++Ptr) {
8646       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8647       QualType PointeeType = (*Ptr)->getPointeeType();
8648       if (!PointeeType->isObjectType())
8649         continue;
8650 
8651       // T& operator[](T*, ptrdiff_t)
8652       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8653     }
8654 
8655     for (BuiltinCandidateTypeSet::iterator
8656               Ptr = CandidateTypes[1].pointer_begin(),
8657            PtrEnd = CandidateTypes[1].pointer_end();
8658          Ptr != PtrEnd; ++Ptr) {
8659       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8660       QualType PointeeType = (*Ptr)->getPointeeType();
8661       if (!PointeeType->isObjectType())
8662         continue;
8663 
8664       // T& operator[](ptrdiff_t, T*)
8665       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8666     }
8667   }
8668 
8669   // C++ [over.built]p11:
8670   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8671   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8672   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8673   //    there exist candidate operator functions of the form
8674   //
8675   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8676   //
8677   //    where CV12 is the union of CV1 and CV2.
8678   void addArrowStarOverloads() {
8679     for (BuiltinCandidateTypeSet::iterator
8680              Ptr = CandidateTypes[0].pointer_begin(),
8681            PtrEnd = CandidateTypes[0].pointer_end();
8682          Ptr != PtrEnd; ++Ptr) {
8683       QualType C1Ty = (*Ptr);
8684       QualType C1;
8685       QualifierCollector Q1;
8686       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8687       if (!isa<RecordType>(C1))
8688         continue;
8689       // heuristic to reduce number of builtin candidates in the set.
8690       // Add volatile/restrict version only if there are conversions to a
8691       // volatile/restrict type.
8692       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8693         continue;
8694       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8695         continue;
8696       for (BuiltinCandidateTypeSet::iterator
8697                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8698              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8699            MemPtr != MemPtrEnd; ++MemPtr) {
8700         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8701         QualType C2 = QualType(mptr->getClass(), 0);
8702         C2 = C2.getUnqualifiedType();
8703         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8704           break;
8705         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8706         // build CV12 T&
8707         QualType T = mptr->getPointeeType();
8708         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8709             T.isVolatileQualified())
8710           continue;
8711         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8712             T.isRestrictQualified())
8713           continue;
8714         T = Q1.apply(S.Context, T);
8715         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8716       }
8717     }
8718   }
8719 
8720   // Note that we don't consider the first argument, since it has been
8721   // contextually converted to bool long ago. The candidates below are
8722   // therefore added as binary.
8723   //
8724   // C++ [over.built]p25:
8725   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8726   //   enumeration type, there exist candidate operator functions of the form
8727   //
8728   //        T        operator?(bool, T, T);
8729   //
8730   void addConditionalOperatorOverloads() {
8731     /// Set of (canonical) types that we've already handled.
8732     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8733 
8734     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8735       for (BuiltinCandidateTypeSet::iterator
8736                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8737              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8738            Ptr != PtrEnd; ++Ptr) {
8739         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8740           continue;
8741 
8742         QualType ParamTypes[2] = { *Ptr, *Ptr };
8743         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8744       }
8745 
8746       for (BuiltinCandidateTypeSet::iterator
8747                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8748              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8749            MemPtr != MemPtrEnd; ++MemPtr) {
8750         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8751           continue;
8752 
8753         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8754         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8755       }
8756 
8757       if (S.getLangOpts().CPlusPlus11) {
8758         for (BuiltinCandidateTypeSet::iterator
8759                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8760                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8761              Enum != EnumEnd; ++Enum) {
8762           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8763             continue;
8764 
8765           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8766             continue;
8767 
8768           QualType ParamTypes[2] = { *Enum, *Enum };
8769           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8770         }
8771       }
8772     }
8773   }
8774 };
8775 
8776 } // end anonymous namespace
8777 
8778 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8779 /// operator overloads to the candidate set (C++ [over.built]), based
8780 /// on the operator @p Op and the arguments given. For example, if the
8781 /// operator is a binary '+', this routine might add "int
8782 /// operator+(int, int)" to cover integer addition.
8783 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8784                                         SourceLocation OpLoc,
8785                                         ArrayRef<Expr *> Args,
8786                                         OverloadCandidateSet &CandidateSet) {
8787   // Find all of the types that the arguments can convert to, but only
8788   // if the operator we're looking at has built-in operator candidates
8789   // that make use of these types. Also record whether we encounter non-record
8790   // candidate types or either arithmetic or enumeral candidate types.
8791   Qualifiers VisibleTypeConversionsQuals;
8792   VisibleTypeConversionsQuals.addConst();
8793   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8794     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8795 
8796   bool HasNonRecordCandidateType = false;
8797   bool HasArithmeticOrEnumeralCandidateType = false;
8798   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8799   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8800     CandidateTypes.emplace_back(*this);
8801     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8802                                                  OpLoc,
8803                                                  true,
8804                                                  (Op == OO_Exclaim ||
8805                                                   Op == OO_AmpAmp ||
8806                                                   Op == OO_PipePipe),
8807                                                  VisibleTypeConversionsQuals);
8808     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8809         CandidateTypes[ArgIdx].hasNonRecordTypes();
8810     HasArithmeticOrEnumeralCandidateType =
8811         HasArithmeticOrEnumeralCandidateType ||
8812         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8813   }
8814 
8815   // Exit early when no non-record types have been added to the candidate set
8816   // for any of the arguments to the operator.
8817   //
8818   // We can't exit early for !, ||, or &&, since there we have always have
8819   // 'bool' overloads.
8820   if (!HasNonRecordCandidateType &&
8821       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8822     return;
8823 
8824   // Setup an object to manage the common state for building overloads.
8825   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8826                                            VisibleTypeConversionsQuals,
8827                                            HasArithmeticOrEnumeralCandidateType,
8828                                            CandidateTypes, CandidateSet);
8829 
8830   // Dispatch over the operation to add in only those overloads which apply.
8831   switch (Op) {
8832   case OO_None:
8833   case NUM_OVERLOADED_OPERATORS:
8834     llvm_unreachable("Expected an overloaded operator");
8835 
8836   case OO_New:
8837   case OO_Delete:
8838   case OO_Array_New:
8839   case OO_Array_Delete:
8840   case OO_Call:
8841     llvm_unreachable(
8842                     "Special operators don't use AddBuiltinOperatorCandidates");
8843 
8844   case OO_Comma:
8845   case OO_Arrow:
8846   case OO_Coawait:
8847     // C++ [over.match.oper]p3:
8848     //   -- For the operator ',', the unary operator '&', the
8849     //      operator '->', or the operator 'co_await', the
8850     //      built-in candidates set is empty.
8851     break;
8852 
8853   case OO_Plus: // '+' is either unary or binary
8854     if (Args.size() == 1)
8855       OpBuilder.addUnaryPlusPointerOverloads();
8856     LLVM_FALLTHROUGH;
8857 
8858   case OO_Minus: // '-' is either unary or binary
8859     if (Args.size() == 1) {
8860       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8861     } else {
8862       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8863       OpBuilder.addGenericBinaryArithmeticOverloads();
8864     }
8865     break;
8866 
8867   case OO_Star: // '*' is either unary or binary
8868     if (Args.size() == 1)
8869       OpBuilder.addUnaryStarPointerOverloads();
8870     else
8871       OpBuilder.addGenericBinaryArithmeticOverloads();
8872     break;
8873 
8874   case OO_Slash:
8875     OpBuilder.addGenericBinaryArithmeticOverloads();
8876     break;
8877 
8878   case OO_PlusPlus:
8879   case OO_MinusMinus:
8880     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8881     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8882     break;
8883 
8884   case OO_EqualEqual:
8885   case OO_ExclaimEqual:
8886     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8887     LLVM_FALLTHROUGH;
8888 
8889   case OO_Less:
8890   case OO_Greater:
8891   case OO_LessEqual:
8892   case OO_GreaterEqual:
8893     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8894     OpBuilder.addGenericBinaryArithmeticOverloads();
8895     break;
8896 
8897   case OO_Spaceship:
8898     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8899     OpBuilder.addThreeWayArithmeticOverloads();
8900     break;
8901 
8902   case OO_Percent:
8903   case OO_Caret:
8904   case OO_Pipe:
8905   case OO_LessLess:
8906   case OO_GreaterGreater:
8907     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8908     break;
8909 
8910   case OO_Amp: // '&' is either unary or binary
8911     if (Args.size() == 1)
8912       // C++ [over.match.oper]p3:
8913       //   -- For the operator ',', the unary operator '&', or the
8914       //      operator '->', the built-in candidates set is empty.
8915       break;
8916 
8917     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8918     break;
8919 
8920   case OO_Tilde:
8921     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8922     break;
8923 
8924   case OO_Equal:
8925     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8926     LLVM_FALLTHROUGH;
8927 
8928   case OO_PlusEqual:
8929   case OO_MinusEqual:
8930     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8931     LLVM_FALLTHROUGH;
8932 
8933   case OO_StarEqual:
8934   case OO_SlashEqual:
8935     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8936     break;
8937 
8938   case OO_PercentEqual:
8939   case OO_LessLessEqual:
8940   case OO_GreaterGreaterEqual:
8941   case OO_AmpEqual:
8942   case OO_CaretEqual:
8943   case OO_PipeEqual:
8944     OpBuilder.addAssignmentIntegralOverloads();
8945     break;
8946 
8947   case OO_Exclaim:
8948     OpBuilder.addExclaimOverload();
8949     break;
8950 
8951   case OO_AmpAmp:
8952   case OO_PipePipe:
8953     OpBuilder.addAmpAmpOrPipePipeOverload();
8954     break;
8955 
8956   case OO_Subscript:
8957     OpBuilder.addSubscriptOverloads();
8958     break;
8959 
8960   case OO_ArrowStar:
8961     OpBuilder.addArrowStarOverloads();
8962     break;
8963 
8964   case OO_Conditional:
8965     OpBuilder.addConditionalOperatorOverloads();
8966     OpBuilder.addGenericBinaryArithmeticOverloads();
8967     break;
8968   }
8969 }
8970 
8971 /// Add function candidates found via argument-dependent lookup
8972 /// to the set of overloading candidates.
8973 ///
8974 /// This routine performs argument-dependent name lookup based on the
8975 /// given function name (which may also be an operator name) and adds
8976 /// all of the overload candidates found by ADL to the overload
8977 /// candidate set (C++ [basic.lookup.argdep]).
8978 void
8979 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8980                                            SourceLocation Loc,
8981                                            ArrayRef<Expr *> Args,
8982                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8983                                            OverloadCandidateSet& CandidateSet,
8984                                            bool PartialOverloading) {
8985   ADLResult Fns;
8986 
8987   // FIXME: This approach for uniquing ADL results (and removing
8988   // redundant candidates from the set) relies on pointer-equality,
8989   // which means we need to key off the canonical decl.  However,
8990   // always going back to the canonical decl might not get us the
8991   // right set of default arguments.  What default arguments are
8992   // we supposed to consider on ADL candidates, anyway?
8993 
8994   // FIXME: Pass in the explicit template arguments?
8995   ArgumentDependentLookup(Name, Loc, Args, Fns);
8996 
8997   // Erase all of the candidates we already knew about.
8998   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8999                                    CandEnd = CandidateSet.end();
9000        Cand != CandEnd; ++Cand)
9001     if (Cand->Function) {
9002       Fns.erase(Cand->Function);
9003       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9004         Fns.erase(FunTmpl);
9005     }
9006 
9007   // For each of the ADL candidates we found, add it to the overload
9008   // set.
9009   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9010     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9011 
9012     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9013       if (ExplicitTemplateArgs)
9014         continue;
9015 
9016       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9017                            /*SuppressUserConversions=*/false, PartialOverloading,
9018                            /*AllowExplicit*/ true,
9019                            /*AllowExplicitConversions*/ false,
9020                            ADLCallKind::UsesADL);
9021     } else {
9022       AddTemplateOverloadCandidate(
9023           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9024           CandidateSet,
9025           /*SuppressUserConversions=*/false, PartialOverloading,
9026           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9027     }
9028   }
9029 }
9030 
9031 namespace {
9032 enum class Comparison { Equal, Better, Worse };
9033 }
9034 
9035 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9036 /// overload resolution.
9037 ///
9038 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9039 /// Cand1's first N enable_if attributes have precisely the same conditions as
9040 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9041 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9042 ///
9043 /// Note that you can have a pair of candidates such that Cand1's enable_if
9044 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9045 /// worse than Cand1's.
9046 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9047                                        const FunctionDecl *Cand2) {
9048   // Common case: One (or both) decls don't have enable_if attrs.
9049   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9050   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9051   if (!Cand1Attr || !Cand2Attr) {
9052     if (Cand1Attr == Cand2Attr)
9053       return Comparison::Equal;
9054     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9055   }
9056 
9057   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9058   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9059 
9060   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9061   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9062     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9063     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9064 
9065     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9066     // has fewer enable_if attributes than Cand2, and vice versa.
9067     if (!Cand1A)
9068       return Comparison::Worse;
9069     if (!Cand2A)
9070       return Comparison::Better;
9071 
9072     Cand1ID.clear();
9073     Cand2ID.clear();
9074 
9075     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9076     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9077     if (Cand1ID != Cand2ID)
9078       return Comparison::Worse;
9079   }
9080 
9081   return Comparison::Equal;
9082 }
9083 
9084 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9085                                           const OverloadCandidate &Cand2) {
9086   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9087       !Cand2.Function->isMultiVersion())
9088     return false;
9089 
9090   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9091   // is obviously better.
9092   if (Cand1.Function->isInvalidDecl()) return false;
9093   if (Cand2.Function->isInvalidDecl()) return true;
9094 
9095   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9096   // cpu_dispatch, else arbitrarily based on the identifiers.
9097   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9098   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9099   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9100   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9101 
9102   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9103     return false;
9104 
9105   if (Cand1CPUDisp && !Cand2CPUDisp)
9106     return true;
9107   if (Cand2CPUDisp && !Cand1CPUDisp)
9108     return false;
9109 
9110   if (Cand1CPUSpec && Cand2CPUSpec) {
9111     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9112       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9113 
9114     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9115         FirstDiff = std::mismatch(
9116             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9117             Cand2CPUSpec->cpus_begin(),
9118             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9119               return LHS->getName() == RHS->getName();
9120             });
9121 
9122     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9123            "Two different cpu-specific versions should not have the same "
9124            "identifier list, otherwise they'd be the same decl!");
9125     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9126   }
9127   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9128 }
9129 
9130 /// isBetterOverloadCandidate - Determines whether the first overload
9131 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9132 bool clang::isBetterOverloadCandidate(
9133     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9134     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9135   // Define viable functions to be better candidates than non-viable
9136   // functions.
9137   if (!Cand2.Viable)
9138     return Cand1.Viable;
9139   else if (!Cand1.Viable)
9140     return false;
9141 
9142   // C++ [over.match.best]p1:
9143   //
9144   //   -- if F is a static member function, ICS1(F) is defined such
9145   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9146   //      any function G, and, symmetrically, ICS1(G) is neither
9147   //      better nor worse than ICS1(F).
9148   unsigned StartArg = 0;
9149   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9150     StartArg = 1;
9151 
9152   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9153     // We don't allow incompatible pointer conversions in C++.
9154     if (!S.getLangOpts().CPlusPlus)
9155       return ICS.isStandard() &&
9156              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9157 
9158     // The only ill-formed conversion we allow in C++ is the string literal to
9159     // char* conversion, which is only considered ill-formed after C++11.
9160     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9161            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9162   };
9163 
9164   // Define functions that don't require ill-formed conversions for a given
9165   // argument to be better candidates than functions that do.
9166   unsigned NumArgs = Cand1.Conversions.size();
9167   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9168   bool HasBetterConversion = false;
9169   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9170     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9171     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9172     if (Cand1Bad != Cand2Bad) {
9173       if (Cand1Bad)
9174         return false;
9175       HasBetterConversion = true;
9176     }
9177   }
9178 
9179   if (HasBetterConversion)
9180     return true;
9181 
9182   // C++ [over.match.best]p1:
9183   //   A viable function F1 is defined to be a better function than another
9184   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9185   //   conversion sequence than ICSi(F2), and then...
9186   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9187     switch (CompareImplicitConversionSequences(S, Loc,
9188                                                Cand1.Conversions[ArgIdx],
9189                                                Cand2.Conversions[ArgIdx])) {
9190     case ImplicitConversionSequence::Better:
9191       // Cand1 has a better conversion sequence.
9192       HasBetterConversion = true;
9193       break;
9194 
9195     case ImplicitConversionSequence::Worse:
9196       // Cand1 can't be better than Cand2.
9197       return false;
9198 
9199     case ImplicitConversionSequence::Indistinguishable:
9200       // Do nothing.
9201       break;
9202     }
9203   }
9204 
9205   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9206   //       ICSj(F2), or, if not that,
9207   if (HasBetterConversion)
9208     return true;
9209 
9210   //   -- the context is an initialization by user-defined conversion
9211   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9212   //      from the return type of F1 to the destination type (i.e.,
9213   //      the type of the entity being initialized) is a better
9214   //      conversion sequence than the standard conversion sequence
9215   //      from the return type of F2 to the destination type.
9216   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9217       Cand1.Function && Cand2.Function &&
9218       isa<CXXConversionDecl>(Cand1.Function) &&
9219       isa<CXXConversionDecl>(Cand2.Function)) {
9220     // First check whether we prefer one of the conversion functions over the
9221     // other. This only distinguishes the results in non-standard, extension
9222     // cases such as the conversion from a lambda closure type to a function
9223     // pointer or block.
9224     ImplicitConversionSequence::CompareKind Result =
9225         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9226     if (Result == ImplicitConversionSequence::Indistinguishable)
9227       Result = CompareStandardConversionSequences(S, Loc,
9228                                                   Cand1.FinalConversion,
9229                                                   Cand2.FinalConversion);
9230 
9231     if (Result != ImplicitConversionSequence::Indistinguishable)
9232       return Result == ImplicitConversionSequence::Better;
9233 
9234     // FIXME: Compare kind of reference binding if conversion functions
9235     // convert to a reference type used in direct reference binding, per
9236     // C++14 [over.match.best]p1 section 2 bullet 3.
9237   }
9238 
9239   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9240   // as combined with the resolution to CWG issue 243.
9241   //
9242   // When the context is initialization by constructor ([over.match.ctor] or
9243   // either phase of [over.match.list]), a constructor is preferred over
9244   // a conversion function.
9245   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9246       Cand1.Function && Cand2.Function &&
9247       isa<CXXConstructorDecl>(Cand1.Function) !=
9248           isa<CXXConstructorDecl>(Cand2.Function))
9249     return isa<CXXConstructorDecl>(Cand1.Function);
9250 
9251   //    -- F1 is a non-template function and F2 is a function template
9252   //       specialization, or, if not that,
9253   bool Cand1IsSpecialization = Cand1.Function &&
9254                                Cand1.Function->getPrimaryTemplate();
9255   bool Cand2IsSpecialization = Cand2.Function &&
9256                                Cand2.Function->getPrimaryTemplate();
9257   if (Cand1IsSpecialization != Cand2IsSpecialization)
9258     return Cand2IsSpecialization;
9259 
9260   //   -- F1 and F2 are function template specializations, and the function
9261   //      template for F1 is more specialized than the template for F2
9262   //      according to the partial ordering rules described in 14.5.5.2, or,
9263   //      if not that,
9264   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9265     if (FunctionTemplateDecl *BetterTemplate
9266           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9267                                          Cand2.Function->getPrimaryTemplate(),
9268                                          Loc,
9269                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9270                                                              : TPOC_Call,
9271                                          Cand1.ExplicitCallArguments,
9272                                          Cand2.ExplicitCallArguments))
9273       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9274   }
9275 
9276   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9277   // A derived-class constructor beats an (inherited) base class constructor.
9278   bool Cand1IsInherited =
9279       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9280   bool Cand2IsInherited =
9281       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9282   if (Cand1IsInherited != Cand2IsInherited)
9283     return Cand2IsInherited;
9284   else if (Cand1IsInherited) {
9285     assert(Cand2IsInherited);
9286     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9287     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9288     if (Cand1Class->isDerivedFrom(Cand2Class))
9289       return true;
9290     if (Cand2Class->isDerivedFrom(Cand1Class))
9291       return false;
9292     // Inherited from sibling base classes: still ambiguous.
9293   }
9294 
9295   // Check C++17 tie-breakers for deduction guides.
9296   {
9297     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9298     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9299     if (Guide1 && Guide2) {
9300       //  -- F1 is generated from a deduction-guide and F2 is not
9301       if (Guide1->isImplicit() != Guide2->isImplicit())
9302         return Guide2->isImplicit();
9303 
9304       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9305       if (Guide1->isCopyDeductionCandidate())
9306         return true;
9307     }
9308   }
9309 
9310   // Check for enable_if value-based overload resolution.
9311   if (Cand1.Function && Cand2.Function) {
9312     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9313     if (Cmp != Comparison::Equal)
9314       return Cmp == Comparison::Better;
9315   }
9316 
9317   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9318     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9319     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9320            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9321   }
9322 
9323   bool HasPS1 = Cand1.Function != nullptr &&
9324                 functionHasPassObjectSizeParams(Cand1.Function);
9325   bool HasPS2 = Cand2.Function != nullptr &&
9326                 functionHasPassObjectSizeParams(Cand2.Function);
9327   if (HasPS1 != HasPS2 && HasPS1)
9328     return true;
9329 
9330   return isBetterMultiversionCandidate(Cand1, Cand2);
9331 }
9332 
9333 /// Determine whether two declarations are "equivalent" for the purposes of
9334 /// name lookup and overload resolution. This applies when the same internal/no
9335 /// linkage entity is defined by two modules (probably by textually including
9336 /// the same header). In such a case, we don't consider the declarations to
9337 /// declare the same entity, but we also don't want lookups with both
9338 /// declarations visible to be ambiguous in some cases (this happens when using
9339 /// a modularized libstdc++).
9340 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9341                                                   const NamedDecl *B) {
9342   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9343   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9344   if (!VA || !VB)
9345     return false;
9346 
9347   // The declarations must be declaring the same name as an internal linkage
9348   // entity in different modules.
9349   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9350           VB->getDeclContext()->getRedeclContext()) ||
9351       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9352           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9353       VA->isExternallyVisible() || VB->isExternallyVisible())
9354     return false;
9355 
9356   // Check that the declarations appear to be equivalent.
9357   //
9358   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9359   // For constants and functions, we should check the initializer or body is
9360   // the same. For non-constant variables, we shouldn't allow it at all.
9361   if (Context.hasSameType(VA->getType(), VB->getType()))
9362     return true;
9363 
9364   // Enum constants within unnamed enumerations will have different types, but
9365   // may still be similar enough to be interchangeable for our purposes.
9366   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9367     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9368       // Only handle anonymous enums. If the enumerations were named and
9369       // equivalent, they would have been merged to the same type.
9370       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9371       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9372       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9373           !Context.hasSameType(EnumA->getIntegerType(),
9374                                EnumB->getIntegerType()))
9375         return false;
9376       // Allow this only if the value is the same for both enumerators.
9377       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9378     }
9379   }
9380 
9381   // Nothing else is sufficiently similar.
9382   return false;
9383 }
9384 
9385 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9386     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9387   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9388 
9389   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9390   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9391       << !M << (M ? M->getFullModuleName() : "");
9392 
9393   for (auto *E : Equiv) {
9394     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9395     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9396         << !M << (M ? M->getFullModuleName() : "");
9397   }
9398 }
9399 
9400 /// Computes the best viable function (C++ 13.3.3)
9401 /// within an overload candidate set.
9402 ///
9403 /// \param Loc The location of the function name (or operator symbol) for
9404 /// which overload resolution occurs.
9405 ///
9406 /// \param Best If overload resolution was successful or found a deleted
9407 /// function, \p Best points to the candidate function found.
9408 ///
9409 /// \returns The result of overload resolution.
9410 OverloadingResult
9411 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9412                                          iterator &Best) {
9413   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9414   std::transform(begin(), end(), std::back_inserter(Candidates),
9415                  [](OverloadCandidate &Cand) { return &Cand; });
9416 
9417   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9418   // are accepted by both clang and NVCC. However, during a particular
9419   // compilation mode only one call variant is viable. We need to
9420   // exclude non-viable overload candidates from consideration based
9421   // only on their host/device attributes. Specifically, if one
9422   // candidate call is WrongSide and the other is SameSide, we ignore
9423   // the WrongSide candidate.
9424   if (S.getLangOpts().CUDA) {
9425     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9426     bool ContainsSameSideCandidate =
9427         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9428           return Cand->Function &&
9429                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9430                      Sema::CFP_SameSide;
9431         });
9432     if (ContainsSameSideCandidate) {
9433       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9434         return Cand->Function &&
9435                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9436                    Sema::CFP_WrongSide;
9437       };
9438       llvm::erase_if(Candidates, IsWrongSideCandidate);
9439     }
9440   }
9441 
9442   // Find the best viable function.
9443   Best = end();
9444   for (auto *Cand : Candidates)
9445     if (Cand->Viable)
9446       if (Best == end() ||
9447           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9448         Best = Cand;
9449 
9450   // If we didn't find any viable functions, abort.
9451   if (Best == end())
9452     return OR_No_Viable_Function;
9453 
9454   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9455 
9456   // Make sure that this function is better than every other viable
9457   // function. If not, we have an ambiguity.
9458   for (auto *Cand : Candidates) {
9459     if (Cand->Viable && Cand != Best &&
9460         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9461       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9462                                                    Cand->Function)) {
9463         EquivalentCands.push_back(Cand->Function);
9464         continue;
9465       }
9466 
9467       Best = end();
9468       return OR_Ambiguous;
9469     }
9470   }
9471 
9472   // Best is the best viable function.
9473   if (Best->Function && Best->Function->isDeleted())
9474     return OR_Deleted;
9475 
9476   if (!EquivalentCands.empty())
9477     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9478                                                     EquivalentCands);
9479 
9480   return OR_Success;
9481 }
9482 
9483 namespace {
9484 
9485 enum OverloadCandidateKind {
9486   oc_function,
9487   oc_method,
9488   oc_constructor,
9489   oc_implicit_default_constructor,
9490   oc_implicit_copy_constructor,
9491   oc_implicit_move_constructor,
9492   oc_implicit_copy_assignment,
9493   oc_implicit_move_assignment,
9494   oc_inherited_constructor
9495 };
9496 
9497 enum OverloadCandidateSelect {
9498   ocs_non_template,
9499   ocs_template,
9500   ocs_described_template,
9501 };
9502 
9503 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9504 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9505                           std::string &Description) {
9506 
9507   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9508   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9509     isTemplate = true;
9510     Description = S.getTemplateArgumentBindingsText(
9511         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9512   }
9513 
9514   OverloadCandidateSelect Select = [&]() {
9515     if (!Description.empty())
9516       return ocs_described_template;
9517     return isTemplate ? ocs_template : ocs_non_template;
9518   }();
9519 
9520   OverloadCandidateKind Kind = [&]() {
9521     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9522       if (!Ctor->isImplicit()) {
9523         if (isa<ConstructorUsingShadowDecl>(Found))
9524           return oc_inherited_constructor;
9525         else
9526           return oc_constructor;
9527       }
9528 
9529       if (Ctor->isDefaultConstructor())
9530         return oc_implicit_default_constructor;
9531 
9532       if (Ctor->isMoveConstructor())
9533         return oc_implicit_move_constructor;
9534 
9535       assert(Ctor->isCopyConstructor() &&
9536              "unexpected sort of implicit constructor");
9537       return oc_implicit_copy_constructor;
9538     }
9539 
9540     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9541       // This actually gets spelled 'candidate function' for now, but
9542       // it doesn't hurt to split it out.
9543       if (!Meth->isImplicit())
9544         return oc_method;
9545 
9546       if (Meth->isMoveAssignmentOperator())
9547         return oc_implicit_move_assignment;
9548 
9549       if (Meth->isCopyAssignmentOperator())
9550         return oc_implicit_copy_assignment;
9551 
9552       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9553       return oc_method;
9554     }
9555 
9556     return oc_function;
9557   }();
9558 
9559   return std::make_pair(Kind, Select);
9560 }
9561 
9562 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9563   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9564   // set.
9565   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9566     S.Diag(FoundDecl->getLocation(),
9567            diag::note_ovl_candidate_inherited_constructor)
9568       << Shadow->getNominatedBaseClass();
9569 }
9570 
9571 } // end anonymous namespace
9572 
9573 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9574                                     const FunctionDecl *FD) {
9575   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9576     bool AlwaysTrue;
9577     if (EnableIf->getCond()->isValueDependent() ||
9578         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9579       return false;
9580     if (!AlwaysTrue)
9581       return false;
9582   }
9583   return true;
9584 }
9585 
9586 /// Returns true if we can take the address of the function.
9587 ///
9588 /// \param Complain - If true, we'll emit a diagnostic
9589 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9590 ///   we in overload resolution?
9591 /// \param Loc - The location of the statement we're complaining about. Ignored
9592 ///   if we're not complaining, or if we're in overload resolution.
9593 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9594                                               bool Complain,
9595                                               bool InOverloadResolution,
9596                                               SourceLocation Loc) {
9597   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9598     if (Complain) {
9599       if (InOverloadResolution)
9600         S.Diag(FD->getBeginLoc(),
9601                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9602       else
9603         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9604     }
9605     return false;
9606   }
9607 
9608   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9609     return P->hasAttr<PassObjectSizeAttr>();
9610   });
9611   if (I == FD->param_end())
9612     return true;
9613 
9614   if (Complain) {
9615     // Add one to ParamNo because it's user-facing
9616     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9617     if (InOverloadResolution)
9618       S.Diag(FD->getLocation(),
9619              diag::note_ovl_candidate_has_pass_object_size_params)
9620           << ParamNo;
9621     else
9622       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9623           << FD << ParamNo;
9624   }
9625   return false;
9626 }
9627 
9628 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9629                                                const FunctionDecl *FD) {
9630   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9631                                            /*InOverloadResolution=*/true,
9632                                            /*Loc=*/SourceLocation());
9633 }
9634 
9635 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9636                                              bool Complain,
9637                                              SourceLocation Loc) {
9638   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9639                                              /*InOverloadResolution=*/false,
9640                                              Loc);
9641 }
9642 
9643 // Notes the location of an overload candidate.
9644 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9645                                  QualType DestType, bool TakingAddress) {
9646   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9647     return;
9648   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9649       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9650     return;
9651 
9652   std::string FnDesc;
9653   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9654       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9655   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9656                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9657                          << Fn << FnDesc;
9658 
9659   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9660   Diag(Fn->getLocation(), PD);
9661   MaybeEmitInheritedConstructorNote(*this, Found);
9662 }
9663 
9664 // Notes the location of all overload candidates designated through
9665 // OverloadedExpr
9666 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9667                                      bool TakingAddress) {
9668   assert(OverloadedExpr->getType() == Context.OverloadTy);
9669 
9670   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9671   OverloadExpr *OvlExpr = Ovl.Expression;
9672 
9673   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9674                             IEnd = OvlExpr->decls_end();
9675        I != IEnd; ++I) {
9676     if (FunctionTemplateDecl *FunTmpl =
9677                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9678       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9679                             TakingAddress);
9680     } else if (FunctionDecl *Fun
9681                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9682       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9683     }
9684   }
9685 }
9686 
9687 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9688 /// "lead" diagnostic; it will be given two arguments, the source and
9689 /// target types of the conversion.
9690 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9691                                  Sema &S,
9692                                  SourceLocation CaretLoc,
9693                                  const PartialDiagnostic &PDiag) const {
9694   S.Diag(CaretLoc, PDiag)
9695     << Ambiguous.getFromType() << Ambiguous.getToType();
9696   // FIXME: The note limiting machinery is borrowed from
9697   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9698   // refactoring here.
9699   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9700   unsigned CandsShown = 0;
9701   AmbiguousConversionSequence::const_iterator I, E;
9702   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9703     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9704       break;
9705     ++CandsShown;
9706     S.NoteOverloadCandidate(I->first, I->second);
9707   }
9708   if (I != E)
9709     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9710 }
9711 
9712 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9713                                   unsigned I, bool TakingCandidateAddress) {
9714   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9715   assert(Conv.isBad());
9716   assert(Cand->Function && "for now, candidate must be a function");
9717   FunctionDecl *Fn = Cand->Function;
9718 
9719   // There's a conversion slot for the object argument if this is a
9720   // non-constructor method.  Note that 'I' corresponds the
9721   // conversion-slot index.
9722   bool isObjectArgument = false;
9723   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9724     if (I == 0)
9725       isObjectArgument = true;
9726     else
9727       I--;
9728   }
9729 
9730   std::string FnDesc;
9731   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9732       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9733 
9734   Expr *FromExpr = Conv.Bad.FromExpr;
9735   QualType FromTy = Conv.Bad.getFromType();
9736   QualType ToTy = Conv.Bad.getToType();
9737 
9738   if (FromTy == S.Context.OverloadTy) {
9739     assert(FromExpr && "overload set argument came from implicit argument?");
9740     Expr *E = FromExpr->IgnoreParens();
9741     if (isa<UnaryOperator>(E))
9742       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9743     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9744 
9745     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9746         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9747         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9748         << Name << I + 1;
9749     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9750     return;
9751   }
9752 
9753   // Do some hand-waving analysis to see if the non-viability is due
9754   // to a qualifier mismatch.
9755   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9756   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9757   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9758     CToTy = RT->getPointeeType();
9759   else {
9760     // TODO: detect and diagnose the full richness of const mismatches.
9761     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9762       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9763         CFromTy = FromPT->getPointeeType();
9764         CToTy = ToPT->getPointeeType();
9765       }
9766   }
9767 
9768   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9769       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9770     Qualifiers FromQs = CFromTy.getQualifiers();
9771     Qualifiers ToQs = CToTy.getQualifiers();
9772 
9773     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9774       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9775           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9776           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9777           << ToTy << (unsigned)isObjectArgument << I + 1;
9778       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9779       return;
9780     }
9781 
9782     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9783       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9784           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9785           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9786           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9787           << (unsigned)isObjectArgument << I + 1;
9788       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9789       return;
9790     }
9791 
9792     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9793       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9794           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9795           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9796           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9797           << (unsigned)isObjectArgument << I + 1;
9798       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9799       return;
9800     }
9801 
9802     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9803       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9804           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9805           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9806           << FromQs.hasUnaligned() << I + 1;
9807       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9808       return;
9809     }
9810 
9811     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9812     assert(CVR && "unexpected qualifiers mismatch");
9813 
9814     if (isObjectArgument) {
9815       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9816           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9817           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9818           << (CVR - 1);
9819     } else {
9820       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9821           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9822           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9823           << (CVR - 1) << I + 1;
9824     }
9825     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9826     return;
9827   }
9828 
9829   // Special diagnostic for failure to convert an initializer list, since
9830   // telling the user that it has type void is not useful.
9831   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9832     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9833         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9834         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9835         << ToTy << (unsigned)isObjectArgument << I + 1;
9836     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9837     return;
9838   }
9839 
9840   // Diagnose references or pointers to incomplete types differently,
9841   // since it's far from impossible that the incompleteness triggered
9842   // the failure.
9843   QualType TempFromTy = FromTy.getNonReferenceType();
9844   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9845     TempFromTy = PTy->getPointeeType();
9846   if (TempFromTy->isIncompleteType()) {
9847     // Emit the generic diagnostic and, optionally, add the hints to it.
9848     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9849         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9850         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9851         << ToTy << (unsigned)isObjectArgument << I + 1
9852         << (unsigned)(Cand->Fix.Kind);
9853 
9854     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9855     return;
9856   }
9857 
9858   // Diagnose base -> derived pointer conversions.
9859   unsigned BaseToDerivedConversion = 0;
9860   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9861     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9862       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9863                                                FromPtrTy->getPointeeType()) &&
9864           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9865           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9866           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9867                           FromPtrTy->getPointeeType()))
9868         BaseToDerivedConversion = 1;
9869     }
9870   } else if (const ObjCObjectPointerType *FromPtrTy
9871                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9872     if (const ObjCObjectPointerType *ToPtrTy
9873                                         = ToTy->getAs<ObjCObjectPointerType>())
9874       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9875         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9876           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9877                                                 FromPtrTy->getPointeeType()) &&
9878               FromIface->isSuperClassOf(ToIface))
9879             BaseToDerivedConversion = 2;
9880   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9881     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9882         !FromTy->isIncompleteType() &&
9883         !ToRefTy->getPointeeType()->isIncompleteType() &&
9884         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9885       BaseToDerivedConversion = 3;
9886     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9887                ToTy.getNonReferenceType().getCanonicalType() ==
9888                FromTy.getNonReferenceType().getCanonicalType()) {
9889       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9890           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9891           << (unsigned)isObjectArgument << I + 1
9892           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9893       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9894       return;
9895     }
9896   }
9897 
9898   if (BaseToDerivedConversion) {
9899     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9900         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9901         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9902         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9903     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9904     return;
9905   }
9906 
9907   if (isa<ObjCObjectPointerType>(CFromTy) &&
9908       isa<PointerType>(CToTy)) {
9909       Qualifiers FromQs = CFromTy.getQualifiers();
9910       Qualifiers ToQs = CToTy.getQualifiers();
9911       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9912         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9913             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9914             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9915             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9916         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9917         return;
9918       }
9919   }
9920 
9921   if (TakingCandidateAddress &&
9922       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9923     return;
9924 
9925   // Emit the generic diagnostic and, optionally, add the hints to it.
9926   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9927   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9928         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9929         << ToTy << (unsigned)isObjectArgument << I + 1
9930         << (unsigned)(Cand->Fix.Kind);
9931 
9932   // If we can fix the conversion, suggest the FixIts.
9933   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9934        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9935     FDiag << *HI;
9936   S.Diag(Fn->getLocation(), FDiag);
9937 
9938   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9939 }
9940 
9941 /// Additional arity mismatch diagnosis specific to a function overload
9942 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9943 /// over a candidate in any candidate set.
9944 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9945                                unsigned NumArgs) {
9946   FunctionDecl *Fn = Cand->Function;
9947   unsigned MinParams = Fn->getMinRequiredArguments();
9948 
9949   // With invalid overloaded operators, it's possible that we think we
9950   // have an arity mismatch when in fact it looks like we have the
9951   // right number of arguments, because only overloaded operators have
9952   // the weird behavior of overloading member and non-member functions.
9953   // Just don't report anything.
9954   if (Fn->isInvalidDecl() &&
9955       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9956     return true;
9957 
9958   if (NumArgs < MinParams) {
9959     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9960            (Cand->FailureKind == ovl_fail_bad_deduction &&
9961             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9962   } else {
9963     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9964            (Cand->FailureKind == ovl_fail_bad_deduction &&
9965             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9966   }
9967 
9968   return false;
9969 }
9970 
9971 /// General arity mismatch diagnosis over a candidate in a candidate set.
9972 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9973                                   unsigned NumFormalArgs) {
9974   assert(isa<FunctionDecl>(D) &&
9975       "The templated declaration should at least be a function"
9976       " when diagnosing bad template argument deduction due to too many"
9977       " or too few arguments");
9978 
9979   FunctionDecl *Fn = cast<FunctionDecl>(D);
9980 
9981   // TODO: treat calls to a missing default constructor as a special case
9982   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9983   unsigned MinParams = Fn->getMinRequiredArguments();
9984 
9985   // at least / at most / exactly
9986   unsigned mode, modeCount;
9987   if (NumFormalArgs < MinParams) {
9988     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9989         FnTy->isTemplateVariadic())
9990       mode = 0; // "at least"
9991     else
9992       mode = 2; // "exactly"
9993     modeCount = MinParams;
9994   } else {
9995     if (MinParams != FnTy->getNumParams())
9996       mode = 1; // "at most"
9997     else
9998       mode = 2; // "exactly"
9999     modeCount = FnTy->getNumParams();
10000   }
10001 
10002   std::string Description;
10003   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10004       ClassifyOverloadCandidate(S, Found, Fn, Description);
10005 
10006   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10007     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10008         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10009         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10010   else
10011     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10012         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10013         << Description << mode << modeCount << NumFormalArgs;
10014 
10015   MaybeEmitInheritedConstructorNote(S, Found);
10016 }
10017 
10018 /// Arity mismatch diagnosis specific to a function overload candidate.
10019 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10020                                   unsigned NumFormalArgs) {
10021   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10022     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10023 }
10024 
10025 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10026   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10027     return TD;
10028   llvm_unreachable("Unsupported: Getting the described template declaration"
10029                    " for bad deduction diagnosis");
10030 }
10031 
10032 /// Diagnose a failed template-argument deduction.
10033 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10034                                  DeductionFailureInfo &DeductionFailure,
10035                                  unsigned NumArgs,
10036                                  bool TakingCandidateAddress) {
10037   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10038   NamedDecl *ParamD;
10039   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10040   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10041   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10042   switch (DeductionFailure.Result) {
10043   case Sema::TDK_Success:
10044     llvm_unreachable("TDK_success while diagnosing bad deduction");
10045 
10046   case Sema::TDK_Incomplete: {
10047     assert(ParamD && "no parameter found for incomplete deduction result");
10048     S.Diag(Templated->getLocation(),
10049            diag::note_ovl_candidate_incomplete_deduction)
10050         << ParamD->getDeclName();
10051     MaybeEmitInheritedConstructorNote(S, Found);
10052     return;
10053   }
10054 
10055   case Sema::TDK_IncompletePack: {
10056     assert(ParamD && "no parameter found for incomplete deduction result");
10057     S.Diag(Templated->getLocation(),
10058            diag::note_ovl_candidate_incomplete_deduction_pack)
10059         << ParamD->getDeclName()
10060         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10061         << *DeductionFailure.getFirstArg();
10062     MaybeEmitInheritedConstructorNote(S, Found);
10063     return;
10064   }
10065 
10066   case Sema::TDK_Underqualified: {
10067     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10068     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10069 
10070     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10071 
10072     // Param will have been canonicalized, but it should just be a
10073     // qualified version of ParamD, so move the qualifiers to that.
10074     QualifierCollector Qs;
10075     Qs.strip(Param);
10076     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10077     assert(S.Context.hasSameType(Param, NonCanonParam));
10078 
10079     // Arg has also been canonicalized, but there's nothing we can do
10080     // about that.  It also doesn't matter as much, because it won't
10081     // have any template parameters in it (because deduction isn't
10082     // done on dependent types).
10083     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10084 
10085     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10086         << ParamD->getDeclName() << Arg << NonCanonParam;
10087     MaybeEmitInheritedConstructorNote(S, Found);
10088     return;
10089   }
10090 
10091   case Sema::TDK_Inconsistent: {
10092     assert(ParamD && "no parameter found for inconsistent deduction result");
10093     int which = 0;
10094     if (isa<TemplateTypeParmDecl>(ParamD))
10095       which = 0;
10096     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10097       // Deduction might have failed because we deduced arguments of two
10098       // different types for a non-type template parameter.
10099       // FIXME: Use a different TDK value for this.
10100       QualType T1 =
10101           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10102       QualType T2 =
10103           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10104       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10105         S.Diag(Templated->getLocation(),
10106                diag::note_ovl_candidate_inconsistent_deduction_types)
10107           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10108           << *DeductionFailure.getSecondArg() << T2;
10109         MaybeEmitInheritedConstructorNote(S, Found);
10110         return;
10111       }
10112 
10113       which = 1;
10114     } else {
10115       which = 2;
10116     }
10117 
10118     S.Diag(Templated->getLocation(),
10119            diag::note_ovl_candidate_inconsistent_deduction)
10120         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10121         << *DeductionFailure.getSecondArg();
10122     MaybeEmitInheritedConstructorNote(S, Found);
10123     return;
10124   }
10125 
10126   case Sema::TDK_InvalidExplicitArguments:
10127     assert(ParamD && "no parameter found for invalid explicit arguments");
10128     if (ParamD->getDeclName())
10129       S.Diag(Templated->getLocation(),
10130              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10131           << ParamD->getDeclName();
10132     else {
10133       int index = 0;
10134       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10135         index = TTP->getIndex();
10136       else if (NonTypeTemplateParmDecl *NTTP
10137                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10138         index = NTTP->getIndex();
10139       else
10140         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10141       S.Diag(Templated->getLocation(),
10142              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10143           << (index + 1);
10144     }
10145     MaybeEmitInheritedConstructorNote(S, Found);
10146     return;
10147 
10148   case Sema::TDK_TooManyArguments:
10149   case Sema::TDK_TooFewArguments:
10150     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10151     return;
10152 
10153   case Sema::TDK_InstantiationDepth:
10154     S.Diag(Templated->getLocation(),
10155            diag::note_ovl_candidate_instantiation_depth);
10156     MaybeEmitInheritedConstructorNote(S, Found);
10157     return;
10158 
10159   case Sema::TDK_SubstitutionFailure: {
10160     // Format the template argument list into the argument string.
10161     SmallString<128> TemplateArgString;
10162     if (TemplateArgumentList *Args =
10163             DeductionFailure.getTemplateArgumentList()) {
10164       TemplateArgString = " ";
10165       TemplateArgString += S.getTemplateArgumentBindingsText(
10166           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10167     }
10168 
10169     // If this candidate was disabled by enable_if, say so.
10170     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10171     if (PDiag && PDiag->second.getDiagID() ==
10172           diag::err_typename_nested_not_found_enable_if) {
10173       // FIXME: Use the source range of the condition, and the fully-qualified
10174       //        name of the enable_if template. These are both present in PDiag.
10175       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10176         << "'enable_if'" << TemplateArgString;
10177       return;
10178     }
10179 
10180     // We found a specific requirement that disabled the enable_if.
10181     if (PDiag && PDiag->second.getDiagID() ==
10182         diag::err_typename_nested_not_found_requirement) {
10183       S.Diag(Templated->getLocation(),
10184              diag::note_ovl_candidate_disabled_by_requirement)
10185         << PDiag->second.getStringArg(0) << TemplateArgString;
10186       return;
10187     }
10188 
10189     // Format the SFINAE diagnostic into the argument string.
10190     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10191     //        formatted message in another diagnostic.
10192     SmallString<128> SFINAEArgString;
10193     SourceRange R;
10194     if (PDiag) {
10195       SFINAEArgString = ": ";
10196       R = SourceRange(PDiag->first, PDiag->first);
10197       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10198     }
10199 
10200     S.Diag(Templated->getLocation(),
10201            diag::note_ovl_candidate_substitution_failure)
10202         << TemplateArgString << SFINAEArgString << R;
10203     MaybeEmitInheritedConstructorNote(S, Found);
10204     return;
10205   }
10206 
10207   case Sema::TDK_DeducedMismatch:
10208   case Sema::TDK_DeducedMismatchNested: {
10209     // Format the template argument list into the argument string.
10210     SmallString<128> TemplateArgString;
10211     if (TemplateArgumentList *Args =
10212             DeductionFailure.getTemplateArgumentList()) {
10213       TemplateArgString = " ";
10214       TemplateArgString += S.getTemplateArgumentBindingsText(
10215           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10216     }
10217 
10218     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10219         << (*DeductionFailure.getCallArgIndex() + 1)
10220         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10221         << TemplateArgString
10222         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10223     break;
10224   }
10225 
10226   case Sema::TDK_NonDeducedMismatch: {
10227     // FIXME: Provide a source location to indicate what we couldn't match.
10228     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10229     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10230     if (FirstTA.getKind() == TemplateArgument::Template &&
10231         SecondTA.getKind() == TemplateArgument::Template) {
10232       TemplateName FirstTN = FirstTA.getAsTemplate();
10233       TemplateName SecondTN = SecondTA.getAsTemplate();
10234       if (FirstTN.getKind() == TemplateName::Template &&
10235           SecondTN.getKind() == TemplateName::Template) {
10236         if (FirstTN.getAsTemplateDecl()->getName() ==
10237             SecondTN.getAsTemplateDecl()->getName()) {
10238           // FIXME: This fixes a bad diagnostic where both templates are named
10239           // the same.  This particular case is a bit difficult since:
10240           // 1) It is passed as a string to the diagnostic printer.
10241           // 2) The diagnostic printer only attempts to find a better
10242           //    name for types, not decls.
10243           // Ideally, this should folded into the diagnostic printer.
10244           S.Diag(Templated->getLocation(),
10245                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10246               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10247           return;
10248         }
10249       }
10250     }
10251 
10252     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10253         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10254       return;
10255 
10256     // FIXME: For generic lambda parameters, check if the function is a lambda
10257     // call operator, and if so, emit a prettier and more informative
10258     // diagnostic that mentions 'auto' and lambda in addition to
10259     // (or instead of?) the canonical template type parameters.
10260     S.Diag(Templated->getLocation(),
10261            diag::note_ovl_candidate_non_deduced_mismatch)
10262         << FirstTA << SecondTA;
10263     return;
10264   }
10265   // TODO: diagnose these individually, then kill off
10266   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10267   case Sema::TDK_MiscellaneousDeductionFailure:
10268     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10269     MaybeEmitInheritedConstructorNote(S, Found);
10270     return;
10271   case Sema::TDK_CUDATargetMismatch:
10272     S.Diag(Templated->getLocation(),
10273            diag::note_cuda_ovl_candidate_target_mismatch);
10274     return;
10275   }
10276 }
10277 
10278 /// Diagnose a failed template-argument deduction, for function calls.
10279 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10280                                  unsigned NumArgs,
10281                                  bool TakingCandidateAddress) {
10282   unsigned TDK = Cand->DeductionFailure.Result;
10283   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10284     if (CheckArityMismatch(S, Cand, NumArgs))
10285       return;
10286   }
10287   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10288                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10289 }
10290 
10291 /// CUDA: diagnose an invalid call across targets.
10292 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10293   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10294   FunctionDecl *Callee = Cand->Function;
10295 
10296   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10297                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10298 
10299   std::string FnDesc;
10300   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10301       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10302 
10303   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10304       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10305       << FnDesc /* Ignored */
10306       << CalleeTarget << CallerTarget;
10307 
10308   // This could be an implicit constructor for which we could not infer the
10309   // target due to a collsion. Diagnose that case.
10310   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10311   if (Meth != nullptr && Meth->isImplicit()) {
10312     CXXRecordDecl *ParentClass = Meth->getParent();
10313     Sema::CXXSpecialMember CSM;
10314 
10315     switch (FnKindPair.first) {
10316     default:
10317       return;
10318     case oc_implicit_default_constructor:
10319       CSM = Sema::CXXDefaultConstructor;
10320       break;
10321     case oc_implicit_copy_constructor:
10322       CSM = Sema::CXXCopyConstructor;
10323       break;
10324     case oc_implicit_move_constructor:
10325       CSM = Sema::CXXMoveConstructor;
10326       break;
10327     case oc_implicit_copy_assignment:
10328       CSM = Sema::CXXCopyAssignment;
10329       break;
10330     case oc_implicit_move_assignment:
10331       CSM = Sema::CXXMoveAssignment;
10332       break;
10333     };
10334 
10335     bool ConstRHS = false;
10336     if (Meth->getNumParams()) {
10337       if (const ReferenceType *RT =
10338               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10339         ConstRHS = RT->getPointeeType().isConstQualified();
10340       }
10341     }
10342 
10343     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10344                                               /* ConstRHS */ ConstRHS,
10345                                               /* Diagnose */ true);
10346   }
10347 }
10348 
10349 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10350   FunctionDecl *Callee = Cand->Function;
10351   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10352 
10353   S.Diag(Callee->getLocation(),
10354          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10355       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10356 }
10357 
10358 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10359   ExplicitSpecifier ES;
10360   const char *DeclName;
10361   switch (Cand->Function->getDeclKind()) {
10362   case Decl::Kind::CXXConstructor:
10363     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10364     DeclName = "constructor";
10365     break;
10366   case Decl::Kind::CXXConversion:
10367     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10368     DeclName = "conversion operator";
10369     break;
10370   case Decl::Kind::CXXDeductionGuide:
10371     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10372     DeclName = "deductiong guide";
10373     break;
10374   default:
10375     llvm_unreachable("invalid Decl");
10376   }
10377   assert(ES.getExpr() && "null expression should be handled before");
10378   S.Diag(Cand->Function->getLocation(),
10379          diag::note_ovl_candidate_explicit_forbidden)
10380       << DeclName;
10381   S.Diag(ES.getExpr()->getBeginLoc(),
10382          diag::note_explicit_bool_resolved_to_true);
10383 }
10384 
10385 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10386   FunctionDecl *Callee = Cand->Function;
10387 
10388   S.Diag(Callee->getLocation(),
10389          diag::note_ovl_candidate_disabled_by_extension)
10390     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10391 }
10392 
10393 /// Generates a 'note' diagnostic for an overload candidate.  We've
10394 /// already generated a primary error at the call site.
10395 ///
10396 /// It really does need to be a single diagnostic with its caret
10397 /// pointed at the candidate declaration.  Yes, this creates some
10398 /// major challenges of technical writing.  Yes, this makes pointing
10399 /// out problems with specific arguments quite awkward.  It's still
10400 /// better than generating twenty screens of text for every failed
10401 /// overload.
10402 ///
10403 /// It would be great to be able to express per-candidate problems
10404 /// more richly for those diagnostic clients that cared, but we'd
10405 /// still have to be just as careful with the default diagnostics.
10406 /// \param CtorDestAS Addr space of object being constructed (for ctor
10407 /// candidates only).
10408 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10409                                   unsigned NumArgs,
10410                                   bool TakingCandidateAddress,
10411                                   LangAS CtorDestAS = LangAS::Default) {
10412   FunctionDecl *Fn = Cand->Function;
10413 
10414   // Note deleted candidates, but only if they're viable.
10415   if (Cand->Viable) {
10416     if (Fn->isDeleted()) {
10417       std::string FnDesc;
10418       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10419           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10420 
10421       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10422           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10423           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10424       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10425       return;
10426     }
10427 
10428     // We don't really have anything else to say about viable candidates.
10429     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10430     return;
10431   }
10432 
10433   switch (Cand->FailureKind) {
10434   case ovl_fail_too_many_arguments:
10435   case ovl_fail_too_few_arguments:
10436     return DiagnoseArityMismatch(S, Cand, NumArgs);
10437 
10438   case ovl_fail_bad_deduction:
10439     return DiagnoseBadDeduction(S, Cand, NumArgs,
10440                                 TakingCandidateAddress);
10441 
10442   case ovl_fail_illegal_constructor: {
10443     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10444       << (Fn->getPrimaryTemplate() ? 1 : 0);
10445     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10446     return;
10447   }
10448 
10449   case ovl_fail_object_addrspace_mismatch: {
10450     Qualifiers QualsForPrinting;
10451     QualsForPrinting.setAddressSpace(CtorDestAS);
10452     S.Diag(Fn->getLocation(),
10453            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10454         << QualsForPrinting;
10455     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10456     return;
10457   }
10458 
10459   case ovl_fail_trivial_conversion:
10460   case ovl_fail_bad_final_conversion:
10461   case ovl_fail_final_conversion_not_exact:
10462     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10463 
10464   case ovl_fail_bad_conversion: {
10465     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10466     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10467       if (Cand->Conversions[I].isBad())
10468         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10469 
10470     // FIXME: this currently happens when we're called from SemaInit
10471     // when user-conversion overload fails.  Figure out how to handle
10472     // those conditions and diagnose them well.
10473     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10474   }
10475 
10476   case ovl_fail_bad_target:
10477     return DiagnoseBadTarget(S, Cand);
10478 
10479   case ovl_fail_enable_if:
10480     return DiagnoseFailedEnableIfAttr(S, Cand);
10481 
10482   case ovl_fail_explicit_resolved:
10483     return DiagnoseFailedExplicitSpec(S, Cand);
10484 
10485   case ovl_fail_ext_disabled:
10486     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10487 
10488   case ovl_fail_inhctor_slice:
10489     // It's generally not interesting to note copy/move constructors here.
10490     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10491       return;
10492     S.Diag(Fn->getLocation(),
10493            diag::note_ovl_candidate_inherited_constructor_slice)
10494       << (Fn->getPrimaryTemplate() ? 1 : 0)
10495       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10496     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10497     return;
10498 
10499   case ovl_fail_addr_not_available: {
10500     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10501     (void)Available;
10502     assert(!Available);
10503     break;
10504   }
10505   case ovl_non_default_multiversion_function:
10506     // Do nothing, these should simply be ignored.
10507     break;
10508   }
10509 }
10510 
10511 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10512   // Desugar the type of the surrogate down to a function type,
10513   // retaining as many typedefs as possible while still showing
10514   // the function type (and, therefore, its parameter types).
10515   QualType FnType = Cand->Surrogate->getConversionType();
10516   bool isLValueReference = false;
10517   bool isRValueReference = false;
10518   bool isPointer = false;
10519   if (const LValueReferenceType *FnTypeRef =
10520         FnType->getAs<LValueReferenceType>()) {
10521     FnType = FnTypeRef->getPointeeType();
10522     isLValueReference = true;
10523   } else if (const RValueReferenceType *FnTypeRef =
10524                FnType->getAs<RValueReferenceType>()) {
10525     FnType = FnTypeRef->getPointeeType();
10526     isRValueReference = true;
10527   }
10528   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10529     FnType = FnTypePtr->getPointeeType();
10530     isPointer = true;
10531   }
10532   // Desugar down to a function type.
10533   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10534   // Reconstruct the pointer/reference as appropriate.
10535   if (isPointer) FnType = S.Context.getPointerType(FnType);
10536   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10537   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10538 
10539   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10540     << FnType;
10541 }
10542 
10543 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10544                                          SourceLocation OpLoc,
10545                                          OverloadCandidate *Cand) {
10546   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10547   std::string TypeStr("operator");
10548   TypeStr += Opc;
10549   TypeStr += "(";
10550   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10551   if (Cand->Conversions.size() == 1) {
10552     TypeStr += ")";
10553     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10554   } else {
10555     TypeStr += ", ";
10556     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10557     TypeStr += ")";
10558     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10559   }
10560 }
10561 
10562 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10563                                          OverloadCandidate *Cand) {
10564   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10565     if (ICS.isBad()) break; // all meaningless after first invalid
10566     if (!ICS.isAmbiguous()) continue;
10567 
10568     ICS.DiagnoseAmbiguousConversion(
10569         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10570   }
10571 }
10572 
10573 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10574   if (Cand->Function)
10575     return Cand->Function->getLocation();
10576   if (Cand->IsSurrogate)
10577     return Cand->Surrogate->getLocation();
10578   return SourceLocation();
10579 }
10580 
10581 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10582   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10583   case Sema::TDK_Success:
10584   case Sema::TDK_NonDependentConversionFailure:
10585     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10586 
10587   case Sema::TDK_Invalid:
10588   case Sema::TDK_Incomplete:
10589   case Sema::TDK_IncompletePack:
10590     return 1;
10591 
10592   case Sema::TDK_Underqualified:
10593   case Sema::TDK_Inconsistent:
10594     return 2;
10595 
10596   case Sema::TDK_SubstitutionFailure:
10597   case Sema::TDK_DeducedMismatch:
10598   case Sema::TDK_DeducedMismatchNested:
10599   case Sema::TDK_NonDeducedMismatch:
10600   case Sema::TDK_MiscellaneousDeductionFailure:
10601   case Sema::TDK_CUDATargetMismatch:
10602     return 3;
10603 
10604   case Sema::TDK_InstantiationDepth:
10605     return 4;
10606 
10607   case Sema::TDK_InvalidExplicitArguments:
10608     return 5;
10609 
10610   case Sema::TDK_TooManyArguments:
10611   case Sema::TDK_TooFewArguments:
10612     return 6;
10613   }
10614   llvm_unreachable("Unhandled deduction result");
10615 }
10616 
10617 namespace {
10618 struct CompareOverloadCandidatesForDisplay {
10619   Sema &S;
10620   SourceLocation Loc;
10621   size_t NumArgs;
10622   OverloadCandidateSet::CandidateSetKind CSK;
10623 
10624   CompareOverloadCandidatesForDisplay(
10625       Sema &S, SourceLocation Loc, size_t NArgs,
10626       OverloadCandidateSet::CandidateSetKind CSK)
10627       : S(S), NumArgs(NArgs), CSK(CSK) {}
10628 
10629   bool operator()(const OverloadCandidate *L,
10630                   const OverloadCandidate *R) {
10631     // Fast-path this check.
10632     if (L == R) return false;
10633 
10634     // Order first by viability.
10635     if (L->Viable) {
10636       if (!R->Viable) return true;
10637 
10638       // TODO: introduce a tri-valued comparison for overload
10639       // candidates.  Would be more worthwhile if we had a sort
10640       // that could exploit it.
10641       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10642         return true;
10643       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10644         return false;
10645     } else if (R->Viable)
10646       return false;
10647 
10648     assert(L->Viable == R->Viable);
10649 
10650     // Criteria by which we can sort non-viable candidates:
10651     if (!L->Viable) {
10652       // 1. Arity mismatches come after other candidates.
10653       if (L->FailureKind == ovl_fail_too_many_arguments ||
10654           L->FailureKind == ovl_fail_too_few_arguments) {
10655         if (R->FailureKind == ovl_fail_too_many_arguments ||
10656             R->FailureKind == ovl_fail_too_few_arguments) {
10657           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10658           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10659           if (LDist == RDist) {
10660             if (L->FailureKind == R->FailureKind)
10661               // Sort non-surrogates before surrogates.
10662               return !L->IsSurrogate && R->IsSurrogate;
10663             // Sort candidates requiring fewer parameters than there were
10664             // arguments given after candidates requiring more parameters
10665             // than there were arguments given.
10666             return L->FailureKind == ovl_fail_too_many_arguments;
10667           }
10668           return LDist < RDist;
10669         }
10670         return false;
10671       }
10672       if (R->FailureKind == ovl_fail_too_many_arguments ||
10673           R->FailureKind == ovl_fail_too_few_arguments)
10674         return true;
10675 
10676       // 2. Bad conversions come first and are ordered by the number
10677       // of bad conversions and quality of good conversions.
10678       if (L->FailureKind == ovl_fail_bad_conversion) {
10679         if (R->FailureKind != ovl_fail_bad_conversion)
10680           return true;
10681 
10682         // The conversion that can be fixed with a smaller number of changes,
10683         // comes first.
10684         unsigned numLFixes = L->Fix.NumConversionsFixed;
10685         unsigned numRFixes = R->Fix.NumConversionsFixed;
10686         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10687         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10688         if (numLFixes != numRFixes) {
10689           return numLFixes < numRFixes;
10690         }
10691 
10692         // If there's any ordering between the defined conversions...
10693         // FIXME: this might not be transitive.
10694         assert(L->Conversions.size() == R->Conversions.size());
10695 
10696         int leftBetter = 0;
10697         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10698         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10699           switch (CompareImplicitConversionSequences(S, Loc,
10700                                                      L->Conversions[I],
10701                                                      R->Conversions[I])) {
10702           case ImplicitConversionSequence::Better:
10703             leftBetter++;
10704             break;
10705 
10706           case ImplicitConversionSequence::Worse:
10707             leftBetter--;
10708             break;
10709 
10710           case ImplicitConversionSequence::Indistinguishable:
10711             break;
10712           }
10713         }
10714         if (leftBetter > 0) return true;
10715         if (leftBetter < 0) return false;
10716 
10717       } else if (R->FailureKind == ovl_fail_bad_conversion)
10718         return false;
10719 
10720       if (L->FailureKind == ovl_fail_bad_deduction) {
10721         if (R->FailureKind != ovl_fail_bad_deduction)
10722           return true;
10723 
10724         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10725           return RankDeductionFailure(L->DeductionFailure)
10726                < RankDeductionFailure(R->DeductionFailure);
10727       } else if (R->FailureKind == ovl_fail_bad_deduction)
10728         return false;
10729 
10730       // TODO: others?
10731     }
10732 
10733     // Sort everything else by location.
10734     SourceLocation LLoc = GetLocationForCandidate(L);
10735     SourceLocation RLoc = GetLocationForCandidate(R);
10736 
10737     // Put candidates without locations (e.g. builtins) at the end.
10738     if (LLoc.isInvalid()) return false;
10739     if (RLoc.isInvalid()) return true;
10740 
10741     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10742   }
10743 };
10744 }
10745 
10746 /// CompleteNonViableCandidate - Normally, overload resolution only
10747 /// computes up to the first bad conversion. Produces the FixIt set if
10748 /// possible.
10749 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10750                                        ArrayRef<Expr *> Args) {
10751   assert(!Cand->Viable);
10752 
10753   // Don't do anything on failures other than bad conversion.
10754   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10755 
10756   // We only want the FixIts if all the arguments can be corrected.
10757   bool Unfixable = false;
10758   // Use a implicit copy initialization to check conversion fixes.
10759   Cand->Fix.setConversionChecker(TryCopyInitialization);
10760 
10761   // Attempt to fix the bad conversion.
10762   unsigned ConvCount = Cand->Conversions.size();
10763   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10764        ++ConvIdx) {
10765     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10766     if (Cand->Conversions[ConvIdx].isInitialized() &&
10767         Cand->Conversions[ConvIdx].isBad()) {
10768       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10769       break;
10770     }
10771   }
10772 
10773   // FIXME: this should probably be preserved from the overload
10774   // operation somehow.
10775   bool SuppressUserConversions = false;
10776 
10777   unsigned ConvIdx = 0;
10778   ArrayRef<QualType> ParamTypes;
10779 
10780   if (Cand->IsSurrogate) {
10781     QualType ConvType
10782       = Cand->Surrogate->getConversionType().getNonReferenceType();
10783     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10784       ConvType = ConvPtrType->getPointeeType();
10785     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10786     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10787     ConvIdx = 1;
10788   } else if (Cand->Function) {
10789     ParamTypes =
10790         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10791     if (isa<CXXMethodDecl>(Cand->Function) &&
10792         !isa<CXXConstructorDecl>(Cand->Function)) {
10793       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10794       ConvIdx = 1;
10795     }
10796   } else {
10797     // Builtin operator.
10798     assert(ConvCount <= 3);
10799     ParamTypes = Cand->BuiltinParamTypes;
10800   }
10801 
10802   // Fill in the rest of the conversions.
10803   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10804     if (Cand->Conversions[ConvIdx].isInitialized()) {
10805       // We've already checked this conversion.
10806     } else if (ArgIdx < ParamTypes.size()) {
10807       if (ParamTypes[ArgIdx]->isDependentType())
10808         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10809             Args[ArgIdx]->getType());
10810       else {
10811         Cand->Conversions[ConvIdx] =
10812             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10813                                   SuppressUserConversions,
10814                                   /*InOverloadResolution=*/true,
10815                                   /*AllowObjCWritebackConversion=*/
10816                                   S.getLangOpts().ObjCAutoRefCount);
10817         // Store the FixIt in the candidate if it exists.
10818         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10819           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10820       }
10821     } else
10822       Cand->Conversions[ConvIdx].setEllipsis();
10823   }
10824 }
10825 
10826 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
10827     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10828     SourceLocation OpLoc,
10829     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10830   // Sort the candidates by viability and position.  Sorting directly would
10831   // be prohibitive, so we make a set of pointers and sort those.
10832   SmallVector<OverloadCandidate*, 32> Cands;
10833   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10834   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10835     if (!Filter(*Cand))
10836       continue;
10837     if (Cand->Viable)
10838       Cands.push_back(Cand);
10839     else if (OCD == OCD_AllCandidates) {
10840       CompleteNonViableCandidate(S, Cand, Args);
10841       if (Cand->Function || Cand->IsSurrogate)
10842         Cands.push_back(Cand);
10843       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10844       // want to list every possible builtin candidate.
10845     }
10846   }
10847 
10848   llvm::stable_sort(
10849       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10850 
10851   return Cands;
10852 }
10853 
10854 /// When overload resolution fails, prints diagnostic messages containing the
10855 /// candidates in the candidate set.
10856 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
10857     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10858     StringRef Opc, SourceLocation OpLoc,
10859     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10860 
10861   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
10862 
10863   S.Diag(PD.first, PD.second);
10864 
10865   NoteCandidates(S, Args, Cands, Opc, OpLoc);
10866 }
10867 
10868 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
10869                                           ArrayRef<OverloadCandidate *> Cands,
10870                                           StringRef Opc, SourceLocation OpLoc) {
10871   bool ReportedAmbiguousConversions = false;
10872 
10873   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10874   unsigned CandsShown = 0;
10875   auto I = Cands.begin(), E = Cands.end();
10876   for (; I != E; ++I) {
10877     OverloadCandidate *Cand = *I;
10878 
10879     // Set an arbitrary limit on the number of candidate functions we'll spam
10880     // the user with.  FIXME: This limit should depend on details of the
10881     // candidate list.
10882     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10883       break;
10884     }
10885     ++CandsShown;
10886 
10887     if (Cand->Function)
10888       NoteFunctionCandidate(S, Cand, Args.size(),
10889                             /*TakingCandidateAddress=*/false, DestAS);
10890     else if (Cand->IsSurrogate)
10891       NoteSurrogateCandidate(S, Cand);
10892     else {
10893       assert(Cand->Viable &&
10894              "Non-viable built-in candidates are not added to Cands.");
10895       // Generally we only see ambiguities including viable builtin
10896       // operators if overload resolution got screwed up by an
10897       // ambiguous user-defined conversion.
10898       //
10899       // FIXME: It's quite possible for different conversions to see
10900       // different ambiguities, though.
10901       if (!ReportedAmbiguousConversions) {
10902         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10903         ReportedAmbiguousConversions = true;
10904       }
10905 
10906       // If this is a viable builtin, print it.
10907       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10908     }
10909   }
10910 
10911   if (I != E)
10912     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10913 }
10914 
10915 static SourceLocation
10916 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10917   return Cand->Specialization ? Cand->Specialization->getLocation()
10918                               : SourceLocation();
10919 }
10920 
10921 namespace {
10922 struct CompareTemplateSpecCandidatesForDisplay {
10923   Sema &S;
10924   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10925 
10926   bool operator()(const TemplateSpecCandidate *L,
10927                   const TemplateSpecCandidate *R) {
10928     // Fast-path this check.
10929     if (L == R)
10930       return false;
10931 
10932     // Assuming that both candidates are not matches...
10933 
10934     // Sort by the ranking of deduction failures.
10935     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10936       return RankDeductionFailure(L->DeductionFailure) <
10937              RankDeductionFailure(R->DeductionFailure);
10938 
10939     // Sort everything else by location.
10940     SourceLocation LLoc = GetLocationForCandidate(L);
10941     SourceLocation RLoc = GetLocationForCandidate(R);
10942 
10943     // Put candidates without locations (e.g. builtins) at the end.
10944     if (LLoc.isInvalid())
10945       return false;
10946     if (RLoc.isInvalid())
10947       return true;
10948 
10949     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10950   }
10951 };
10952 }
10953 
10954 /// Diagnose a template argument deduction failure.
10955 /// We are treating these failures as overload failures due to bad
10956 /// deductions.
10957 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10958                                                  bool ForTakingAddress) {
10959   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10960                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10961 }
10962 
10963 void TemplateSpecCandidateSet::destroyCandidates() {
10964   for (iterator i = begin(), e = end(); i != e; ++i) {
10965     i->DeductionFailure.Destroy();
10966   }
10967 }
10968 
10969 void TemplateSpecCandidateSet::clear() {
10970   destroyCandidates();
10971   Candidates.clear();
10972 }
10973 
10974 /// NoteCandidates - When no template specialization match is found, prints
10975 /// diagnostic messages containing the non-matching specializations that form
10976 /// the candidate set.
10977 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10978 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10979 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10980   // Sort the candidates by position (assuming no candidate is a match).
10981   // Sorting directly would be prohibitive, so we make a set of pointers
10982   // and sort those.
10983   SmallVector<TemplateSpecCandidate *, 32> Cands;
10984   Cands.reserve(size());
10985   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10986     if (Cand->Specialization)
10987       Cands.push_back(Cand);
10988     // Otherwise, this is a non-matching builtin candidate.  We do not,
10989     // in general, want to list every possible builtin candidate.
10990   }
10991 
10992   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10993 
10994   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10995   // for generalization purposes (?).
10996   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10997 
10998   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10999   unsigned CandsShown = 0;
11000   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11001     TemplateSpecCandidate *Cand = *I;
11002 
11003     // Set an arbitrary limit on the number of candidates we'll spam
11004     // the user with.  FIXME: This limit should depend on details of the
11005     // candidate list.
11006     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11007       break;
11008     ++CandsShown;
11009 
11010     assert(Cand->Specialization &&
11011            "Non-matching built-in candidates are not added to Cands.");
11012     Cand->NoteDeductionFailure(S, ForTakingAddress);
11013   }
11014 
11015   if (I != E)
11016     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11017 }
11018 
11019 // [PossiblyAFunctionType]  -->   [Return]
11020 // NonFunctionType --> NonFunctionType
11021 // R (A) --> R(A)
11022 // R (*)(A) --> R (A)
11023 // R (&)(A) --> R (A)
11024 // R (S::*)(A) --> R (A)
11025 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11026   QualType Ret = PossiblyAFunctionType;
11027   if (const PointerType *ToTypePtr =
11028     PossiblyAFunctionType->getAs<PointerType>())
11029     Ret = ToTypePtr->getPointeeType();
11030   else if (const ReferenceType *ToTypeRef =
11031     PossiblyAFunctionType->getAs<ReferenceType>())
11032     Ret = ToTypeRef->getPointeeType();
11033   else if (const MemberPointerType *MemTypePtr =
11034     PossiblyAFunctionType->getAs<MemberPointerType>())
11035     Ret = MemTypePtr->getPointeeType();
11036   Ret =
11037     Context.getCanonicalType(Ret).getUnqualifiedType();
11038   return Ret;
11039 }
11040 
11041 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11042                                  bool Complain = true) {
11043   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11044       S.DeduceReturnType(FD, Loc, Complain))
11045     return true;
11046 
11047   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11048   if (S.getLangOpts().CPlusPlus17 &&
11049       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11050       !S.ResolveExceptionSpec(Loc, FPT))
11051     return true;
11052 
11053   return false;
11054 }
11055 
11056 namespace {
11057 // A helper class to help with address of function resolution
11058 // - allows us to avoid passing around all those ugly parameters
11059 class AddressOfFunctionResolver {
11060   Sema& S;
11061   Expr* SourceExpr;
11062   const QualType& TargetType;
11063   QualType TargetFunctionType; // Extracted function type from target type
11064 
11065   bool Complain;
11066   //DeclAccessPair& ResultFunctionAccessPair;
11067   ASTContext& Context;
11068 
11069   bool TargetTypeIsNonStaticMemberFunction;
11070   bool FoundNonTemplateFunction;
11071   bool StaticMemberFunctionFromBoundPointer;
11072   bool HasComplained;
11073 
11074   OverloadExpr::FindResult OvlExprInfo;
11075   OverloadExpr *OvlExpr;
11076   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11077   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11078   TemplateSpecCandidateSet FailedCandidates;
11079 
11080 public:
11081   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11082                             const QualType &TargetType, bool Complain)
11083       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11084         Complain(Complain), Context(S.getASTContext()),
11085         TargetTypeIsNonStaticMemberFunction(
11086             !!TargetType->getAs<MemberPointerType>()),
11087         FoundNonTemplateFunction(false),
11088         StaticMemberFunctionFromBoundPointer(false),
11089         HasComplained(false),
11090         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11091         OvlExpr(OvlExprInfo.Expression),
11092         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11093     ExtractUnqualifiedFunctionTypeFromTargetType();
11094 
11095     if (TargetFunctionType->isFunctionType()) {
11096       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11097         if (!UME->isImplicitAccess() &&
11098             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11099           StaticMemberFunctionFromBoundPointer = true;
11100     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11101       DeclAccessPair dap;
11102       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11103               OvlExpr, false, &dap)) {
11104         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11105           if (!Method->isStatic()) {
11106             // If the target type is a non-function type and the function found
11107             // is a non-static member function, pretend as if that was the
11108             // target, it's the only possible type to end up with.
11109             TargetTypeIsNonStaticMemberFunction = true;
11110 
11111             // And skip adding the function if its not in the proper form.
11112             // We'll diagnose this due to an empty set of functions.
11113             if (!OvlExprInfo.HasFormOfMemberPointer)
11114               return;
11115           }
11116 
11117         Matches.push_back(std::make_pair(dap, Fn));
11118       }
11119       return;
11120     }
11121 
11122     if (OvlExpr->hasExplicitTemplateArgs())
11123       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11124 
11125     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11126       // C++ [over.over]p4:
11127       //   If more than one function is selected, [...]
11128       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11129         if (FoundNonTemplateFunction)
11130           EliminateAllTemplateMatches();
11131         else
11132           EliminateAllExceptMostSpecializedTemplate();
11133       }
11134     }
11135 
11136     if (S.getLangOpts().CUDA && Matches.size() > 1)
11137       EliminateSuboptimalCudaMatches();
11138   }
11139 
11140   bool hasComplained() const { return HasComplained; }
11141 
11142 private:
11143   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11144     QualType Discard;
11145     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11146            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11147   }
11148 
11149   /// \return true if A is considered a better overload candidate for the
11150   /// desired type than B.
11151   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11152     // If A doesn't have exactly the correct type, we don't want to classify it
11153     // as "better" than anything else. This way, the user is required to
11154     // disambiguate for us if there are multiple candidates and no exact match.
11155     return candidateHasExactlyCorrectType(A) &&
11156            (!candidateHasExactlyCorrectType(B) ||
11157             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11158   }
11159 
11160   /// \return true if we were able to eliminate all but one overload candidate,
11161   /// false otherwise.
11162   bool eliminiateSuboptimalOverloadCandidates() {
11163     // Same algorithm as overload resolution -- one pass to pick the "best",
11164     // another pass to be sure that nothing is better than the best.
11165     auto Best = Matches.begin();
11166     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11167       if (isBetterCandidate(I->second, Best->second))
11168         Best = I;
11169 
11170     const FunctionDecl *BestFn = Best->second;
11171     auto IsBestOrInferiorToBest = [this, BestFn](
11172         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11173       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11174     };
11175 
11176     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11177     // option, so we can potentially give the user a better error
11178     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11179       return false;
11180     Matches[0] = *Best;
11181     Matches.resize(1);
11182     return true;
11183   }
11184 
11185   bool isTargetTypeAFunction() const {
11186     return TargetFunctionType->isFunctionType();
11187   }
11188 
11189   // [ToType]     [Return]
11190 
11191   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11192   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11193   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11194   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11195     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11196   }
11197 
11198   // return true if any matching specializations were found
11199   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11200                                    const DeclAccessPair& CurAccessFunPair) {
11201     if (CXXMethodDecl *Method
11202               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11203       // Skip non-static function templates when converting to pointer, and
11204       // static when converting to member pointer.
11205       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11206         return false;
11207     }
11208     else if (TargetTypeIsNonStaticMemberFunction)
11209       return false;
11210 
11211     // C++ [over.over]p2:
11212     //   If the name is a function template, template argument deduction is
11213     //   done (14.8.2.2), and if the argument deduction succeeds, the
11214     //   resulting template argument list is used to generate a single
11215     //   function template specialization, which is added to the set of
11216     //   overloaded functions considered.
11217     FunctionDecl *Specialization = nullptr;
11218     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11219     if (Sema::TemplateDeductionResult Result
11220           = S.DeduceTemplateArguments(FunctionTemplate,
11221                                       &OvlExplicitTemplateArgs,
11222                                       TargetFunctionType, Specialization,
11223                                       Info, /*IsAddressOfFunction*/true)) {
11224       // Make a note of the failed deduction for diagnostics.
11225       FailedCandidates.addCandidate()
11226           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11227                MakeDeductionFailureInfo(Context, Result, Info));
11228       return false;
11229     }
11230 
11231     // Template argument deduction ensures that we have an exact match or
11232     // compatible pointer-to-function arguments that would be adjusted by ICS.
11233     // This function template specicalization works.
11234     assert(S.isSameOrCompatibleFunctionType(
11235               Context.getCanonicalType(Specialization->getType()),
11236               Context.getCanonicalType(TargetFunctionType)));
11237 
11238     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11239       return false;
11240 
11241     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11242     return true;
11243   }
11244 
11245   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11246                                       const DeclAccessPair& CurAccessFunPair) {
11247     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11248       // Skip non-static functions when converting to pointer, and static
11249       // when converting to member pointer.
11250       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11251         return false;
11252     }
11253     else if (TargetTypeIsNonStaticMemberFunction)
11254       return false;
11255 
11256     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11257       if (S.getLangOpts().CUDA)
11258         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11259           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11260             return false;
11261       if (FunDecl->isMultiVersion()) {
11262         const auto *TA = FunDecl->getAttr<TargetAttr>();
11263         if (TA && !TA->isDefaultVersion())
11264           return false;
11265       }
11266 
11267       // If any candidate has a placeholder return type, trigger its deduction
11268       // now.
11269       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11270                                Complain)) {
11271         HasComplained |= Complain;
11272         return false;
11273       }
11274 
11275       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11276         return false;
11277 
11278       // If we're in C, we need to support types that aren't exactly identical.
11279       if (!S.getLangOpts().CPlusPlus ||
11280           candidateHasExactlyCorrectType(FunDecl)) {
11281         Matches.push_back(std::make_pair(
11282             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11283         FoundNonTemplateFunction = true;
11284         return true;
11285       }
11286     }
11287 
11288     return false;
11289   }
11290 
11291   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11292     bool Ret = false;
11293 
11294     // If the overload expression doesn't have the form of a pointer to
11295     // member, don't try to convert it to a pointer-to-member type.
11296     if (IsInvalidFormOfPointerToMemberFunction())
11297       return false;
11298 
11299     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11300                                E = OvlExpr->decls_end();
11301          I != E; ++I) {
11302       // Look through any using declarations to find the underlying function.
11303       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11304 
11305       // C++ [over.over]p3:
11306       //   Non-member functions and static member functions match
11307       //   targets of type "pointer-to-function" or "reference-to-function."
11308       //   Nonstatic member functions match targets of
11309       //   type "pointer-to-member-function."
11310       // Note that according to DR 247, the containing class does not matter.
11311       if (FunctionTemplateDecl *FunctionTemplate
11312                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11313         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11314           Ret = true;
11315       }
11316       // If we have explicit template arguments supplied, skip non-templates.
11317       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11318                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11319         Ret = true;
11320     }
11321     assert(Ret || Matches.empty());
11322     return Ret;
11323   }
11324 
11325   void EliminateAllExceptMostSpecializedTemplate() {
11326     //   [...] and any given function template specialization F1 is
11327     //   eliminated if the set contains a second function template
11328     //   specialization whose function template is more specialized
11329     //   than the function template of F1 according to the partial
11330     //   ordering rules of 14.5.5.2.
11331 
11332     // The algorithm specified above is quadratic. We instead use a
11333     // two-pass algorithm (similar to the one used to identify the
11334     // best viable function in an overload set) that identifies the
11335     // best function template (if it exists).
11336 
11337     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11338     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11339       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11340 
11341     // TODO: It looks like FailedCandidates does not serve much purpose
11342     // here, since the no_viable diagnostic has index 0.
11343     UnresolvedSetIterator Result = S.getMostSpecialized(
11344         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11345         SourceExpr->getBeginLoc(), S.PDiag(),
11346         S.PDiag(diag::err_addr_ovl_ambiguous)
11347             << Matches[0].second->getDeclName(),
11348         S.PDiag(diag::note_ovl_candidate)
11349             << (unsigned)oc_function << (unsigned)ocs_described_template,
11350         Complain, TargetFunctionType);
11351 
11352     if (Result != MatchesCopy.end()) {
11353       // Make it the first and only element
11354       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11355       Matches[0].second = cast<FunctionDecl>(*Result);
11356       Matches.resize(1);
11357     } else
11358       HasComplained |= Complain;
11359   }
11360 
11361   void EliminateAllTemplateMatches() {
11362     //   [...] any function template specializations in the set are
11363     //   eliminated if the set also contains a non-template function, [...]
11364     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11365       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11366         ++I;
11367       else {
11368         Matches[I] = Matches[--N];
11369         Matches.resize(N);
11370       }
11371     }
11372   }
11373 
11374   void EliminateSuboptimalCudaMatches() {
11375     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11376   }
11377 
11378 public:
11379   void ComplainNoMatchesFound() const {
11380     assert(Matches.empty());
11381     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11382         << OvlExpr->getName() << TargetFunctionType
11383         << OvlExpr->getSourceRange();
11384     if (FailedCandidates.empty())
11385       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11386                                   /*TakingAddress=*/true);
11387     else {
11388       // We have some deduction failure messages. Use them to diagnose
11389       // the function templates, and diagnose the non-template candidates
11390       // normally.
11391       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11392                                  IEnd = OvlExpr->decls_end();
11393            I != IEnd; ++I)
11394         if (FunctionDecl *Fun =
11395                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11396           if (!functionHasPassObjectSizeParams(Fun))
11397             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11398                                     /*TakingAddress=*/true);
11399       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11400     }
11401   }
11402 
11403   bool IsInvalidFormOfPointerToMemberFunction() const {
11404     return TargetTypeIsNonStaticMemberFunction &&
11405       !OvlExprInfo.HasFormOfMemberPointer;
11406   }
11407 
11408   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11409       // TODO: Should we condition this on whether any functions might
11410       // have matched, or is it more appropriate to do that in callers?
11411       // TODO: a fixit wouldn't hurt.
11412       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11413         << TargetType << OvlExpr->getSourceRange();
11414   }
11415 
11416   bool IsStaticMemberFunctionFromBoundPointer() const {
11417     return StaticMemberFunctionFromBoundPointer;
11418   }
11419 
11420   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11421     S.Diag(OvlExpr->getBeginLoc(),
11422            diag::err_invalid_form_pointer_member_function)
11423         << OvlExpr->getSourceRange();
11424   }
11425 
11426   void ComplainOfInvalidConversion() const {
11427     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11428         << OvlExpr->getName() << TargetType;
11429   }
11430 
11431   void ComplainMultipleMatchesFound() const {
11432     assert(Matches.size() > 1);
11433     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11434         << OvlExpr->getName() << OvlExpr->getSourceRange();
11435     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11436                                 /*TakingAddress=*/true);
11437   }
11438 
11439   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11440 
11441   int getNumMatches() const { return Matches.size(); }
11442 
11443   FunctionDecl* getMatchingFunctionDecl() const {
11444     if (Matches.size() != 1) return nullptr;
11445     return Matches[0].second;
11446   }
11447 
11448   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11449     if (Matches.size() != 1) return nullptr;
11450     return &Matches[0].first;
11451   }
11452 };
11453 }
11454 
11455 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11456 /// an overloaded function (C++ [over.over]), where @p From is an
11457 /// expression with overloaded function type and @p ToType is the type
11458 /// we're trying to resolve to. For example:
11459 ///
11460 /// @code
11461 /// int f(double);
11462 /// int f(int);
11463 ///
11464 /// int (*pfd)(double) = f; // selects f(double)
11465 /// @endcode
11466 ///
11467 /// This routine returns the resulting FunctionDecl if it could be
11468 /// resolved, and NULL otherwise. When @p Complain is true, this
11469 /// routine will emit diagnostics if there is an error.
11470 FunctionDecl *
11471 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11472                                          QualType TargetType,
11473                                          bool Complain,
11474                                          DeclAccessPair &FoundResult,
11475                                          bool *pHadMultipleCandidates) {
11476   assert(AddressOfExpr->getType() == Context.OverloadTy);
11477 
11478   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11479                                      Complain);
11480   int NumMatches = Resolver.getNumMatches();
11481   FunctionDecl *Fn = nullptr;
11482   bool ShouldComplain = Complain && !Resolver.hasComplained();
11483   if (NumMatches == 0 && ShouldComplain) {
11484     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11485       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11486     else
11487       Resolver.ComplainNoMatchesFound();
11488   }
11489   else if (NumMatches > 1 && ShouldComplain)
11490     Resolver.ComplainMultipleMatchesFound();
11491   else if (NumMatches == 1) {
11492     Fn = Resolver.getMatchingFunctionDecl();
11493     assert(Fn);
11494     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11495       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11496     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11497     if (Complain) {
11498       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11499         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11500       else
11501         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11502     }
11503   }
11504 
11505   if (pHadMultipleCandidates)
11506     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11507   return Fn;
11508 }
11509 
11510 /// Given an expression that refers to an overloaded function, try to
11511 /// resolve that function to a single function that can have its address taken.
11512 /// This will modify `Pair` iff it returns non-null.
11513 ///
11514 /// This routine can only realistically succeed if all but one candidates in the
11515 /// overload set for SrcExpr cannot have their addresses taken.
11516 FunctionDecl *
11517 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11518                                                   DeclAccessPair &Pair) {
11519   OverloadExpr::FindResult R = OverloadExpr::find(E);
11520   OverloadExpr *Ovl = R.Expression;
11521   FunctionDecl *Result = nullptr;
11522   DeclAccessPair DAP;
11523   // Don't use the AddressOfResolver because we're specifically looking for
11524   // cases where we have one overload candidate that lacks
11525   // enable_if/pass_object_size/...
11526   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11527     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11528     if (!FD)
11529       return nullptr;
11530 
11531     if (!checkAddressOfFunctionIsAvailable(FD))
11532       continue;
11533 
11534     // We have more than one result; quit.
11535     if (Result)
11536       return nullptr;
11537     DAP = I.getPair();
11538     Result = FD;
11539   }
11540 
11541   if (Result)
11542     Pair = DAP;
11543   return Result;
11544 }
11545 
11546 /// Given an overloaded function, tries to turn it into a non-overloaded
11547 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11548 /// will perform access checks, diagnose the use of the resultant decl, and, if
11549 /// requested, potentially perform a function-to-pointer decay.
11550 ///
11551 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11552 /// Otherwise, returns true. This may emit diagnostics and return true.
11553 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11554     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11555   Expr *E = SrcExpr.get();
11556   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11557 
11558   DeclAccessPair DAP;
11559   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11560   if (!Found || Found->isCPUDispatchMultiVersion() ||
11561       Found->isCPUSpecificMultiVersion())
11562     return false;
11563 
11564   // Emitting multiple diagnostics for a function that is both inaccessible and
11565   // unavailable is consistent with our behavior elsewhere. So, always check
11566   // for both.
11567   DiagnoseUseOfDecl(Found, E->getExprLoc());
11568   CheckAddressOfMemberAccess(E, DAP);
11569   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11570   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11571     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11572   else
11573     SrcExpr = Fixed;
11574   return true;
11575 }
11576 
11577 /// Given an expression that refers to an overloaded function, try to
11578 /// resolve that overloaded function expression down to a single function.
11579 ///
11580 /// This routine can only resolve template-ids that refer to a single function
11581 /// template, where that template-id refers to a single template whose template
11582 /// arguments are either provided by the template-id or have defaults,
11583 /// as described in C++0x [temp.arg.explicit]p3.
11584 ///
11585 /// If no template-ids are found, no diagnostics are emitted and NULL is
11586 /// returned.
11587 FunctionDecl *
11588 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11589                                                   bool Complain,
11590                                                   DeclAccessPair *FoundResult) {
11591   // C++ [over.over]p1:
11592   //   [...] [Note: any redundant set of parentheses surrounding the
11593   //   overloaded function name is ignored (5.1). ]
11594   // C++ [over.over]p1:
11595   //   [...] The overloaded function name can be preceded by the &
11596   //   operator.
11597 
11598   // If we didn't actually find any template-ids, we're done.
11599   if (!ovl->hasExplicitTemplateArgs())
11600     return nullptr;
11601 
11602   TemplateArgumentListInfo ExplicitTemplateArgs;
11603   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11604   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11605 
11606   // Look through all of the overloaded functions, searching for one
11607   // whose type matches exactly.
11608   FunctionDecl *Matched = nullptr;
11609   for (UnresolvedSetIterator I = ovl->decls_begin(),
11610          E = ovl->decls_end(); I != E; ++I) {
11611     // C++0x [temp.arg.explicit]p3:
11612     //   [...] In contexts where deduction is done and fails, or in contexts
11613     //   where deduction is not done, if a template argument list is
11614     //   specified and it, along with any default template arguments,
11615     //   identifies a single function template specialization, then the
11616     //   template-id is an lvalue for the function template specialization.
11617     FunctionTemplateDecl *FunctionTemplate
11618       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11619 
11620     // C++ [over.over]p2:
11621     //   If the name is a function template, template argument deduction is
11622     //   done (14.8.2.2), and if the argument deduction succeeds, the
11623     //   resulting template argument list is used to generate a single
11624     //   function template specialization, which is added to the set of
11625     //   overloaded functions considered.
11626     FunctionDecl *Specialization = nullptr;
11627     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11628     if (TemplateDeductionResult Result
11629           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11630                                     Specialization, Info,
11631                                     /*IsAddressOfFunction*/true)) {
11632       // Make a note of the failed deduction for diagnostics.
11633       // TODO: Actually use the failed-deduction info?
11634       FailedCandidates.addCandidate()
11635           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11636                MakeDeductionFailureInfo(Context, Result, Info));
11637       continue;
11638     }
11639 
11640     assert(Specialization && "no specialization and no error?");
11641 
11642     // Multiple matches; we can't resolve to a single declaration.
11643     if (Matched) {
11644       if (Complain) {
11645         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11646           << ovl->getName();
11647         NoteAllOverloadCandidates(ovl);
11648       }
11649       return nullptr;
11650     }
11651 
11652     Matched = Specialization;
11653     if (FoundResult) *FoundResult = I.getPair();
11654   }
11655 
11656   if (Matched &&
11657       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11658     return nullptr;
11659 
11660   return Matched;
11661 }
11662 
11663 // Resolve and fix an overloaded expression that can be resolved
11664 // because it identifies a single function template specialization.
11665 //
11666 // Last three arguments should only be supplied if Complain = true
11667 //
11668 // Return true if it was logically possible to so resolve the
11669 // expression, regardless of whether or not it succeeded.  Always
11670 // returns true if 'complain' is set.
11671 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11672                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11673                       bool complain, SourceRange OpRangeForComplaining,
11674                                            QualType DestTypeForComplaining,
11675                                             unsigned DiagIDForComplaining) {
11676   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11677 
11678   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11679 
11680   DeclAccessPair found;
11681   ExprResult SingleFunctionExpression;
11682   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11683                            ovl.Expression, /*complain*/ false, &found)) {
11684     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11685       SrcExpr = ExprError();
11686       return true;
11687     }
11688 
11689     // It is only correct to resolve to an instance method if we're
11690     // resolving a form that's permitted to be a pointer to member.
11691     // Otherwise we'll end up making a bound member expression, which
11692     // is illegal in all the contexts we resolve like this.
11693     if (!ovl.HasFormOfMemberPointer &&
11694         isa<CXXMethodDecl>(fn) &&
11695         cast<CXXMethodDecl>(fn)->isInstance()) {
11696       if (!complain) return false;
11697 
11698       Diag(ovl.Expression->getExprLoc(),
11699            diag::err_bound_member_function)
11700         << 0 << ovl.Expression->getSourceRange();
11701 
11702       // TODO: I believe we only end up here if there's a mix of
11703       // static and non-static candidates (otherwise the expression
11704       // would have 'bound member' type, not 'overload' type).
11705       // Ideally we would note which candidate was chosen and why
11706       // the static candidates were rejected.
11707       SrcExpr = ExprError();
11708       return true;
11709     }
11710 
11711     // Fix the expression to refer to 'fn'.
11712     SingleFunctionExpression =
11713         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11714 
11715     // If desired, do function-to-pointer decay.
11716     if (doFunctionPointerConverion) {
11717       SingleFunctionExpression =
11718         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11719       if (SingleFunctionExpression.isInvalid()) {
11720         SrcExpr = ExprError();
11721         return true;
11722       }
11723     }
11724   }
11725 
11726   if (!SingleFunctionExpression.isUsable()) {
11727     if (complain) {
11728       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11729         << ovl.Expression->getName()
11730         << DestTypeForComplaining
11731         << OpRangeForComplaining
11732         << ovl.Expression->getQualifierLoc().getSourceRange();
11733       NoteAllOverloadCandidates(SrcExpr.get());
11734 
11735       SrcExpr = ExprError();
11736       return true;
11737     }
11738 
11739     return false;
11740   }
11741 
11742   SrcExpr = SingleFunctionExpression;
11743   return true;
11744 }
11745 
11746 /// Add a single candidate to the overload set.
11747 static void AddOverloadedCallCandidate(Sema &S,
11748                                        DeclAccessPair FoundDecl,
11749                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11750                                        ArrayRef<Expr *> Args,
11751                                        OverloadCandidateSet &CandidateSet,
11752                                        bool PartialOverloading,
11753                                        bool KnownValid) {
11754   NamedDecl *Callee = FoundDecl.getDecl();
11755   if (isa<UsingShadowDecl>(Callee))
11756     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11757 
11758   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11759     if (ExplicitTemplateArgs) {
11760       assert(!KnownValid && "Explicit template arguments?");
11761       return;
11762     }
11763     // Prevent ill-formed function decls to be added as overload candidates.
11764     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11765       return;
11766 
11767     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11768                            /*SuppressUserConversions=*/false,
11769                            PartialOverloading);
11770     return;
11771   }
11772 
11773   if (FunctionTemplateDecl *FuncTemplate
11774       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11775     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11776                                    ExplicitTemplateArgs, Args, CandidateSet,
11777                                    /*SuppressUserConversions=*/false,
11778                                    PartialOverloading);
11779     return;
11780   }
11781 
11782   assert(!KnownValid && "unhandled case in overloaded call candidate");
11783 }
11784 
11785 /// Add the overload candidates named by callee and/or found by argument
11786 /// dependent lookup to the given overload set.
11787 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11788                                        ArrayRef<Expr *> Args,
11789                                        OverloadCandidateSet &CandidateSet,
11790                                        bool PartialOverloading) {
11791 
11792 #ifndef NDEBUG
11793   // Verify that ArgumentDependentLookup is consistent with the rules
11794   // in C++0x [basic.lookup.argdep]p3:
11795   //
11796   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11797   //   and let Y be the lookup set produced by argument dependent
11798   //   lookup (defined as follows). If X contains
11799   //
11800   //     -- a declaration of a class member, or
11801   //
11802   //     -- a block-scope function declaration that is not a
11803   //        using-declaration, or
11804   //
11805   //     -- a declaration that is neither a function or a function
11806   //        template
11807   //
11808   //   then Y is empty.
11809 
11810   if (ULE->requiresADL()) {
11811     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11812            E = ULE->decls_end(); I != E; ++I) {
11813       assert(!(*I)->getDeclContext()->isRecord());
11814       assert(isa<UsingShadowDecl>(*I) ||
11815              !(*I)->getDeclContext()->isFunctionOrMethod());
11816       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11817     }
11818   }
11819 #endif
11820 
11821   // It would be nice to avoid this copy.
11822   TemplateArgumentListInfo TABuffer;
11823   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11824   if (ULE->hasExplicitTemplateArgs()) {
11825     ULE->copyTemplateArgumentsInto(TABuffer);
11826     ExplicitTemplateArgs = &TABuffer;
11827   }
11828 
11829   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11830          E = ULE->decls_end(); I != E; ++I)
11831     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11832                                CandidateSet, PartialOverloading,
11833                                /*KnownValid*/ true);
11834 
11835   if (ULE->requiresADL())
11836     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11837                                          Args, ExplicitTemplateArgs,
11838                                          CandidateSet, PartialOverloading);
11839 }
11840 
11841 /// Determine whether a declaration with the specified name could be moved into
11842 /// a different namespace.
11843 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11844   switch (Name.getCXXOverloadedOperator()) {
11845   case OO_New: case OO_Array_New:
11846   case OO_Delete: case OO_Array_Delete:
11847     return false;
11848 
11849   default:
11850     return true;
11851   }
11852 }
11853 
11854 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11855 /// template, where the non-dependent name was declared after the template
11856 /// was defined. This is common in code written for a compilers which do not
11857 /// correctly implement two-stage name lookup.
11858 ///
11859 /// Returns true if a viable candidate was found and a diagnostic was issued.
11860 static bool
11861 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11862                        const CXXScopeSpec &SS, LookupResult &R,
11863                        OverloadCandidateSet::CandidateSetKind CSK,
11864                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11865                        ArrayRef<Expr *> Args,
11866                        bool *DoDiagnoseEmptyLookup = nullptr) {
11867   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11868     return false;
11869 
11870   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11871     if (DC->isTransparentContext())
11872       continue;
11873 
11874     SemaRef.LookupQualifiedName(R, DC);
11875 
11876     if (!R.empty()) {
11877       R.suppressDiagnostics();
11878 
11879       if (isa<CXXRecordDecl>(DC)) {
11880         // Don't diagnose names we find in classes; we get much better
11881         // diagnostics for these from DiagnoseEmptyLookup.
11882         R.clear();
11883         if (DoDiagnoseEmptyLookup)
11884           *DoDiagnoseEmptyLookup = true;
11885         return false;
11886       }
11887 
11888       OverloadCandidateSet Candidates(FnLoc, CSK);
11889       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11890         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11891                                    ExplicitTemplateArgs, Args,
11892                                    Candidates, false, /*KnownValid*/ false);
11893 
11894       OverloadCandidateSet::iterator Best;
11895       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11896         // No viable functions. Don't bother the user with notes for functions
11897         // which don't work and shouldn't be found anyway.
11898         R.clear();
11899         return false;
11900       }
11901 
11902       // Find the namespaces where ADL would have looked, and suggest
11903       // declaring the function there instead.
11904       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11905       Sema::AssociatedClassSet AssociatedClasses;
11906       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11907                                                  AssociatedNamespaces,
11908                                                  AssociatedClasses);
11909       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11910       if (canBeDeclaredInNamespace(R.getLookupName())) {
11911         DeclContext *Std = SemaRef.getStdNamespace();
11912         for (Sema::AssociatedNamespaceSet::iterator
11913                it = AssociatedNamespaces.begin(),
11914                end = AssociatedNamespaces.end(); it != end; ++it) {
11915           // Never suggest declaring a function within namespace 'std'.
11916           if (Std && Std->Encloses(*it))
11917             continue;
11918 
11919           // Never suggest declaring a function within a namespace with a
11920           // reserved name, like __gnu_cxx.
11921           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11922           if (NS &&
11923               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11924             continue;
11925 
11926           SuggestedNamespaces.insert(*it);
11927         }
11928       }
11929 
11930       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11931         << R.getLookupName();
11932       if (SuggestedNamespaces.empty()) {
11933         SemaRef.Diag(Best->Function->getLocation(),
11934                      diag::note_not_found_by_two_phase_lookup)
11935           << R.getLookupName() << 0;
11936       } else if (SuggestedNamespaces.size() == 1) {
11937         SemaRef.Diag(Best->Function->getLocation(),
11938                      diag::note_not_found_by_two_phase_lookup)
11939           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11940       } else {
11941         // FIXME: It would be useful to list the associated namespaces here,
11942         // but the diagnostics infrastructure doesn't provide a way to produce
11943         // a localized representation of a list of items.
11944         SemaRef.Diag(Best->Function->getLocation(),
11945                      diag::note_not_found_by_two_phase_lookup)
11946           << R.getLookupName() << 2;
11947       }
11948 
11949       // Try to recover by calling this function.
11950       return true;
11951     }
11952 
11953     R.clear();
11954   }
11955 
11956   return false;
11957 }
11958 
11959 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11960 /// template, where the non-dependent operator was declared after the template
11961 /// was defined.
11962 ///
11963 /// Returns true if a viable candidate was found and a diagnostic was issued.
11964 static bool
11965 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11966                                SourceLocation OpLoc,
11967                                ArrayRef<Expr *> Args) {
11968   DeclarationName OpName =
11969     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11970   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11971   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11972                                 OverloadCandidateSet::CSK_Operator,
11973                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11974 }
11975 
11976 namespace {
11977 class BuildRecoveryCallExprRAII {
11978   Sema &SemaRef;
11979 public:
11980   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11981     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11982     SemaRef.IsBuildingRecoveryCallExpr = true;
11983   }
11984 
11985   ~BuildRecoveryCallExprRAII() {
11986     SemaRef.IsBuildingRecoveryCallExpr = false;
11987   }
11988 };
11989 
11990 }
11991 
11992 /// Attempts to recover from a call where no functions were found.
11993 ///
11994 /// Returns true if new candidates were found.
11995 static ExprResult
11996 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11997                       UnresolvedLookupExpr *ULE,
11998                       SourceLocation LParenLoc,
11999                       MutableArrayRef<Expr *> Args,
12000                       SourceLocation RParenLoc,
12001                       bool EmptyLookup, bool AllowTypoCorrection) {
12002   // Do not try to recover if it is already building a recovery call.
12003   // This stops infinite loops for template instantiations like
12004   //
12005   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12006   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12007   //
12008   if (SemaRef.IsBuildingRecoveryCallExpr)
12009     return ExprError();
12010   BuildRecoveryCallExprRAII RCE(SemaRef);
12011 
12012   CXXScopeSpec SS;
12013   SS.Adopt(ULE->getQualifierLoc());
12014   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12015 
12016   TemplateArgumentListInfo TABuffer;
12017   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12018   if (ULE->hasExplicitTemplateArgs()) {
12019     ULE->copyTemplateArgumentsInto(TABuffer);
12020     ExplicitTemplateArgs = &TABuffer;
12021   }
12022 
12023   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12024                  Sema::LookupOrdinaryName);
12025   bool DoDiagnoseEmptyLookup = EmptyLookup;
12026   if (!DiagnoseTwoPhaseLookup(
12027           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12028           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12029     NoTypoCorrectionCCC NoTypoValidator{};
12030     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12031                                                 ExplicitTemplateArgs != nullptr,
12032                                                 dyn_cast<MemberExpr>(Fn));
12033     CorrectionCandidateCallback &Validator =
12034         AllowTypoCorrection
12035             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12036             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12037     if (!DoDiagnoseEmptyLookup ||
12038         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12039                                     Args))
12040       return ExprError();
12041   }
12042 
12043   assert(!R.empty() && "lookup results empty despite recovery");
12044 
12045   // If recovery created an ambiguity, just bail out.
12046   if (R.isAmbiguous()) {
12047     R.suppressDiagnostics();
12048     return ExprError();
12049   }
12050 
12051   // Build an implicit member call if appropriate.  Just drop the
12052   // casts and such from the call, we don't really care.
12053   ExprResult NewFn = ExprError();
12054   if ((*R.begin())->isCXXClassMember())
12055     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12056                                                     ExplicitTemplateArgs, S);
12057   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12058     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12059                                         ExplicitTemplateArgs);
12060   else
12061     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12062 
12063   if (NewFn.isInvalid())
12064     return ExprError();
12065 
12066   // This shouldn't cause an infinite loop because we're giving it
12067   // an expression with viable lookup results, which should never
12068   // end up here.
12069   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12070                                MultiExprArg(Args.data(), Args.size()),
12071                                RParenLoc);
12072 }
12073 
12074 /// Constructs and populates an OverloadedCandidateSet from
12075 /// the given function.
12076 /// \returns true when an the ExprResult output parameter has been set.
12077 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12078                                   UnresolvedLookupExpr *ULE,
12079                                   MultiExprArg Args,
12080                                   SourceLocation RParenLoc,
12081                                   OverloadCandidateSet *CandidateSet,
12082                                   ExprResult *Result) {
12083 #ifndef NDEBUG
12084   if (ULE->requiresADL()) {
12085     // To do ADL, we must have found an unqualified name.
12086     assert(!ULE->getQualifier() && "qualified name with ADL");
12087 
12088     // We don't perform ADL for implicit declarations of builtins.
12089     // Verify that this was correctly set up.
12090     FunctionDecl *F;
12091     if (ULE->decls_begin() != ULE->decls_end() &&
12092         ULE->decls_begin() + 1 == ULE->decls_end() &&
12093         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12094         F->getBuiltinID() && F->isImplicit())
12095       llvm_unreachable("performing ADL for builtin");
12096 
12097     // We don't perform ADL in C.
12098     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12099   }
12100 #endif
12101 
12102   UnbridgedCastsSet UnbridgedCasts;
12103   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12104     *Result = ExprError();
12105     return true;
12106   }
12107 
12108   // Add the functions denoted by the callee to the set of candidate
12109   // functions, including those from argument-dependent lookup.
12110   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12111 
12112   if (getLangOpts().MSVCCompat &&
12113       CurContext->isDependentContext() && !isSFINAEContext() &&
12114       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12115 
12116     OverloadCandidateSet::iterator Best;
12117     if (CandidateSet->empty() ||
12118         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12119             OR_No_Viable_Function) {
12120       // In Microsoft mode, if we are inside a template class member function
12121       // then create a type dependent CallExpr. The goal is to postpone name
12122       // lookup to instantiation time to be able to search into type dependent
12123       // base classes.
12124       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12125                                       VK_RValue, RParenLoc);
12126       CE->setTypeDependent(true);
12127       CE->setValueDependent(true);
12128       CE->setInstantiationDependent(true);
12129       *Result = CE;
12130       return true;
12131     }
12132   }
12133 
12134   if (CandidateSet->empty())
12135     return false;
12136 
12137   UnbridgedCasts.restore();
12138   return false;
12139 }
12140 
12141 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12142 /// the completed call expression. If overload resolution fails, emits
12143 /// diagnostics and returns ExprError()
12144 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12145                                            UnresolvedLookupExpr *ULE,
12146                                            SourceLocation LParenLoc,
12147                                            MultiExprArg Args,
12148                                            SourceLocation RParenLoc,
12149                                            Expr *ExecConfig,
12150                                            OverloadCandidateSet *CandidateSet,
12151                                            OverloadCandidateSet::iterator *Best,
12152                                            OverloadingResult OverloadResult,
12153                                            bool AllowTypoCorrection) {
12154   if (CandidateSet->empty())
12155     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12156                                  RParenLoc, /*EmptyLookup=*/true,
12157                                  AllowTypoCorrection);
12158 
12159   switch (OverloadResult) {
12160   case OR_Success: {
12161     FunctionDecl *FDecl = (*Best)->Function;
12162     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12163     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12164       return ExprError();
12165     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12166     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12167                                          ExecConfig, /*IsExecConfig=*/false,
12168                                          (*Best)->IsADLCandidate);
12169   }
12170 
12171   case OR_No_Viable_Function: {
12172     // Try to recover by looking for viable functions which the user might
12173     // have meant to call.
12174     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12175                                                 Args, RParenLoc,
12176                                                 /*EmptyLookup=*/false,
12177                                                 AllowTypoCorrection);
12178     if (!Recovery.isInvalid())
12179       return Recovery;
12180 
12181     // If the user passes in a function that we can't take the address of, we
12182     // generally end up emitting really bad error messages. Here, we attempt to
12183     // emit better ones.
12184     for (const Expr *Arg : Args) {
12185       if (!Arg->getType()->isFunctionType())
12186         continue;
12187       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12188         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12189         if (FD &&
12190             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12191                                                        Arg->getExprLoc()))
12192           return ExprError();
12193       }
12194     }
12195 
12196     CandidateSet->NoteCandidates(
12197         PartialDiagnosticAt(
12198             Fn->getBeginLoc(),
12199             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12200                 << ULE->getName() << Fn->getSourceRange()),
12201         SemaRef, OCD_AllCandidates, Args);
12202     break;
12203   }
12204 
12205   case OR_Ambiguous:
12206     CandidateSet->NoteCandidates(
12207         PartialDiagnosticAt(Fn->getBeginLoc(),
12208                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12209                                 << ULE->getName() << Fn->getSourceRange()),
12210         SemaRef, OCD_ViableCandidates, Args);
12211     break;
12212 
12213   case OR_Deleted: {
12214     CandidateSet->NoteCandidates(
12215         PartialDiagnosticAt(Fn->getBeginLoc(),
12216                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12217                                 << ULE->getName() << Fn->getSourceRange()),
12218         SemaRef, OCD_AllCandidates, Args);
12219 
12220     // We emitted an error for the unavailable/deleted function call but keep
12221     // the call in the AST.
12222     FunctionDecl *FDecl = (*Best)->Function;
12223     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12224     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12225                                          ExecConfig, /*IsExecConfig=*/false,
12226                                          (*Best)->IsADLCandidate);
12227   }
12228   }
12229 
12230   // Overload resolution failed.
12231   return ExprError();
12232 }
12233 
12234 static void markUnaddressableCandidatesUnviable(Sema &S,
12235                                                 OverloadCandidateSet &CS) {
12236   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12237     if (I->Viable &&
12238         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12239       I->Viable = false;
12240       I->FailureKind = ovl_fail_addr_not_available;
12241     }
12242   }
12243 }
12244 
12245 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12246 /// (which eventually refers to the declaration Func) and the call
12247 /// arguments Args/NumArgs, attempt to resolve the function call down
12248 /// to a specific function. If overload resolution succeeds, returns
12249 /// the call expression produced by overload resolution.
12250 /// Otherwise, emits diagnostics and returns ExprError.
12251 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12252                                          UnresolvedLookupExpr *ULE,
12253                                          SourceLocation LParenLoc,
12254                                          MultiExprArg Args,
12255                                          SourceLocation RParenLoc,
12256                                          Expr *ExecConfig,
12257                                          bool AllowTypoCorrection,
12258                                          bool CalleesAddressIsTaken) {
12259   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12260                                     OverloadCandidateSet::CSK_Normal);
12261   ExprResult result;
12262 
12263   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12264                              &result))
12265     return result;
12266 
12267   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12268   // functions that aren't addressible are considered unviable.
12269   if (CalleesAddressIsTaken)
12270     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12271 
12272   OverloadCandidateSet::iterator Best;
12273   OverloadingResult OverloadResult =
12274       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12275 
12276   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12277                                   ExecConfig, &CandidateSet, &Best,
12278                                   OverloadResult, AllowTypoCorrection);
12279 }
12280 
12281 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12282   return Functions.size() > 1 ||
12283     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12284 }
12285 
12286 /// Create a unary operation that may resolve to an overloaded
12287 /// operator.
12288 ///
12289 /// \param OpLoc The location of the operator itself (e.g., '*').
12290 ///
12291 /// \param Opc The UnaryOperatorKind that describes this operator.
12292 ///
12293 /// \param Fns The set of non-member functions that will be
12294 /// considered by overload resolution. The caller needs to build this
12295 /// set based on the context using, e.g.,
12296 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12297 /// set should not contain any member functions; those will be added
12298 /// by CreateOverloadedUnaryOp().
12299 ///
12300 /// \param Input The input argument.
12301 ExprResult
12302 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12303                               const UnresolvedSetImpl &Fns,
12304                               Expr *Input, bool PerformADL) {
12305   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12306   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12307   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12308   // TODO: provide better source location info.
12309   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12310 
12311   if (checkPlaceholderForOverload(*this, Input))
12312     return ExprError();
12313 
12314   Expr *Args[2] = { Input, nullptr };
12315   unsigned NumArgs = 1;
12316 
12317   // For post-increment and post-decrement, add the implicit '0' as
12318   // the second argument, so that we know this is a post-increment or
12319   // post-decrement.
12320   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12321     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12322     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12323                                      SourceLocation());
12324     NumArgs = 2;
12325   }
12326 
12327   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12328 
12329   if (Input->isTypeDependent()) {
12330     if (Fns.empty())
12331       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12332                                          VK_RValue, OK_Ordinary, OpLoc, false);
12333 
12334     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12335     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12336         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12337         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12338     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12339                                        Context.DependentTy, VK_RValue, OpLoc,
12340                                        FPOptions());
12341   }
12342 
12343   // Build an empty overload set.
12344   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12345 
12346   // Add the candidates from the given function set.
12347   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12348 
12349   // Add operator candidates that are member functions.
12350   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12351 
12352   // Add candidates from ADL.
12353   if (PerformADL) {
12354     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12355                                          /*ExplicitTemplateArgs*/nullptr,
12356                                          CandidateSet);
12357   }
12358 
12359   // Add builtin operator candidates.
12360   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12361 
12362   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12363 
12364   // Perform overload resolution.
12365   OverloadCandidateSet::iterator Best;
12366   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12367   case OR_Success: {
12368     // We found a built-in operator or an overloaded operator.
12369     FunctionDecl *FnDecl = Best->Function;
12370 
12371     if (FnDecl) {
12372       Expr *Base = nullptr;
12373       // We matched an overloaded operator. Build a call to that
12374       // operator.
12375 
12376       // Convert the arguments.
12377       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12378         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12379 
12380         ExprResult InputRes =
12381           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12382                                               Best->FoundDecl, Method);
12383         if (InputRes.isInvalid())
12384           return ExprError();
12385         Base = Input = InputRes.get();
12386       } else {
12387         // Convert the arguments.
12388         ExprResult InputInit
12389           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12390                                                       Context,
12391                                                       FnDecl->getParamDecl(0)),
12392                                       SourceLocation(),
12393                                       Input);
12394         if (InputInit.isInvalid())
12395           return ExprError();
12396         Input = InputInit.get();
12397       }
12398 
12399       // Build the actual expression node.
12400       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12401                                                 Base, HadMultipleCandidates,
12402                                                 OpLoc);
12403       if (FnExpr.isInvalid())
12404         return ExprError();
12405 
12406       // Determine the result type.
12407       QualType ResultTy = FnDecl->getReturnType();
12408       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12409       ResultTy = ResultTy.getNonLValueExprType(Context);
12410 
12411       Args[0] = Input;
12412       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12413           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12414           FPOptions(), Best->IsADLCandidate);
12415 
12416       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12417         return ExprError();
12418 
12419       if (CheckFunctionCall(FnDecl, TheCall,
12420                             FnDecl->getType()->castAs<FunctionProtoType>()))
12421         return ExprError();
12422 
12423       return MaybeBindToTemporary(TheCall);
12424     } else {
12425       // We matched a built-in operator. Convert the arguments, then
12426       // break out so that we will build the appropriate built-in
12427       // operator node.
12428       ExprResult InputRes = PerformImplicitConversion(
12429           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12430           CCK_ForBuiltinOverloadedOp);
12431       if (InputRes.isInvalid())
12432         return ExprError();
12433       Input = InputRes.get();
12434       break;
12435     }
12436   }
12437 
12438   case OR_No_Viable_Function:
12439     // This is an erroneous use of an operator which can be overloaded by
12440     // a non-member function. Check for non-member operators which were
12441     // defined too late to be candidates.
12442     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12443       // FIXME: Recover by calling the found function.
12444       return ExprError();
12445 
12446     // No viable function; fall through to handling this as a
12447     // built-in operator, which will produce an error message for us.
12448     break;
12449 
12450   case OR_Ambiguous:
12451     CandidateSet.NoteCandidates(
12452         PartialDiagnosticAt(OpLoc,
12453                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12454                                 << UnaryOperator::getOpcodeStr(Opc)
12455                                 << Input->getType() << Input->getSourceRange()),
12456         *this, OCD_ViableCandidates, ArgsArray,
12457         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12458     return ExprError();
12459 
12460   case OR_Deleted:
12461     CandidateSet.NoteCandidates(
12462         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12463                                        << UnaryOperator::getOpcodeStr(Opc)
12464                                        << Input->getSourceRange()),
12465         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12466         OpLoc);
12467     return ExprError();
12468   }
12469 
12470   // Either we found no viable overloaded operator or we matched a
12471   // built-in operator. In either case, fall through to trying to
12472   // build a built-in operation.
12473   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12474 }
12475 
12476 /// Create a binary operation that may resolve to an overloaded
12477 /// operator.
12478 ///
12479 /// \param OpLoc The location of the operator itself (e.g., '+').
12480 ///
12481 /// \param Opc The BinaryOperatorKind that describes this operator.
12482 ///
12483 /// \param Fns The set of non-member functions that will be
12484 /// considered by overload resolution. The caller needs to build this
12485 /// set based on the context using, e.g.,
12486 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12487 /// set should not contain any member functions; those will be added
12488 /// by CreateOverloadedBinOp().
12489 ///
12490 /// \param LHS Left-hand argument.
12491 /// \param RHS Right-hand argument.
12492 ExprResult
12493 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12494                             BinaryOperatorKind Opc,
12495                             const UnresolvedSetImpl &Fns,
12496                             Expr *LHS, Expr *RHS, bool PerformADL) {
12497   Expr *Args[2] = { LHS, RHS };
12498   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12499 
12500   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12501   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12502 
12503   // If either side is type-dependent, create an appropriate dependent
12504   // expression.
12505   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12506     if (Fns.empty()) {
12507       // If there are no functions to store, just build a dependent
12508       // BinaryOperator or CompoundAssignment.
12509       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12510         return new (Context) BinaryOperator(
12511             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12512             OpLoc, FPFeatures);
12513 
12514       return new (Context) CompoundAssignOperator(
12515           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12516           Context.DependentTy, Context.DependentTy, OpLoc,
12517           FPFeatures);
12518     }
12519 
12520     // FIXME: save results of ADL from here?
12521     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12522     // TODO: provide better source location info in DNLoc component.
12523     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12524     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12525         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12526         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12527     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12528                                        Context.DependentTy, VK_RValue, OpLoc,
12529                                        FPFeatures);
12530   }
12531 
12532   // Always do placeholder-like conversions on the RHS.
12533   if (checkPlaceholderForOverload(*this, Args[1]))
12534     return ExprError();
12535 
12536   // Do placeholder-like conversion on the LHS; note that we should
12537   // not get here with a PseudoObject LHS.
12538   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12539   if (checkPlaceholderForOverload(*this, Args[0]))
12540     return ExprError();
12541 
12542   // If this is the assignment operator, we only perform overload resolution
12543   // if the left-hand side is a class or enumeration type. This is actually
12544   // a hack. The standard requires that we do overload resolution between the
12545   // various built-in candidates, but as DR507 points out, this can lead to
12546   // problems. So we do it this way, which pretty much follows what GCC does.
12547   // Note that we go the traditional code path for compound assignment forms.
12548   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12549     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12550 
12551   // If this is the .* operator, which is not overloadable, just
12552   // create a built-in binary operator.
12553   if (Opc == BO_PtrMemD)
12554     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12555 
12556   // Build an empty overload set.
12557   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12558 
12559   // Add the candidates from the given function set.
12560   AddFunctionCandidates(Fns, Args, CandidateSet);
12561 
12562   // Add operator candidates that are member functions.
12563   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12564 
12565   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12566   // performed for an assignment operator (nor for operator[] nor operator->,
12567   // which don't get here).
12568   if (Opc != BO_Assign && PerformADL)
12569     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12570                                          /*ExplicitTemplateArgs*/ nullptr,
12571                                          CandidateSet);
12572 
12573   // Add builtin operator candidates.
12574   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12575 
12576   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12577 
12578   // Perform overload resolution.
12579   OverloadCandidateSet::iterator Best;
12580   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12581     case OR_Success: {
12582       // We found a built-in operator or an overloaded operator.
12583       FunctionDecl *FnDecl = Best->Function;
12584 
12585       if (FnDecl) {
12586         Expr *Base = nullptr;
12587         // We matched an overloaded operator. Build a call to that
12588         // operator.
12589 
12590         // Convert the arguments.
12591         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12592           // Best->Access is only meaningful for class members.
12593           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12594 
12595           ExprResult Arg1 =
12596             PerformCopyInitialization(
12597               InitializedEntity::InitializeParameter(Context,
12598                                                      FnDecl->getParamDecl(0)),
12599               SourceLocation(), Args[1]);
12600           if (Arg1.isInvalid())
12601             return ExprError();
12602 
12603           ExprResult Arg0 =
12604             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12605                                                 Best->FoundDecl, Method);
12606           if (Arg0.isInvalid())
12607             return ExprError();
12608           Base = Args[0] = Arg0.getAs<Expr>();
12609           Args[1] = RHS = Arg1.getAs<Expr>();
12610         } else {
12611           // Convert the arguments.
12612           ExprResult Arg0 = PerformCopyInitialization(
12613             InitializedEntity::InitializeParameter(Context,
12614                                                    FnDecl->getParamDecl(0)),
12615             SourceLocation(), Args[0]);
12616           if (Arg0.isInvalid())
12617             return ExprError();
12618 
12619           ExprResult Arg1 =
12620             PerformCopyInitialization(
12621               InitializedEntity::InitializeParameter(Context,
12622                                                      FnDecl->getParamDecl(1)),
12623               SourceLocation(), Args[1]);
12624           if (Arg1.isInvalid())
12625             return ExprError();
12626           Args[0] = LHS = Arg0.getAs<Expr>();
12627           Args[1] = RHS = Arg1.getAs<Expr>();
12628         }
12629 
12630         // Build the actual expression node.
12631         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12632                                                   Best->FoundDecl, Base,
12633                                                   HadMultipleCandidates, OpLoc);
12634         if (FnExpr.isInvalid())
12635           return ExprError();
12636 
12637         // Determine the result type.
12638         QualType ResultTy = FnDecl->getReturnType();
12639         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12640         ResultTy = ResultTy.getNonLValueExprType(Context);
12641 
12642         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12643             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12644             Best->IsADLCandidate);
12645 
12646         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12647                                 FnDecl))
12648           return ExprError();
12649 
12650         ArrayRef<const Expr *> ArgsArray(Args, 2);
12651         const Expr *ImplicitThis = nullptr;
12652         // Cut off the implicit 'this'.
12653         if (isa<CXXMethodDecl>(FnDecl)) {
12654           ImplicitThis = ArgsArray[0];
12655           ArgsArray = ArgsArray.slice(1);
12656         }
12657 
12658         // Check for a self move.
12659         if (Op == OO_Equal)
12660           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12661 
12662         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12663                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12664                   VariadicDoesNotApply);
12665 
12666         return MaybeBindToTemporary(TheCall);
12667       } else {
12668         // We matched a built-in operator. Convert the arguments, then
12669         // break out so that we will build the appropriate built-in
12670         // operator node.
12671         ExprResult ArgsRes0 = PerformImplicitConversion(
12672             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12673             AA_Passing, CCK_ForBuiltinOverloadedOp);
12674         if (ArgsRes0.isInvalid())
12675           return ExprError();
12676         Args[0] = ArgsRes0.get();
12677 
12678         ExprResult ArgsRes1 = PerformImplicitConversion(
12679             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12680             AA_Passing, CCK_ForBuiltinOverloadedOp);
12681         if (ArgsRes1.isInvalid())
12682           return ExprError();
12683         Args[1] = ArgsRes1.get();
12684         break;
12685       }
12686     }
12687 
12688     case OR_No_Viable_Function: {
12689       // C++ [over.match.oper]p9:
12690       //   If the operator is the operator , [...] and there are no
12691       //   viable functions, then the operator is assumed to be the
12692       //   built-in operator and interpreted according to clause 5.
12693       if (Opc == BO_Comma)
12694         break;
12695 
12696       // For class as left operand for assignment or compound assignment
12697       // operator do not fall through to handling in built-in, but report that
12698       // no overloaded assignment operator found
12699       ExprResult Result = ExprError();
12700       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
12701       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
12702                                                    Args, OpLoc);
12703       if (Args[0]->getType()->isRecordType() &&
12704           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12705         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12706              << BinaryOperator::getOpcodeStr(Opc)
12707              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12708         if (Args[0]->getType()->isIncompleteType()) {
12709           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12710             << Args[0]->getType()
12711             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12712         }
12713       } else {
12714         // This is an erroneous use of an operator which can be overloaded by
12715         // a non-member function. Check for non-member operators which were
12716         // defined too late to be candidates.
12717         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12718           // FIXME: Recover by calling the found function.
12719           return ExprError();
12720 
12721         // No viable function; try to create a built-in operation, which will
12722         // produce an error. Then, show the non-viable candidates.
12723         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12724       }
12725       assert(Result.isInvalid() &&
12726              "C++ binary operator overloading is missing candidates!");
12727       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
12728       return Result;
12729     }
12730 
12731     case OR_Ambiguous:
12732       CandidateSet.NoteCandidates(
12733           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12734                                          << BinaryOperator::getOpcodeStr(Opc)
12735                                          << Args[0]->getType()
12736                                          << Args[1]->getType()
12737                                          << Args[0]->getSourceRange()
12738                                          << Args[1]->getSourceRange()),
12739           *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12740           OpLoc);
12741       return ExprError();
12742 
12743     case OR_Deleted:
12744       if (isImplicitlyDeleted(Best->Function)) {
12745         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12746         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12747           << Context.getRecordType(Method->getParent())
12748           << getSpecialMember(Method);
12749 
12750         // The user probably meant to call this special member. Just
12751         // explain why it's deleted.
12752         NoteDeletedFunction(Method);
12753         return ExprError();
12754       }
12755       CandidateSet.NoteCandidates(
12756           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12757                                          << BinaryOperator::getOpcodeStr(Opc)
12758                                          << Args[0]->getSourceRange()
12759                                          << Args[1]->getSourceRange()),
12760           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12761           OpLoc);
12762       return ExprError();
12763   }
12764 
12765   // We matched a built-in operator; build it.
12766   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12767 }
12768 
12769 ExprResult
12770 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12771                                          SourceLocation RLoc,
12772                                          Expr *Base, Expr *Idx) {
12773   Expr *Args[2] = { Base, Idx };
12774   DeclarationName OpName =
12775       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12776 
12777   // If either side is type-dependent, create an appropriate dependent
12778   // expression.
12779   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12780 
12781     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12782     // CHECKME: no 'operator' keyword?
12783     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12784     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12785     UnresolvedLookupExpr *Fn
12786       = UnresolvedLookupExpr::Create(Context, NamingClass,
12787                                      NestedNameSpecifierLoc(), OpNameInfo,
12788                                      /*ADL*/ true, /*Overloaded*/ false,
12789                                      UnresolvedSetIterator(),
12790                                      UnresolvedSetIterator());
12791     // Can't add any actual overloads yet
12792 
12793     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12794                                        Context.DependentTy, VK_RValue, RLoc,
12795                                        FPOptions());
12796   }
12797 
12798   // Handle placeholders on both operands.
12799   if (checkPlaceholderForOverload(*this, Args[0]))
12800     return ExprError();
12801   if (checkPlaceholderForOverload(*this, Args[1]))
12802     return ExprError();
12803 
12804   // Build an empty overload set.
12805   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12806 
12807   // Subscript can only be overloaded as a member function.
12808 
12809   // Add operator candidates that are member functions.
12810   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12811 
12812   // Add builtin operator candidates.
12813   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12814 
12815   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12816 
12817   // Perform overload resolution.
12818   OverloadCandidateSet::iterator Best;
12819   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12820     case OR_Success: {
12821       // We found a built-in operator or an overloaded operator.
12822       FunctionDecl *FnDecl = Best->Function;
12823 
12824       if (FnDecl) {
12825         // We matched an overloaded operator. Build a call to that
12826         // operator.
12827 
12828         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12829 
12830         // Convert the arguments.
12831         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12832         ExprResult Arg0 =
12833           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12834                                               Best->FoundDecl, Method);
12835         if (Arg0.isInvalid())
12836           return ExprError();
12837         Args[0] = Arg0.get();
12838 
12839         // Convert the arguments.
12840         ExprResult InputInit
12841           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12842                                                       Context,
12843                                                       FnDecl->getParamDecl(0)),
12844                                       SourceLocation(),
12845                                       Args[1]);
12846         if (InputInit.isInvalid())
12847           return ExprError();
12848 
12849         Args[1] = InputInit.getAs<Expr>();
12850 
12851         // Build the actual expression node.
12852         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12853         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12854         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12855                                                   Best->FoundDecl,
12856                                                   Base,
12857                                                   HadMultipleCandidates,
12858                                                   OpLocInfo.getLoc(),
12859                                                   OpLocInfo.getInfo());
12860         if (FnExpr.isInvalid())
12861           return ExprError();
12862 
12863         // Determine the result type
12864         QualType ResultTy = FnDecl->getReturnType();
12865         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12866         ResultTy = ResultTy.getNonLValueExprType(Context);
12867 
12868         CXXOperatorCallExpr *TheCall =
12869             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12870                                         Args, ResultTy, VK, RLoc, FPOptions());
12871 
12872         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12873           return ExprError();
12874 
12875         if (CheckFunctionCall(Method, TheCall,
12876                               Method->getType()->castAs<FunctionProtoType>()))
12877           return ExprError();
12878 
12879         return MaybeBindToTemporary(TheCall);
12880       } else {
12881         // We matched a built-in operator. Convert the arguments, then
12882         // break out so that we will build the appropriate built-in
12883         // operator node.
12884         ExprResult ArgsRes0 = PerformImplicitConversion(
12885             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12886             AA_Passing, CCK_ForBuiltinOverloadedOp);
12887         if (ArgsRes0.isInvalid())
12888           return ExprError();
12889         Args[0] = ArgsRes0.get();
12890 
12891         ExprResult ArgsRes1 = PerformImplicitConversion(
12892             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12893             AA_Passing, CCK_ForBuiltinOverloadedOp);
12894         if (ArgsRes1.isInvalid())
12895           return ExprError();
12896         Args[1] = ArgsRes1.get();
12897 
12898         break;
12899       }
12900     }
12901 
12902     case OR_No_Viable_Function: {
12903       PartialDiagnostic PD = CandidateSet.empty()
12904           ? (PDiag(diag::err_ovl_no_oper)
12905              << Args[0]->getType() << /*subscript*/ 0
12906              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
12907           : (PDiag(diag::err_ovl_no_viable_subscript)
12908              << Args[0]->getType() << Args[0]->getSourceRange()
12909              << Args[1]->getSourceRange());
12910       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
12911                                   OCD_AllCandidates, Args, "[]", LLoc);
12912       return ExprError();
12913     }
12914 
12915     case OR_Ambiguous:
12916       CandidateSet.NoteCandidates(
12917           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12918                                         << "[]" << Args[0]->getType()
12919                                         << Args[1]->getType()
12920                                         << Args[0]->getSourceRange()
12921                                         << Args[1]->getSourceRange()),
12922           *this, OCD_ViableCandidates, Args, "[]", LLoc);
12923       return ExprError();
12924 
12925     case OR_Deleted:
12926       CandidateSet.NoteCandidates(
12927           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
12928                                         << "[]" << Args[0]->getSourceRange()
12929                                         << Args[1]->getSourceRange()),
12930           *this, OCD_AllCandidates, Args, "[]", LLoc);
12931       return ExprError();
12932     }
12933 
12934   // We matched a built-in operator; build it.
12935   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12936 }
12937 
12938 /// BuildCallToMemberFunction - Build a call to a member
12939 /// function. MemExpr is the expression that refers to the member
12940 /// function (and includes the object parameter), Args/NumArgs are the
12941 /// arguments to the function call (not including the object
12942 /// parameter). The caller needs to validate that the member
12943 /// expression refers to a non-static member function or an overloaded
12944 /// member function.
12945 ExprResult
12946 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12947                                 SourceLocation LParenLoc,
12948                                 MultiExprArg Args,
12949                                 SourceLocation RParenLoc) {
12950   assert(MemExprE->getType() == Context.BoundMemberTy ||
12951          MemExprE->getType() == Context.OverloadTy);
12952 
12953   // Dig out the member expression. This holds both the object
12954   // argument and the member function we're referring to.
12955   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12956 
12957   // Determine whether this is a call to a pointer-to-member function.
12958   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12959     assert(op->getType() == Context.BoundMemberTy);
12960     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12961 
12962     QualType fnType =
12963       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12964 
12965     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12966     QualType resultType = proto->getCallResultType(Context);
12967     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12968 
12969     // Check that the object type isn't more qualified than the
12970     // member function we're calling.
12971     Qualifiers funcQuals = proto->getMethodQuals();
12972 
12973     QualType objectType = op->getLHS()->getType();
12974     if (op->getOpcode() == BO_PtrMemI)
12975       objectType = objectType->castAs<PointerType>()->getPointeeType();
12976     Qualifiers objectQuals = objectType.getQualifiers();
12977 
12978     Qualifiers difference = objectQuals - funcQuals;
12979     difference.removeObjCGCAttr();
12980     difference.removeAddressSpace();
12981     if (difference) {
12982       std::string qualsString = difference.getAsString();
12983       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12984         << fnType.getUnqualifiedType()
12985         << qualsString
12986         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12987     }
12988 
12989     CXXMemberCallExpr *call =
12990         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12991                                   valueKind, RParenLoc, proto->getNumParams());
12992 
12993     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12994                             call, nullptr))
12995       return ExprError();
12996 
12997     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12998       return ExprError();
12999 
13000     if (CheckOtherCall(call, proto))
13001       return ExprError();
13002 
13003     return MaybeBindToTemporary(call);
13004   }
13005 
13006   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13007     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13008                             RParenLoc);
13009 
13010   UnbridgedCastsSet UnbridgedCasts;
13011   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13012     return ExprError();
13013 
13014   MemberExpr *MemExpr;
13015   CXXMethodDecl *Method = nullptr;
13016   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13017   NestedNameSpecifier *Qualifier = nullptr;
13018   if (isa<MemberExpr>(NakedMemExpr)) {
13019     MemExpr = cast<MemberExpr>(NakedMemExpr);
13020     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13021     FoundDecl = MemExpr->getFoundDecl();
13022     Qualifier = MemExpr->getQualifier();
13023     UnbridgedCasts.restore();
13024   } else {
13025     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13026     Qualifier = UnresExpr->getQualifier();
13027 
13028     QualType ObjectType = UnresExpr->getBaseType();
13029     Expr::Classification ObjectClassification
13030       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13031                             : UnresExpr->getBase()->Classify(Context);
13032 
13033     // Add overload candidates
13034     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13035                                       OverloadCandidateSet::CSK_Normal);
13036 
13037     // FIXME: avoid copy.
13038     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13039     if (UnresExpr->hasExplicitTemplateArgs()) {
13040       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13041       TemplateArgs = &TemplateArgsBuffer;
13042     }
13043 
13044     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13045            E = UnresExpr->decls_end(); I != E; ++I) {
13046 
13047       NamedDecl *Func = *I;
13048       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13049       if (isa<UsingShadowDecl>(Func))
13050         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13051 
13052 
13053       // Microsoft supports direct constructor calls.
13054       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13055         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13056                              CandidateSet,
13057                              /*SuppressUserConversions*/ false);
13058       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13059         // If explicit template arguments were provided, we can't call a
13060         // non-template member function.
13061         if (TemplateArgs)
13062           continue;
13063 
13064         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13065                            ObjectClassification, Args, CandidateSet,
13066                            /*SuppressUserConversions=*/false);
13067       } else {
13068         AddMethodTemplateCandidate(
13069             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13070             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13071             /*SuppressUserConversions=*/false);
13072       }
13073     }
13074 
13075     DeclarationName DeclName = UnresExpr->getMemberName();
13076 
13077     UnbridgedCasts.restore();
13078 
13079     OverloadCandidateSet::iterator Best;
13080     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13081                                             Best)) {
13082     case OR_Success:
13083       Method = cast<CXXMethodDecl>(Best->Function);
13084       FoundDecl = Best->FoundDecl;
13085       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13086       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13087         return ExprError();
13088       // If FoundDecl is different from Method (such as if one is a template
13089       // and the other a specialization), make sure DiagnoseUseOfDecl is
13090       // called on both.
13091       // FIXME: This would be more comprehensively addressed by modifying
13092       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13093       // being used.
13094       if (Method != FoundDecl.getDecl() &&
13095                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13096         return ExprError();
13097       break;
13098 
13099     case OR_No_Viable_Function:
13100       CandidateSet.NoteCandidates(
13101           PartialDiagnosticAt(
13102               UnresExpr->getMemberLoc(),
13103               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13104                   << DeclName << MemExprE->getSourceRange()),
13105           *this, OCD_AllCandidates, Args);
13106       // FIXME: Leaking incoming expressions!
13107       return ExprError();
13108 
13109     case OR_Ambiguous:
13110       CandidateSet.NoteCandidates(
13111           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13112                               PDiag(diag::err_ovl_ambiguous_member_call)
13113                                   << DeclName << MemExprE->getSourceRange()),
13114           *this, OCD_AllCandidates, Args);
13115       // FIXME: Leaking incoming expressions!
13116       return ExprError();
13117 
13118     case OR_Deleted:
13119       CandidateSet.NoteCandidates(
13120           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13121                               PDiag(diag::err_ovl_deleted_member_call)
13122                                   << DeclName << MemExprE->getSourceRange()),
13123           *this, OCD_AllCandidates, Args);
13124       // FIXME: Leaking incoming expressions!
13125       return ExprError();
13126     }
13127 
13128     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13129 
13130     // If overload resolution picked a static member, build a
13131     // non-member call based on that function.
13132     if (Method->isStatic()) {
13133       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13134                                    RParenLoc);
13135     }
13136 
13137     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13138   }
13139 
13140   QualType ResultType = Method->getReturnType();
13141   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13142   ResultType = ResultType.getNonLValueExprType(Context);
13143 
13144   assert(Method && "Member call to something that isn't a method?");
13145   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13146   CXXMemberCallExpr *TheCall =
13147       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13148                                 RParenLoc, Proto->getNumParams());
13149 
13150   // Check for a valid return type.
13151   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13152                           TheCall, Method))
13153     return ExprError();
13154 
13155   // Convert the object argument (for a non-static member function call).
13156   // We only need to do this if there was actually an overload; otherwise
13157   // it was done at lookup.
13158   if (!Method->isStatic()) {
13159     ExprResult ObjectArg =
13160       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13161                                           FoundDecl, Method);
13162     if (ObjectArg.isInvalid())
13163       return ExprError();
13164     MemExpr->setBase(ObjectArg.get());
13165   }
13166 
13167   // Convert the rest of the arguments
13168   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13169                               RParenLoc))
13170     return ExprError();
13171 
13172   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13173 
13174   if (CheckFunctionCall(Method, TheCall, Proto))
13175     return ExprError();
13176 
13177   // In the case the method to call was not selected by the overloading
13178   // resolution process, we still need to handle the enable_if attribute. Do
13179   // that here, so it will not hide previous -- and more relevant -- errors.
13180   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13181     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13182       Diag(MemE->getMemberLoc(),
13183            diag::err_ovl_no_viable_member_function_in_call)
13184           << Method << Method->getSourceRange();
13185       Diag(Method->getLocation(),
13186            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13187           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13188       return ExprError();
13189     }
13190   }
13191 
13192   if ((isa<CXXConstructorDecl>(CurContext) ||
13193        isa<CXXDestructorDecl>(CurContext)) &&
13194       TheCall->getMethodDecl()->isPure()) {
13195     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13196 
13197     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13198         MemExpr->performsVirtualDispatch(getLangOpts())) {
13199       Diag(MemExpr->getBeginLoc(),
13200            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13201           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13202           << MD->getParent()->getDeclName();
13203 
13204       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13205       if (getLangOpts().AppleKext)
13206         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13207             << MD->getParent()->getDeclName() << MD->getDeclName();
13208     }
13209   }
13210 
13211   if (CXXDestructorDecl *DD =
13212           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13213     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13214     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13215     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13216                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13217                          MemExpr->getMemberLoc());
13218   }
13219 
13220   return MaybeBindToTemporary(TheCall);
13221 }
13222 
13223 /// BuildCallToObjectOfClassType - Build a call to an object of class
13224 /// type (C++ [over.call.object]), which can end up invoking an
13225 /// overloaded function call operator (@c operator()) or performing a
13226 /// user-defined conversion on the object argument.
13227 ExprResult
13228 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13229                                    SourceLocation LParenLoc,
13230                                    MultiExprArg Args,
13231                                    SourceLocation RParenLoc) {
13232   if (checkPlaceholderForOverload(*this, Obj))
13233     return ExprError();
13234   ExprResult Object = Obj;
13235 
13236   UnbridgedCastsSet UnbridgedCasts;
13237   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13238     return ExprError();
13239 
13240   assert(Object.get()->getType()->isRecordType() &&
13241          "Requires object type argument");
13242   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13243 
13244   // C++ [over.call.object]p1:
13245   //  If the primary-expression E in the function call syntax
13246   //  evaluates to a class object of type "cv T", then the set of
13247   //  candidate functions includes at least the function call
13248   //  operators of T. The function call operators of T are obtained by
13249   //  ordinary lookup of the name operator() in the context of
13250   //  (E).operator().
13251   OverloadCandidateSet CandidateSet(LParenLoc,
13252                                     OverloadCandidateSet::CSK_Operator);
13253   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13254 
13255   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13256                           diag::err_incomplete_object_call, Object.get()))
13257     return true;
13258 
13259   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13260   LookupQualifiedName(R, Record->getDecl());
13261   R.suppressDiagnostics();
13262 
13263   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13264        Oper != OperEnd; ++Oper) {
13265     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13266                        Object.get()->Classify(Context), Args, CandidateSet,
13267                        /*SuppressUserConversion=*/false);
13268   }
13269 
13270   // C++ [over.call.object]p2:
13271   //   In addition, for each (non-explicit in C++0x) conversion function
13272   //   declared in T of the form
13273   //
13274   //        operator conversion-type-id () cv-qualifier;
13275   //
13276   //   where cv-qualifier is the same cv-qualification as, or a
13277   //   greater cv-qualification than, cv, and where conversion-type-id
13278   //   denotes the type "pointer to function of (P1,...,Pn) returning
13279   //   R", or the type "reference to pointer to function of
13280   //   (P1,...,Pn) returning R", or the type "reference to function
13281   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13282   //   is also considered as a candidate function. Similarly,
13283   //   surrogate call functions are added to the set of candidate
13284   //   functions for each conversion function declared in an
13285   //   accessible base class provided the function is not hidden
13286   //   within T by another intervening declaration.
13287   const auto &Conversions =
13288       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13289   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13290     NamedDecl *D = *I;
13291     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13292     if (isa<UsingShadowDecl>(D))
13293       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13294 
13295     // Skip over templated conversion functions; they aren't
13296     // surrogates.
13297     if (isa<FunctionTemplateDecl>(D))
13298       continue;
13299 
13300     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13301     if (!Conv->isExplicit()) {
13302       // Strip the reference type (if any) and then the pointer type (if
13303       // any) to get down to what might be a function type.
13304       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13305       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13306         ConvType = ConvPtrType->getPointeeType();
13307 
13308       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13309       {
13310         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13311                               Object.get(), Args, CandidateSet);
13312       }
13313     }
13314   }
13315 
13316   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13317 
13318   // Perform overload resolution.
13319   OverloadCandidateSet::iterator Best;
13320   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13321                                           Best)) {
13322   case OR_Success:
13323     // Overload resolution succeeded; we'll build the appropriate call
13324     // below.
13325     break;
13326 
13327   case OR_No_Viable_Function: {
13328     PartialDiagnostic PD =
13329         CandidateSet.empty()
13330             ? (PDiag(diag::err_ovl_no_oper)
13331                << Object.get()->getType() << /*call*/ 1
13332                << Object.get()->getSourceRange())
13333             : (PDiag(diag::err_ovl_no_viable_object_call)
13334                << Object.get()->getType() << Object.get()->getSourceRange());
13335     CandidateSet.NoteCandidates(
13336         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13337         OCD_AllCandidates, Args);
13338     break;
13339   }
13340   case OR_Ambiguous:
13341     CandidateSet.NoteCandidates(
13342         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13343                             PDiag(diag::err_ovl_ambiguous_object_call)
13344                                 << Object.get()->getType()
13345                                 << Object.get()->getSourceRange()),
13346         *this, OCD_ViableCandidates, Args);
13347     break;
13348 
13349   case OR_Deleted:
13350     CandidateSet.NoteCandidates(
13351         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13352                             PDiag(diag::err_ovl_deleted_object_call)
13353                                 << Object.get()->getType()
13354                                 << Object.get()->getSourceRange()),
13355         *this, OCD_AllCandidates, Args);
13356     break;
13357   }
13358 
13359   if (Best == CandidateSet.end())
13360     return true;
13361 
13362   UnbridgedCasts.restore();
13363 
13364   if (Best->Function == nullptr) {
13365     // Since there is no function declaration, this is one of the
13366     // surrogate candidates. Dig out the conversion function.
13367     CXXConversionDecl *Conv
13368       = cast<CXXConversionDecl>(
13369                          Best->Conversions[0].UserDefined.ConversionFunction);
13370 
13371     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13372                               Best->FoundDecl);
13373     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13374       return ExprError();
13375     assert(Conv == Best->FoundDecl.getDecl() &&
13376              "Found Decl & conversion-to-functionptr should be same, right?!");
13377     // We selected one of the surrogate functions that converts the
13378     // object parameter to a function pointer. Perform the conversion
13379     // on the object argument, then let BuildCallExpr finish the job.
13380 
13381     // Create an implicit member expr to refer to the conversion operator.
13382     // and then call it.
13383     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13384                                              Conv, HadMultipleCandidates);
13385     if (Call.isInvalid())
13386       return ExprError();
13387     // Record usage of conversion in an implicit cast.
13388     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13389                                     CK_UserDefinedConversion, Call.get(),
13390                                     nullptr, VK_RValue);
13391 
13392     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13393   }
13394 
13395   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13396 
13397   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13398   // that calls this method, using Object for the implicit object
13399   // parameter and passing along the remaining arguments.
13400   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13401 
13402   // An error diagnostic has already been printed when parsing the declaration.
13403   if (Method->isInvalidDecl())
13404     return ExprError();
13405 
13406   const FunctionProtoType *Proto =
13407     Method->getType()->getAs<FunctionProtoType>();
13408 
13409   unsigned NumParams = Proto->getNumParams();
13410 
13411   DeclarationNameInfo OpLocInfo(
13412                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13413   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13414   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13415                                            Obj, HadMultipleCandidates,
13416                                            OpLocInfo.getLoc(),
13417                                            OpLocInfo.getInfo());
13418   if (NewFn.isInvalid())
13419     return true;
13420 
13421   // The number of argument slots to allocate in the call. If we have default
13422   // arguments we need to allocate space for them as well. We additionally
13423   // need one more slot for the object parameter.
13424   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13425 
13426   // Build the full argument list for the method call (the implicit object
13427   // parameter is placed at the beginning of the list).
13428   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13429 
13430   bool IsError = false;
13431 
13432   // Initialize the implicit object parameter.
13433   ExprResult ObjRes =
13434     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13435                                         Best->FoundDecl, Method);
13436   if (ObjRes.isInvalid())
13437     IsError = true;
13438   else
13439     Object = ObjRes;
13440   MethodArgs[0] = Object.get();
13441 
13442   // Check the argument types.
13443   for (unsigned i = 0; i != NumParams; i++) {
13444     Expr *Arg;
13445     if (i < Args.size()) {
13446       Arg = Args[i];
13447 
13448       // Pass the argument.
13449 
13450       ExprResult InputInit
13451         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13452                                                     Context,
13453                                                     Method->getParamDecl(i)),
13454                                     SourceLocation(), Arg);
13455 
13456       IsError |= InputInit.isInvalid();
13457       Arg = InputInit.getAs<Expr>();
13458     } else {
13459       ExprResult DefArg
13460         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13461       if (DefArg.isInvalid()) {
13462         IsError = true;
13463         break;
13464       }
13465 
13466       Arg = DefArg.getAs<Expr>();
13467     }
13468 
13469     MethodArgs[i + 1] = Arg;
13470   }
13471 
13472   // If this is a variadic call, handle args passed through "...".
13473   if (Proto->isVariadic()) {
13474     // Promote the arguments (C99 6.5.2.2p7).
13475     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13476       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13477                                                         nullptr);
13478       IsError |= Arg.isInvalid();
13479       MethodArgs[i + 1] = Arg.get();
13480     }
13481   }
13482 
13483   if (IsError)
13484     return true;
13485 
13486   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13487 
13488   // Once we've built TheCall, all of the expressions are properly owned.
13489   QualType ResultTy = Method->getReturnType();
13490   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13491   ResultTy = ResultTy.getNonLValueExprType(Context);
13492 
13493   CXXOperatorCallExpr *TheCall =
13494       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13495                                   ResultTy, VK, RParenLoc, FPOptions());
13496 
13497   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13498     return true;
13499 
13500   if (CheckFunctionCall(Method, TheCall, Proto))
13501     return true;
13502 
13503   return MaybeBindToTemporary(TheCall);
13504 }
13505 
13506 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13507 ///  (if one exists), where @c Base is an expression of class type and
13508 /// @c Member is the name of the member we're trying to find.
13509 ExprResult
13510 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13511                                bool *NoArrowOperatorFound) {
13512   assert(Base->getType()->isRecordType() &&
13513          "left-hand side must have class type");
13514 
13515   if (checkPlaceholderForOverload(*this, Base))
13516     return ExprError();
13517 
13518   SourceLocation Loc = Base->getExprLoc();
13519 
13520   // C++ [over.ref]p1:
13521   //
13522   //   [...] An expression x->m is interpreted as (x.operator->())->m
13523   //   for a class object x of type T if T::operator->() exists and if
13524   //   the operator is selected as the best match function by the
13525   //   overload resolution mechanism (13.3).
13526   DeclarationName OpName =
13527     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13528   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13529   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13530 
13531   if (RequireCompleteType(Loc, Base->getType(),
13532                           diag::err_typecheck_incomplete_tag, Base))
13533     return ExprError();
13534 
13535   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13536   LookupQualifiedName(R, BaseRecord->getDecl());
13537   R.suppressDiagnostics();
13538 
13539   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13540        Oper != OperEnd; ++Oper) {
13541     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13542                        None, CandidateSet, /*SuppressUserConversion=*/false);
13543   }
13544 
13545   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13546 
13547   // Perform overload resolution.
13548   OverloadCandidateSet::iterator Best;
13549   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13550   case OR_Success:
13551     // Overload resolution succeeded; we'll build the call below.
13552     break;
13553 
13554   case OR_No_Viable_Function: {
13555     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
13556     if (CandidateSet.empty()) {
13557       QualType BaseType = Base->getType();
13558       if (NoArrowOperatorFound) {
13559         // Report this specific error to the caller instead of emitting a
13560         // diagnostic, as requested.
13561         *NoArrowOperatorFound = true;
13562         return ExprError();
13563       }
13564       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13565         << BaseType << Base->getSourceRange();
13566       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13567         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13568           << FixItHint::CreateReplacement(OpLoc, ".");
13569       }
13570     } else
13571       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13572         << "operator->" << Base->getSourceRange();
13573     CandidateSet.NoteCandidates(*this, Base, Cands);
13574     return ExprError();
13575   }
13576   case OR_Ambiguous:
13577     CandidateSet.NoteCandidates(
13578         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
13579                                        << "->" << Base->getType()
13580                                        << Base->getSourceRange()),
13581         *this, OCD_ViableCandidates, Base);
13582     return ExprError();
13583 
13584   case OR_Deleted:
13585     CandidateSet.NoteCandidates(
13586         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13587                                        << "->" << Base->getSourceRange()),
13588         *this, OCD_AllCandidates, Base);
13589     return ExprError();
13590   }
13591 
13592   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13593 
13594   // Convert the object parameter.
13595   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13596   ExprResult BaseResult =
13597     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13598                                         Best->FoundDecl, Method);
13599   if (BaseResult.isInvalid())
13600     return ExprError();
13601   Base = BaseResult.get();
13602 
13603   // Build the operator call.
13604   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13605                                             Base, HadMultipleCandidates, OpLoc);
13606   if (FnExpr.isInvalid())
13607     return ExprError();
13608 
13609   QualType ResultTy = Method->getReturnType();
13610   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13611   ResultTy = ResultTy.getNonLValueExprType(Context);
13612   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13613       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13614 
13615   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13616     return ExprError();
13617 
13618   if (CheckFunctionCall(Method, TheCall,
13619                         Method->getType()->castAs<FunctionProtoType>()))
13620     return ExprError();
13621 
13622   return MaybeBindToTemporary(TheCall);
13623 }
13624 
13625 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13626 /// a literal operator described by the provided lookup results.
13627 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13628                                           DeclarationNameInfo &SuffixInfo,
13629                                           ArrayRef<Expr*> Args,
13630                                           SourceLocation LitEndLoc,
13631                                        TemplateArgumentListInfo *TemplateArgs) {
13632   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13633 
13634   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13635                                     OverloadCandidateSet::CSK_Normal);
13636   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13637                         /*SuppressUserConversions=*/true);
13638 
13639   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13640 
13641   // Perform overload resolution. This will usually be trivial, but might need
13642   // to perform substitutions for a literal operator template.
13643   OverloadCandidateSet::iterator Best;
13644   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13645   case OR_Success:
13646   case OR_Deleted:
13647     break;
13648 
13649   case OR_No_Viable_Function:
13650     CandidateSet.NoteCandidates(
13651         PartialDiagnosticAt(UDSuffixLoc,
13652                             PDiag(diag::err_ovl_no_viable_function_in_call)
13653                                 << R.getLookupName()),
13654         *this, OCD_AllCandidates, Args);
13655     return ExprError();
13656 
13657   case OR_Ambiguous:
13658     CandidateSet.NoteCandidates(
13659         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
13660                                                 << R.getLookupName()),
13661         *this, OCD_ViableCandidates, Args);
13662     return ExprError();
13663   }
13664 
13665   FunctionDecl *FD = Best->Function;
13666   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13667                                         nullptr, HadMultipleCandidates,
13668                                         SuffixInfo.getLoc(),
13669                                         SuffixInfo.getInfo());
13670   if (Fn.isInvalid())
13671     return true;
13672 
13673   // Check the argument types. This should almost always be a no-op, except
13674   // that array-to-pointer decay is applied to string literals.
13675   Expr *ConvArgs[2];
13676   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13677     ExprResult InputInit = PerformCopyInitialization(
13678       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13679       SourceLocation(), Args[ArgIdx]);
13680     if (InputInit.isInvalid())
13681       return true;
13682     ConvArgs[ArgIdx] = InputInit.get();
13683   }
13684 
13685   QualType ResultTy = FD->getReturnType();
13686   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13687   ResultTy = ResultTy.getNonLValueExprType(Context);
13688 
13689   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13690       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13691       VK, LitEndLoc, UDSuffixLoc);
13692 
13693   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13694     return ExprError();
13695 
13696   if (CheckFunctionCall(FD, UDL, nullptr))
13697     return ExprError();
13698 
13699   return MaybeBindToTemporary(UDL);
13700 }
13701 
13702 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13703 /// given LookupResult is non-empty, it is assumed to describe a member which
13704 /// will be invoked. Otherwise, the function will be found via argument
13705 /// dependent lookup.
13706 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13707 /// otherwise CallExpr is set to ExprError() and some non-success value
13708 /// is returned.
13709 Sema::ForRangeStatus
13710 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13711                                 SourceLocation RangeLoc,
13712                                 const DeclarationNameInfo &NameInfo,
13713                                 LookupResult &MemberLookup,
13714                                 OverloadCandidateSet *CandidateSet,
13715                                 Expr *Range, ExprResult *CallExpr) {
13716   Scope *S = nullptr;
13717 
13718   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13719   if (!MemberLookup.empty()) {
13720     ExprResult MemberRef =
13721         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13722                                  /*IsPtr=*/false, CXXScopeSpec(),
13723                                  /*TemplateKWLoc=*/SourceLocation(),
13724                                  /*FirstQualifierInScope=*/nullptr,
13725                                  MemberLookup,
13726                                  /*TemplateArgs=*/nullptr, S);
13727     if (MemberRef.isInvalid()) {
13728       *CallExpr = ExprError();
13729       return FRS_DiagnosticIssued;
13730     }
13731     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13732     if (CallExpr->isInvalid()) {
13733       *CallExpr = ExprError();
13734       return FRS_DiagnosticIssued;
13735     }
13736   } else {
13737     UnresolvedSet<0> FoundNames;
13738     UnresolvedLookupExpr *Fn =
13739       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13740                                    NestedNameSpecifierLoc(), NameInfo,
13741                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13742                                    FoundNames.begin(), FoundNames.end());
13743 
13744     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13745                                                     CandidateSet, CallExpr);
13746     if (CandidateSet->empty() || CandidateSetError) {
13747       *CallExpr = ExprError();
13748       return FRS_NoViableFunction;
13749     }
13750     OverloadCandidateSet::iterator Best;
13751     OverloadingResult OverloadResult =
13752         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13753 
13754     if (OverloadResult == OR_No_Viable_Function) {
13755       *CallExpr = ExprError();
13756       return FRS_NoViableFunction;
13757     }
13758     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13759                                          Loc, nullptr, CandidateSet, &Best,
13760                                          OverloadResult,
13761                                          /*AllowTypoCorrection=*/false);
13762     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13763       *CallExpr = ExprError();
13764       return FRS_DiagnosticIssued;
13765     }
13766   }
13767   return FRS_Success;
13768 }
13769 
13770 
13771 /// FixOverloadedFunctionReference - E is an expression that refers to
13772 /// a C++ overloaded function (possibly with some parentheses and
13773 /// perhaps a '&' around it). We have resolved the overloaded function
13774 /// to the function declaration Fn, so patch up the expression E to
13775 /// refer (possibly indirectly) to Fn. Returns the new expr.
13776 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13777                                            FunctionDecl *Fn) {
13778   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13779     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13780                                                    Found, Fn);
13781     if (SubExpr == PE->getSubExpr())
13782       return PE;
13783 
13784     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13785   }
13786 
13787   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13788     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13789                                                    Found, Fn);
13790     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13791                                SubExpr->getType()) &&
13792            "Implicit cast type cannot be determined from overload");
13793     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13794     if (SubExpr == ICE->getSubExpr())
13795       return ICE;
13796 
13797     return ImplicitCastExpr::Create(Context, ICE->getType(),
13798                                     ICE->getCastKind(),
13799                                     SubExpr, nullptr,
13800                                     ICE->getValueKind());
13801   }
13802 
13803   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13804     if (!GSE->isResultDependent()) {
13805       Expr *SubExpr =
13806           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13807       if (SubExpr == GSE->getResultExpr())
13808         return GSE;
13809 
13810       // Replace the resulting type information before rebuilding the generic
13811       // selection expression.
13812       ArrayRef<Expr *> A = GSE->getAssocExprs();
13813       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13814       unsigned ResultIdx = GSE->getResultIndex();
13815       AssocExprs[ResultIdx] = SubExpr;
13816 
13817       return GenericSelectionExpr::Create(
13818           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13819           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13820           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13821           ResultIdx);
13822     }
13823     // Rather than fall through to the unreachable, return the original generic
13824     // selection expression.
13825     return GSE;
13826   }
13827 
13828   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13829     assert(UnOp->getOpcode() == UO_AddrOf &&
13830            "Can only take the address of an overloaded function");
13831     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13832       if (Method->isStatic()) {
13833         // Do nothing: static member functions aren't any different
13834         // from non-member functions.
13835       } else {
13836         // Fix the subexpression, which really has to be an
13837         // UnresolvedLookupExpr holding an overloaded member function
13838         // or template.
13839         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13840                                                        Found, Fn);
13841         if (SubExpr == UnOp->getSubExpr())
13842           return UnOp;
13843 
13844         assert(isa<DeclRefExpr>(SubExpr)
13845                && "fixed to something other than a decl ref");
13846         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13847                && "fixed to a member ref with no nested name qualifier");
13848 
13849         // We have taken the address of a pointer to member
13850         // function. Perform the computation here so that we get the
13851         // appropriate pointer to member type.
13852         QualType ClassType
13853           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13854         QualType MemPtrType
13855           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13856         // Under the MS ABI, lock down the inheritance model now.
13857         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13858           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13859 
13860         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13861                                            VK_RValue, OK_Ordinary,
13862                                            UnOp->getOperatorLoc(), false);
13863       }
13864     }
13865     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13866                                                    Found, Fn);
13867     if (SubExpr == UnOp->getSubExpr())
13868       return UnOp;
13869 
13870     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13871                                      Context.getPointerType(SubExpr->getType()),
13872                                        VK_RValue, OK_Ordinary,
13873                                        UnOp->getOperatorLoc(), false);
13874   }
13875 
13876   // C++ [except.spec]p17:
13877   //   An exception-specification is considered to be needed when:
13878   //   - in an expression the function is the unique lookup result or the
13879   //     selected member of a set of overloaded functions
13880   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13881     ResolveExceptionSpec(E->getExprLoc(), FPT);
13882 
13883   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13884     // FIXME: avoid copy.
13885     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13886     if (ULE->hasExplicitTemplateArgs()) {
13887       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13888       TemplateArgs = &TemplateArgsBuffer;
13889     }
13890 
13891     DeclRefExpr *DRE =
13892         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
13893                          ULE->getQualifierLoc(), Found.getDecl(),
13894                          ULE->getTemplateKeywordLoc(), TemplateArgs);
13895     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13896     return DRE;
13897   }
13898 
13899   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13900     // FIXME: avoid copy.
13901     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13902     if (MemExpr->hasExplicitTemplateArgs()) {
13903       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13904       TemplateArgs = &TemplateArgsBuffer;
13905     }
13906 
13907     Expr *Base;
13908 
13909     // If we're filling in a static method where we used to have an
13910     // implicit member access, rewrite to a simple decl ref.
13911     if (MemExpr->isImplicitAccess()) {
13912       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13913         DeclRefExpr *DRE = BuildDeclRefExpr(
13914             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
13915             MemExpr->getQualifierLoc(), Found.getDecl(),
13916             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
13917         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13918         return DRE;
13919       } else {
13920         SourceLocation Loc = MemExpr->getMemberLoc();
13921         if (MemExpr->getQualifier())
13922           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13923         Base =
13924             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
13925       }
13926     } else
13927       Base = MemExpr->getBase();
13928 
13929     ExprValueKind valueKind;
13930     QualType type;
13931     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13932       valueKind = VK_LValue;
13933       type = Fn->getType();
13934     } else {
13935       valueKind = VK_RValue;
13936       type = Context.BoundMemberTy;
13937     }
13938 
13939     return BuildMemberExpr(
13940         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13941         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13942         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
13943         type, valueKind, OK_Ordinary, TemplateArgs);
13944   }
13945 
13946   llvm_unreachable("Invalid reference to overloaded function");
13947 }
13948 
13949 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13950                                                 DeclAccessPair Found,
13951                                                 FunctionDecl *Fn) {
13952   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13953 }
13954