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/AST/ASTContext.h"
14 #include "clang/AST/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.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/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
43 using AllowedExplicit = Sema::AllowedExplicit;
44 
45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47     return P->hasAttr<PassObjectSizeAttr>();
48   });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult
53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54                       const Expr *Base, bool HadMultipleCandidates,
55                       SourceLocation Loc = SourceLocation(),
56                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58     return ExprError();
59   // If FoundDecl is different from Fn (such as if one is a template
60   // and the other a specialization), make sure DiagnoseUseOfDecl is
61   // called on both.
62   // FIXME: This would be more comprehensively addressed by modifying
63   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64   // being used.
65   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66     return ExprError();
67   DeclRefExpr *DRE = new (S.Context)
68       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69   if (HadMultipleCandidates)
70     DRE->setHadMultipleCandidates(true);
71 
72   S.MarkDeclRefReferenced(DRE, Base);
73   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75       S.ResolveExceptionSpec(Loc, FPT);
76       DRE->setType(Fn->getType());
77     }
78   }
79   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80                              CK_FunctionToPointerDecay);
81 }
82 
83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84                                  bool InOverloadResolution,
85                                  StandardConversionSequence &SCS,
86                                  bool CStyle,
87                                  bool AllowObjCWritebackConversion);
88 
89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90                                                  QualType &ToType,
91                                                  bool InOverloadResolution,
92                                                  StandardConversionSequence &SCS,
93                                                  bool CStyle);
94 static OverloadingResult
95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96                         UserDefinedConversionSequence& User,
97                         OverloadCandidateSet& Conversions,
98                         AllowedExplicit AllowExplicit,
99                         bool AllowObjCConversionOnExplicit);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103                                    const StandardConversionSequence& SCS1,
104                                    const StandardConversionSequence& SCS2);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareQualificationConversions(Sema &S,
108                                 const StandardConversionSequence& SCS1,
109                                 const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 /// GetConversionRank - Retrieve the implicit conversion rank
117 /// corresponding to the given implicit conversion kind.
118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119   static const ImplicitConversionRank
120     Rank[(int)ICK_Num_Conversion_Kinds] = {
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Promotion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_OCL_Scalar_Widening,
142     ICR_Complex_Real_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Writeback_Conversion,
146     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147                      // it was omitted by the patch that added
148                      // ICK_Zero_Event_Conversion
149     ICR_C_Conversion,
150     ICR_C_Conversion_Extension
151   };
152   return Rank[(int)Kind];
153 }
154 
155 /// GetImplicitConversionName - Return the name of this kind of
156 /// implicit conversion.
157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159     "No conversion",
160     "Lvalue-to-rvalue",
161     "Array-to-pointer",
162     "Function-to-pointer",
163     "Function pointer conversion",
164     "Qualification",
165     "Integral promotion",
166     "Floating point promotion",
167     "Complex promotion",
168     "Integral conversion",
169     "Floating conversion",
170     "Complex conversion",
171     "Floating-integral conversion",
172     "Pointer conversion",
173     "Pointer-to-member conversion",
174     "Boolean conversion",
175     "Compatible-types conversion",
176     "Derived-to-base conversion",
177     "Vector conversion",
178     "SVE Vector conversion",
179     "Vector splat",
180     "Complex-real conversion",
181     "Block Pointer conversion",
182     "Transparent Union Conversion",
183     "Writeback conversion",
184     "OpenCL Zero Event Conversion",
185     "C specific type conversion",
186     "Incompatible pointer conversion"
187   };
188   return Name[Kind];
189 }
190 
191 /// StandardConversionSequence - Set the standard conversion
192 /// sequence to the identity conversion.
193 void StandardConversionSequence::setAsIdentityConversion() {
194   First = ICK_Identity;
195   Second = ICK_Identity;
196   Third = ICK_Identity;
197   DeprecatedStringLiteralToCharPtr = false;
198   QualificationIncludesObjCLifetime = false;
199   ReferenceBinding = false;
200   DirectBinding = false;
201   IsLvalueReference = true;
202   BindsToFunctionLvalue = false;
203   BindsToRvalue = false;
204   BindsImplicitObjectArgumentWithoutRefQualifier = false;
205   ObjCLifetimeConversionBinding = false;
206   CopyConstructor = nullptr;
207 }
208 
209 /// getRank - Retrieve the rank of this standard conversion sequence
210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211 /// implicit conversions.
212 ImplicitConversionRank StandardConversionSequence::getRank() const {
213   ImplicitConversionRank Rank = ICR_Exact_Match;
214   if  (GetConversionRank(First) > Rank)
215     Rank = GetConversionRank(First);
216   if  (GetConversionRank(Second) > Rank)
217     Rank = GetConversionRank(Second);
218   if  (GetConversionRank(Third) > Rank)
219     Rank = GetConversionRank(Third);
220   return Rank;
221 }
222 
223 /// isPointerConversionToBool - Determines whether this conversion is
224 /// a conversion of a pointer or pointer-to-member to bool. This is
225 /// used as part of the ranking of standard conversion sequences
226 /// (C++ 13.3.3.2p4).
227 bool StandardConversionSequence::isPointerConversionToBool() const {
228   // Note that FromType has not necessarily been transformed by the
229   // array-to-pointer or function-to-pointer implicit conversions, so
230   // check for their presence as well as checking whether FromType is
231   // a pointer.
232   if (getToType(1)->isBooleanType() &&
233       (getFromType()->isPointerType() ||
234        getFromType()->isMemberPointerType() ||
235        getFromType()->isObjCObjectPointerType() ||
236        getFromType()->isBlockPointerType() ||
237        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238     return true;
239 
240   return false;
241 }
242 
243 /// isPointerConversionToVoidPointer - Determines whether this
244 /// conversion is a conversion of a pointer to a void pointer. This is
245 /// used as part of the ranking of standard conversion sequences (C++
246 /// 13.3.3.2p4).
247 bool
248 StandardConversionSequence::
249 isPointerConversionToVoidPointer(ASTContext& Context) const {
250   QualType FromType = getFromType();
251   QualType ToType = getToType(1);
252 
253   // Note that FromType has not necessarily been transformed by the
254   // array-to-pointer implicit conversion, so check for its presence
255   // and redo the conversion to get a pointer.
256   if (First == ICK_Array_To_Pointer)
257     FromType = Context.getArrayDecayedType(FromType);
258 
259   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261       return ToPtrType->getPointeeType()->isVoidType();
262 
263   return false;
264 }
265 
266 /// Skip any implicit casts which could be either part of a narrowing conversion
267 /// or after one in an implicit conversion.
268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269                                              const Expr *Converted) {
270   // We can have cleanups wrapping the converted expression; these need to be
271   // preserved so that destructors run if necessary.
272   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273     Expr *Inner =
274         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276                                     EWC->getObjects());
277   }
278 
279   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280     switch (ICE->getCastKind()) {
281     case CK_NoOp:
282     case CK_IntegralCast:
283     case CK_IntegralToBoolean:
284     case CK_IntegralToFloating:
285     case CK_BooleanToSignedIntegral:
286     case CK_FloatingToIntegral:
287     case CK_FloatingToBoolean:
288     case CK_FloatingCast:
289       Converted = ICE->getSubExpr();
290       continue;
291 
292     default:
293       return Converted;
294     }
295   }
296 
297   return Converted;
298 }
299 
300 /// Check if this standard conversion sequence represents a narrowing
301 /// conversion, according to C++11 [dcl.init.list]p7.
302 ///
303 /// \param Ctx  The AST context.
304 /// \param Converted  The result of applying this standard conversion sequence.
305 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306 ///        value of the expression prior to the narrowing conversion.
307 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308 ///        type of the expression prior to the narrowing conversion.
309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310 ///        from floating point types to integral types should be ignored.
311 NarrowingKind StandardConversionSequence::getNarrowingKind(
312     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315 
316   // C++11 [dcl.init.list]p7:
317   //   A narrowing conversion is an implicit conversion ...
318   QualType FromType = getToType(0);
319   QualType ToType = getToType(1);
320 
321   // A conversion to an enumeration type is narrowing if the conversion to
322   // the underlying type is narrowing. This only arises for expressions of
323   // the form 'Enum{init}'.
324   if (auto *ET = ToType->getAs<EnumType>())
325     ToType = ET->getDecl()->getIntegerType();
326 
327   switch (Second) {
328   // 'bool' is an integral type; dispatch to the right place to handle it.
329   case ICK_Boolean_Conversion:
330     if (FromType->isRealFloatingType())
331       goto FloatingIntegralConversion;
332     if (FromType->isIntegralOrUnscopedEnumerationType())
333       goto IntegralConversion;
334     // -- from a pointer type or pointer-to-member type to bool, or
335     return NK_Type_Narrowing;
336 
337   // -- from a floating-point type to an integer type, or
338   //
339   // -- from an integer type or unscoped enumeration type to a floating-point
340   //    type, except where the source is a constant expression and the actual
341   //    value after conversion will fit into the target type and will produce
342   //    the original value when converted back to the original type, or
343   case ICK_Floating_Integral:
344   FloatingIntegralConversion:
345     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346       return NK_Type_Narrowing;
347     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348                ToType->isRealFloatingType()) {
349       if (IgnoreFloatToIntegralConversion)
350         return NK_Not_Narrowing;
351       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352       assert(Initializer && "Unknown conversion expression");
353 
354       // If it's value-dependent, we can't tell whether it's narrowing.
355       if (Initializer->isValueDependent())
356         return NK_Dependent_Narrowing;
357 
358       if (Optional<llvm::APSInt> IntConstantValue =
359               Initializer->getIntegerConstantExpr(Ctx)) {
360         // Convert the integer to the floating type.
361         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363                                 llvm::APFloat::rmNearestTiesToEven);
364         // And back.
365         llvm::APSInt ConvertedValue = *IntConstantValue;
366         bool ignored;
367         Result.convertToInteger(ConvertedValue,
368                                 llvm::APFloat::rmTowardZero, &ignored);
369         // If the resulting value is different, this was a narrowing conversion.
370         if (*IntConstantValue != ConvertedValue) {
371           ConstantValue = APValue(*IntConstantValue);
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         // Variables are always narrowings.
377         return NK_Variable_Narrowing;
378       }
379     }
380     return NK_Not_Narrowing;
381 
382   // -- from long double to double or float, or from double to float, except
383   //    where the source is a constant expression and the actual value after
384   //    conversion is within the range of values that can be represented (even
385   //    if it cannot be represented exactly), or
386   case ICK_Floating_Conversion:
387     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389       // FromType is larger than ToType.
390       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391 
392       // If it's value-dependent, we can't tell whether it's narrowing.
393       if (Initializer->isValueDependent())
394         return NK_Dependent_Narrowing;
395 
396       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397         // Constant!
398         assert(ConstantValue.isFloat());
399         llvm::APFloat FloatVal = ConstantValue.getFloat();
400         // Convert the source value into the target type.
401         bool ignored;
402         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403           Ctx.getFloatTypeSemantics(ToType),
404           llvm::APFloat::rmNearestTiesToEven, &ignored);
405         // If there was no overflow, the source value is within the range of
406         // values that can be represented.
407         if (ConvertStatus & llvm::APFloat::opOverflow) {
408           ConstantType = Initializer->getType();
409           return NK_Constant_Narrowing;
410         }
411       } else {
412         return NK_Variable_Narrowing;
413       }
414     }
415     return NK_Not_Narrowing;
416 
417   // -- from an integer type or unscoped enumeration type to an integer type
418   //    that cannot represent all the values of the original type, except where
419   //    the source is a constant expression and the actual value after
420   //    conversion will fit into the target type and will produce the original
421   //    value when converted back to the original type.
422   case ICK_Integral_Conversion:
423   IntegralConversion: {
424     assert(FromType->isIntegralOrUnscopedEnumerationType());
425     assert(ToType->isIntegralOrUnscopedEnumerationType());
426     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427     const unsigned FromWidth = Ctx.getIntWidth(FromType);
428     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429     const unsigned ToWidth = Ctx.getIntWidth(ToType);
430 
431     if (FromWidth > ToWidth ||
432         (FromWidth == ToWidth && FromSigned != ToSigned) ||
433         (FromSigned && !ToSigned)) {
434       // Not all values of FromType can be represented in ToType.
435       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436 
437       // If it's value-dependent, we can't tell whether it's narrowing.
438       if (Initializer->isValueDependent())
439         return NK_Dependent_Narrowing;
440 
441       Optional<llvm::APSInt> OptInitializerValue;
442       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443         // Such conversions on variables are always narrowing.
444         return NK_Variable_Narrowing;
445       }
446       llvm::APSInt &InitializerValue = *OptInitializerValue;
447       bool Narrowing = false;
448       if (FromWidth < ToWidth) {
449         // Negative -> unsigned is narrowing. Otherwise, more bits is never
450         // narrowing.
451         if (InitializerValue.isSigned() && InitializerValue.isNegative())
452           Narrowing = true;
453       } else {
454         // Add a bit to the InitializerValue so we don't have to worry about
455         // signed vs. unsigned comparisons.
456         InitializerValue = InitializerValue.extend(
457           InitializerValue.getBitWidth() + 1);
458         // Convert the initializer to and from the target width and signed-ness.
459         llvm::APSInt ConvertedValue = InitializerValue;
460         ConvertedValue = ConvertedValue.trunc(ToWidth);
461         ConvertedValue.setIsSigned(ToSigned);
462         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463         ConvertedValue.setIsSigned(InitializerValue.isSigned());
464         // If the result is different, this was a narrowing conversion.
465         if (ConvertedValue != InitializerValue)
466           Narrowing = true;
467       }
468       if (Narrowing) {
469         ConstantType = Initializer->getType();
470         ConstantValue = APValue(InitializerValue);
471         return NK_Constant_Narrowing;
472       }
473     }
474     return NK_Not_Narrowing;
475   }
476 
477   default:
478     // Other kinds of conversions are not narrowings.
479     return NK_Not_Narrowing;
480   }
481 }
482 
483 /// dump - Print this standard conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   bool PrintedSomething = false;
488   if (First != ICK_Identity) {
489     OS << GetImplicitConversionName(First);
490     PrintedSomething = true;
491   }
492 
493   if (Second != ICK_Identity) {
494     if (PrintedSomething) {
495       OS << " -> ";
496     }
497     OS << GetImplicitConversionName(Second);
498 
499     if (CopyConstructor) {
500       OS << " (by copy constructor)";
501     } else if (DirectBinding) {
502       OS << " (direct reference binding)";
503     } else if (ReferenceBinding) {
504       OS << " (reference binding)";
505     }
506     PrintedSomething = true;
507   }
508 
509   if (Third != ICK_Identity) {
510     if (PrintedSomething) {
511       OS << " -> ";
512     }
513     OS << GetImplicitConversionName(Third);
514     PrintedSomething = true;
515   }
516 
517   if (!PrintedSomething) {
518     OS << "No conversions required";
519   }
520 }
521 
522 /// dump - Print this user-defined conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void UserDefinedConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (Before.First || Before.Second || Before.Third) {
527     Before.dump();
528     OS << " -> ";
529   }
530   if (ConversionFunction)
531     OS << '\'' << *ConversionFunction << '\'';
532   else
533     OS << "aggregate initialization";
534   if (After.First || After.Second || After.Third) {
535     OS << " -> ";
536     After.dump();
537   }
538 }
539 
540 /// dump - Print this implicit conversion sequence to standard
541 /// error. Useful for debugging overloading issues.
542 void ImplicitConversionSequence::dump() const {
543   raw_ostream &OS = llvm::errs();
544   if (isStdInitializerListElement())
545     OS << "Worst std::initializer_list element conversion: ";
546   switch (ConversionKind) {
547   case StandardConversion:
548     OS << "Standard conversion: ";
549     Standard.dump();
550     break;
551   case UserDefinedConversion:
552     OS << "User-defined conversion: ";
553     UserDefined.dump();
554     break;
555   case EllipsisConversion:
556     OS << "Ellipsis conversion";
557     break;
558   case AmbiguousConversion:
559     OS << "Ambiguous conversion";
560     break;
561   case BadConversion:
562     OS << "Bad conversion";
563     break;
564   }
565 
566   OS << "\n";
567 }
568 
569 void AmbiguousConversionSequence::construct() {
570   new (&conversions()) ConversionSet();
571 }
572 
573 void AmbiguousConversionSequence::destruct() {
574   conversions().~ConversionSet();
575 }
576 
577 void
578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579   FromTypePtr = O.FromTypePtr;
580   ToTypePtr = O.ToTypePtr;
581   new (&conversions()) ConversionSet(O.conversions());
582 }
583 
584 namespace {
585   // Structure used by DeductionFailureInfo to store
586   // template argument information.
587   struct DFIArguments {
588     TemplateArgument FirstArg;
589     TemplateArgument SecondArg;
590   };
591   // Structure used by DeductionFailureInfo to store
592   // template parameter and template argument information.
593   struct DFIParamWithArguments : DFIArguments {
594     TemplateParameter Param;
595   };
596   // Structure used by DeductionFailureInfo to store template argument
597   // information and the index of the problematic call argument.
598   struct DFIDeducedMismatchArgs : DFIArguments {
599     TemplateArgumentList *TemplateArgs;
600     unsigned CallArgIndex;
601   };
602   // Structure used by DeductionFailureInfo to store information about
603   // unsatisfied constraints.
604   struct CNSInfo {
605     TemplateArgumentList *TemplateArgs;
606     ConstraintSatisfaction Satisfaction;
607   };
608 }
609 
610 /// Convert from Sema's representation of template deduction information
611 /// to the form used in overload-candidate information.
612 DeductionFailureInfo
613 clang::MakeDeductionFailureInfo(ASTContext &Context,
614                                 Sema::TemplateDeductionResult TDK,
615                                 TemplateDeductionInfo &Info) {
616   DeductionFailureInfo Result;
617   Result.Result = static_cast<unsigned>(TDK);
618   Result.HasDiagnostic = false;
619   switch (TDK) {
620   case Sema::TDK_Invalid:
621   case Sema::TDK_InstantiationDepth:
622   case Sema::TDK_TooManyArguments:
623   case Sema::TDK_TooFewArguments:
624   case Sema::TDK_MiscellaneousDeductionFailure:
625   case Sema::TDK_CUDATargetMismatch:
626     Result.Data = nullptr;
627     break;
628 
629   case Sema::TDK_Incomplete:
630   case Sema::TDK_InvalidExplicitArguments:
631     Result.Data = Info.Param.getOpaqueValue();
632     break;
633 
634   case Sema::TDK_DeducedMismatch:
635   case Sema::TDK_DeducedMismatchNested: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     auto *Saved = new (Context) DFIDeducedMismatchArgs;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Saved->TemplateArgs = Info.take();
641     Saved->CallArgIndex = Info.CallArgIndex;
642     Result.Data = Saved;
643     break;
644   }
645 
646   case Sema::TDK_NonDeducedMismatch: {
647     // FIXME: Should allocate from normal heap so that we can free this later.
648     DFIArguments *Saved = new (Context) DFIArguments;
649     Saved->FirstArg = Info.FirstArg;
650     Saved->SecondArg = Info.SecondArg;
651     Result.Data = Saved;
652     break;
653   }
654 
655   case Sema::TDK_IncompletePack:
656     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657   case Sema::TDK_Inconsistent:
658   case Sema::TDK_Underqualified: {
659     // FIXME: Should allocate from normal heap so that we can free this later.
660     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661     Saved->Param = Info.Param;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_SubstitutionFailure:
669     Result.Data = Info.take();
670     if (Info.hasSFINAEDiagnostic()) {
671       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672           SourceLocation(), PartialDiagnostic::NullDiagnostic());
673       Info.takeSFINAEDiagnostic(*Diag);
674       Result.HasDiagnostic = true;
675     }
676     break;
677 
678   case Sema::TDK_ConstraintsNotSatisfied: {
679     CNSInfo *Saved = new (Context) CNSInfo;
680     Saved->TemplateArgs = Info.take();
681     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682     Result.Data = Saved;
683     break;
684   }
685 
686   case Sema::TDK_Success:
687   case Sema::TDK_NonDependentConversionFailure:
688     llvm_unreachable("not a deduction failure");
689   }
690 
691   return Result;
692 }
693 
694 void DeductionFailureInfo::Destroy() {
695   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696   case Sema::TDK_Success:
697   case Sema::TDK_Invalid:
698   case Sema::TDK_InstantiationDepth:
699   case Sema::TDK_Incomplete:
700   case Sema::TDK_TooManyArguments:
701   case Sema::TDK_TooFewArguments:
702   case Sema::TDK_InvalidExplicitArguments:
703   case Sema::TDK_CUDATargetMismatch:
704   case Sema::TDK_NonDependentConversionFailure:
705     break;
706 
707   case Sema::TDK_IncompletePack:
708   case Sema::TDK_Inconsistent:
709   case Sema::TDK_Underqualified:
710   case Sema::TDK_DeducedMismatch:
711   case Sema::TDK_DeducedMismatchNested:
712   case Sema::TDK_NonDeducedMismatch:
713     // FIXME: Destroy the data?
714     Data = nullptr;
715     break;
716 
717   case Sema::TDK_SubstitutionFailure:
718     // FIXME: Destroy the template argument list?
719     Data = nullptr;
720     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721       Diag->~PartialDiagnosticAt();
722       HasDiagnostic = false;
723     }
724     break;
725 
726   case Sema::TDK_ConstraintsNotSatisfied:
727     // FIXME: Destroy the template argument list?
728     Data = nullptr;
729     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730       Diag->~PartialDiagnosticAt();
731       HasDiagnostic = false;
732     }
733     break;
734 
735   // Unhandled
736   case Sema::TDK_MiscellaneousDeductionFailure:
737     break;
738   }
739 }
740 
741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742   if (HasDiagnostic)
743     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744   return nullptr;
745 }
746 
747 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749   case Sema::TDK_Success:
750   case Sema::TDK_Invalid:
751   case Sema::TDK_InstantiationDepth:
752   case Sema::TDK_TooManyArguments:
753   case Sema::TDK_TooFewArguments:
754   case Sema::TDK_SubstitutionFailure:
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757   case Sema::TDK_NonDeducedMismatch:
758   case Sema::TDK_CUDATargetMismatch:
759   case Sema::TDK_NonDependentConversionFailure:
760   case Sema::TDK_ConstraintsNotSatisfied:
761     return TemplateParameter();
762 
763   case Sema::TDK_Incomplete:
764   case Sema::TDK_InvalidExplicitArguments:
765     return TemplateParameter::getFromOpaqueValue(Data);
766 
767   case Sema::TDK_IncompletePack:
768   case Sema::TDK_Inconsistent:
769   case Sema::TDK_Underqualified:
770     return static_cast<DFIParamWithArguments*>(Data)->Param;
771 
772   // Unhandled
773   case Sema::TDK_MiscellaneousDeductionFailure:
774     break;
775   }
776 
777   return TemplateParameter();
778 }
779 
780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782   case Sema::TDK_Success:
783   case Sema::TDK_Invalid:
784   case Sema::TDK_InstantiationDepth:
785   case Sema::TDK_TooManyArguments:
786   case Sema::TDK_TooFewArguments:
787   case Sema::TDK_Incomplete:
788   case Sema::TDK_IncompletePack:
789   case Sema::TDK_InvalidExplicitArguments:
790   case Sema::TDK_Inconsistent:
791   case Sema::TDK_Underqualified:
792   case Sema::TDK_NonDeducedMismatch:
793   case Sema::TDK_CUDATargetMismatch:
794   case Sema::TDK_NonDependentConversionFailure:
795     return nullptr;
796 
797   case Sema::TDK_DeducedMismatch:
798   case Sema::TDK_DeducedMismatchNested:
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800 
801   case Sema::TDK_SubstitutionFailure:
802     return static_cast<TemplateArgumentList*>(Data);
803 
804   case Sema::TDK_ConstraintsNotSatisfied:
805     return static_cast<CNSInfo*>(Data)->TemplateArgs;
806 
807   // Unhandled
808   case Sema::TDK_MiscellaneousDeductionFailure:
809     break;
810   }
811 
812   return nullptr;
813 }
814 
815 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817   case Sema::TDK_Success:
818   case Sema::TDK_Invalid:
819   case Sema::TDK_InstantiationDepth:
820   case Sema::TDK_Incomplete:
821   case Sema::TDK_TooManyArguments:
822   case Sema::TDK_TooFewArguments:
823   case Sema::TDK_InvalidExplicitArguments:
824   case Sema::TDK_SubstitutionFailure:
825   case Sema::TDK_CUDATargetMismatch:
826   case Sema::TDK_NonDependentConversionFailure:
827   case Sema::TDK_ConstraintsNotSatisfied:
828     return nullptr;
829 
830   case Sema::TDK_IncompletePack:
831   case Sema::TDK_Inconsistent:
832   case Sema::TDK_Underqualified:
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835   case Sema::TDK_NonDeducedMismatch:
836     return &static_cast<DFIArguments*>(Data)->FirstArg;
837 
838   // Unhandled
839   case Sema::TDK_MiscellaneousDeductionFailure:
840     break;
841   }
842 
843   return nullptr;
844 }
845 
846 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848   case Sema::TDK_Success:
849   case Sema::TDK_Invalid:
850   case Sema::TDK_InstantiationDepth:
851   case Sema::TDK_Incomplete:
852   case Sema::TDK_IncompletePack:
853   case Sema::TDK_TooManyArguments:
854   case Sema::TDK_TooFewArguments:
855   case Sema::TDK_InvalidExplicitArguments:
856   case Sema::TDK_SubstitutionFailure:
857   case Sema::TDK_CUDATargetMismatch:
858   case Sema::TDK_NonDependentConversionFailure:
859   case Sema::TDK_ConstraintsNotSatisfied:
860     return nullptr;
861 
862   case Sema::TDK_Inconsistent:
863   case Sema::TDK_Underqualified:
864   case Sema::TDK_DeducedMismatch:
865   case Sema::TDK_DeducedMismatchNested:
866   case Sema::TDK_NonDeducedMismatch:
867     return &static_cast<DFIArguments*>(Data)->SecondArg;
868 
869   // Unhandled
870   case Sema::TDK_MiscellaneousDeductionFailure:
871     break;
872   }
873 
874   return nullptr;
875 }
876 
877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879   case Sema::TDK_DeducedMismatch:
880   case Sema::TDK_DeducedMismatchNested:
881     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882 
883   default:
884     return llvm::None;
885   }
886 }
887 
888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889     OverloadedOperatorKind Op) {
890   if (!AllowRewrittenCandidates)
891     return false;
892   return Op == OO_EqualEqual || Op == OO_Spaceship;
893 }
894 
895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896     ASTContext &Ctx, const FunctionDecl *FD) {
897   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898     return false;
899   // Don't bother adding a reversed candidate that can never be a better
900   // match than the non-reversed version.
901   return FD->getNumParams() != 2 ||
902          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903                                      FD->getParamDecl(1)->getType()) ||
904          FD->hasAttr<EnableIfAttr>();
905 }
906 
907 void OverloadCandidateSet::destroyCandidates() {
908   for (iterator i = begin(), e = end(); i != e; ++i) {
909     for (auto &C : i->Conversions)
910       C.~ImplicitConversionSequence();
911     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912       i->DeductionFailure.Destroy();
913   }
914 }
915 
916 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917   destroyCandidates();
918   SlabAllocator.Reset();
919   NumInlineBytesUsed = 0;
920   Candidates.clear();
921   Functions.clear();
922   Kind = CSK;
923 }
924 
925 namespace {
926   class UnbridgedCastsSet {
927     struct Entry {
928       Expr **Addr;
929       Expr *Saved;
930     };
931     SmallVector<Entry, 2> Entries;
932 
933   public:
934     void save(Sema &S, Expr *&E) {
935       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
936       Entry entry = { &E, E };
937       Entries.push_back(entry);
938       E = S.stripARCUnbridgedCast(E);
939     }
940 
941     void restore() {
942       for (SmallVectorImpl<Entry>::iterator
943              i = Entries.begin(), e = Entries.end(); i != e; ++i)
944         *i->Addr = i->Saved;
945     }
946   };
947 }
948 
949 /// checkPlaceholderForOverload - Do any interesting placeholder-like
950 /// preprocessing on the given expression.
951 ///
952 /// \param unbridgedCasts a collection to which to add unbridged casts;
953 ///   without this, they will be immediately diagnosed as errors
954 ///
955 /// Return true on unrecoverable error.
956 static bool
957 checkPlaceholderForOverload(Sema &S, Expr *&E,
958                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
959   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
960     // We can't handle overloaded expressions here because overload
961     // resolution might reasonably tweak them.
962     if (placeholder->getKind() == BuiltinType::Overload) return false;
963 
964     // If the context potentially accepts unbridged ARC casts, strip
965     // the unbridged cast and add it to the collection for later restoration.
966     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967         unbridgedCasts) {
968       unbridgedCasts->save(S, E);
969       return false;
970     }
971 
972     // Go ahead and check everything else.
973     ExprResult result = S.CheckPlaceholderExpr(E);
974     if (result.isInvalid())
975       return true;
976 
977     E = result.get();
978     return false;
979   }
980 
981   // Nothing to do.
982   return false;
983 }
984 
985 /// checkArgPlaceholdersForOverload - Check a set of call operands for
986 /// placeholders.
987 static bool checkArgPlaceholdersForOverload(Sema &S,
988                                             MultiExprArg Args,
989                                             UnbridgedCastsSet &unbridged) {
990   for (unsigned i = 0, e = Args.size(); i != e; ++i)
991     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992       return true;
993 
994   return false;
995 }
996 
997 /// Determine whether the given New declaration is an overload of the
998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001 /// functions (or function templates) at all. When it does return Ovl_Match or
1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004 /// declaration.
1005 ///
1006 /// Example: Given the following input:
1007 ///
1008 ///   void f(int, float); // #1
1009 ///   void f(int, int); // #2
1010 ///   int f(int, int); // #3
1011 ///
1012 /// When we process #1, there is no previous declaration of "f", so IsOverload
1013 /// will not be used.
1014 ///
1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018 /// unchanged.
1019 ///
1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1024 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1025 ///
1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027 /// by a using declaration. The rules for whether to hide shadow declarations
1028 /// ignore some properties which otherwise figure into a function template's
1029 /// signature.
1030 Sema::OverloadKind
1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032                     NamedDecl *&Match, bool NewIsUsingDecl) {
1033   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034          I != E; ++I) {
1035     NamedDecl *OldD = *I;
1036 
1037     bool OldIsUsingDecl = false;
1038     if (isa<UsingShadowDecl>(OldD)) {
1039       OldIsUsingDecl = true;
1040 
1041       // We can always introduce two using declarations into the same
1042       // context, even if they have identical signatures.
1043       if (NewIsUsingDecl) continue;
1044 
1045       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046     }
1047 
1048     // A using-declaration does not conflict with another declaration
1049     // if one of them is hidden.
1050     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051       continue;
1052 
1053     // If either declaration was introduced by a using declaration,
1054     // we'll need to use slightly different rules for matching.
1055     // Essentially, these rules are the normal rules, except that
1056     // function templates hide function templates with different
1057     // return types or template parameter lists.
1058     bool UseMemberUsingDeclRules =
1059       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060       !New->getFriendObjectKind();
1061 
1062     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066           continue;
1067         }
1068 
1069         if (!isa<FunctionTemplateDecl>(OldD) &&
1070             !shouldLinkPossiblyHiddenDecl(*I, New))
1071           continue;
1072 
1073         Match = *I;
1074         return Ovl_Match;
1075       }
1076 
1077       // Builtins that have custom typechecking or have a reference should
1078       // not be overloadable or redeclarable.
1079       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080         Match = *I;
1081         return Ovl_NonFunction;
1082       }
1083     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084       // We can overload with these, which can show up when doing
1085       // redeclaration checks for UsingDecls.
1086       assert(Old.getLookupKind() == LookupUsingDeclName);
1087     } else if (isa<TagDecl>(OldD)) {
1088       // We can always overload with tags by hiding them.
1089     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090       // Optimistically assume that an unresolved using decl will
1091       // overload; if it doesn't, we'll have to diagnose during
1092       // template instantiation.
1093       //
1094       // Exception: if the scope is dependent and this is not a class
1095       // member, the using declaration can only introduce an enumerator.
1096       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097         Match = *I;
1098         return Ovl_NonFunction;
1099       }
1100     } else {
1101       // (C++ 13p1):
1102       //   Only function declarations can be overloaded; object and type
1103       //   declarations cannot be overloaded.
1104       Match = *I;
1105       return Ovl_NonFunction;
1106     }
1107   }
1108 
1109   // C++ [temp.friend]p1:
1110   //   For a friend function declaration that is not a template declaration:
1111   //    -- if the name of the friend is a qualified or unqualified template-id,
1112   //       [...], otherwise
1113   //    -- if the name of the friend is a qualified-id and a matching
1114   //       non-template function is found in the specified class or namespace,
1115   //       the friend declaration refers to that function, otherwise,
1116   //    -- if the name of the friend is a qualified-id and a matching function
1117   //       template is found in the specified class or namespace, the friend
1118   //       declaration refers to the deduced specialization of that function
1119   //       template, otherwise
1120   //    -- the name shall be an unqualified-id [...]
1121   // If we get here for a qualified friend declaration, we've just reached the
1122   // third bullet. If the type of the friend is dependent, skip this lookup
1123   // until instantiation.
1124   if (New->getFriendObjectKind() && New->getQualifier() &&
1125       !New->getDescribedFunctionTemplate() &&
1126       !New->getDependentSpecializationInfo() &&
1127       !New->getType()->isDependentType()) {
1128     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129     TemplateSpecResult.addAllDecls(Old);
1130     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131                                             /*QualifiedFriend*/true)) {
1132       New->setInvalidDecl();
1133       return Ovl_Overload;
1134     }
1135 
1136     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137     return Ovl_Match;
1138   }
1139 
1140   return Ovl_Overload;
1141 }
1142 
1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145                       bool ConsiderRequiresClauses) {
1146   // C++ [basic.start.main]p2: This function shall not be overloaded.
1147   if (New->isMain())
1148     return false;
1149 
1150   // MSVCRT user defined entry points cannot be overloaded.
1151   if (New->isMSVCRTEntryPoint())
1152     return false;
1153 
1154   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156 
1157   // C++ [temp.fct]p2:
1158   //   A function template can be overloaded with other function templates
1159   //   and with normal (non-template) functions.
1160   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161     return true;
1162 
1163   // Is the function New an overload of the function Old?
1164   QualType OldQType = Context.getCanonicalType(Old->getType());
1165   QualType NewQType = Context.getCanonicalType(New->getType());
1166 
1167   // Compare the signatures (C++ 1.3.10) of the two functions to
1168   // determine whether they are overloads. If we find any mismatch
1169   // in the signature, they are overloads.
1170 
1171   // If either of these functions is a K&R-style function (no
1172   // prototype), then we consider them to have matching signatures.
1173   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175     return false;
1176 
1177   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179 
1180   // The signature of a function includes the types of its
1181   // parameters (C++ 1.3.10), which includes the presence or absence
1182   // of the ellipsis; see C++ DR 357).
1183   if (OldQType != NewQType &&
1184       (OldType->getNumParams() != NewType->getNumParams() ||
1185        OldType->isVariadic() != NewType->isVariadic() ||
1186        !FunctionParamTypesAreEqual(OldType, NewType)))
1187     return true;
1188 
1189   // C++ [temp.over.link]p4:
1190   //   The signature of a function template consists of its function
1191   //   signature, its return type and its template parameter list. The names
1192   //   of the template parameters are significant only for establishing the
1193   //   relationship between the template parameters and the rest of the
1194   //   signature.
1195   //
1196   // We check the return type and template parameter lists for function
1197   // templates first; the remaining checks follow.
1198   //
1199   // However, we don't consider either of these when deciding whether
1200   // a member introduced by a shadow declaration is hidden.
1201   if (!UseMemberUsingDeclRules && NewTemplate &&
1202       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203                                        OldTemplate->getTemplateParameters(),
1204                                        false, TPL_TemplateMatch) ||
1205        !Context.hasSameType(Old->getDeclaredReturnType(),
1206                             New->getDeclaredReturnType())))
1207     return true;
1208 
1209   // If the function is a class member, its signature includes the
1210   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211   //
1212   // As part of this, also check whether one of the member functions
1213   // is static, in which case they are not overloads (C++
1214   // 13.1p2). While not part of the definition of the signature,
1215   // this check is important to determine whether these functions
1216   // can be overloaded.
1217   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219   if (OldMethod && NewMethod &&
1220       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222       if (!UseMemberUsingDeclRules &&
1223           (OldMethod->getRefQualifier() == RQ_None ||
1224            NewMethod->getRefQualifier() == RQ_None)) {
1225         // C++0x [over.load]p2:
1226         //   - Member function declarations with the same name and the same
1227         //     parameter-type-list as well as member function template
1228         //     declarations with the same name, the same parameter-type-list, and
1229         //     the same template parameter lists cannot be overloaded if any of
1230         //     them, but not all, have a ref-qualifier (8.3.5).
1231         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234       }
1235       return true;
1236     }
1237 
1238     // We may not have applied the implicit const for a constexpr member
1239     // function yet (because we haven't yet resolved whether this is a static
1240     // or non-static member function). Add it now, on the assumption that this
1241     // is a redeclaration of OldMethod.
1242     auto OldQuals = OldMethod->getMethodQualifiers();
1243     auto NewQuals = NewMethod->getMethodQualifiers();
1244     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245         !isa<CXXConstructorDecl>(NewMethod))
1246       NewQuals.addConst();
1247     // We do not allow overloading based off of '__restrict'.
1248     OldQuals.removeRestrict();
1249     NewQuals.removeRestrict();
1250     if (OldQuals != NewQuals)
1251       return true;
1252   }
1253 
1254   // Though pass_object_size is placed on parameters and takes an argument, we
1255   // consider it to be a function-level modifier for the sake of function
1256   // identity. Either the function has one or more parameters with
1257   // pass_object_size or it doesn't.
1258   if (functionHasPassObjectSizeParams(New) !=
1259       functionHasPassObjectSizeParams(Old))
1260     return true;
1261 
1262   // enable_if attributes are an order-sensitive part of the signature.
1263   for (specific_attr_iterator<EnableIfAttr>
1264          NewI = New->specific_attr_begin<EnableIfAttr>(),
1265          NewE = New->specific_attr_end<EnableIfAttr>(),
1266          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267          OldE = Old->specific_attr_end<EnableIfAttr>();
1268        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269     if (NewI == NewE || OldI == OldE)
1270       return true;
1271     llvm::FoldingSetNodeID NewID, OldID;
1272     NewI->getCond()->Profile(NewID, Context, true);
1273     OldI->getCond()->Profile(OldID, Context, true);
1274     if (NewID != OldID)
1275       return true;
1276   }
1277 
1278   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279     // Don't allow overloading of destructors.  (In theory we could, but it
1280     // would be a giant change to clang.)
1281     if (!isa<CXXDestructorDecl>(New)) {
1282       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283                          OldTarget = IdentifyCUDATarget(Old);
1284       if (NewTarget != CFT_InvalidTarget) {
1285         assert((OldTarget != CFT_InvalidTarget) &&
1286                "Unexpected invalid target.");
1287 
1288         // Allow overloading of functions with same signature and different CUDA
1289         // target attributes.
1290         if (NewTarget != OldTarget)
1291           return true;
1292       }
1293     }
1294   }
1295 
1296   if (ConsiderRequiresClauses) {
1297     Expr *NewRC = New->getTrailingRequiresClause(),
1298          *OldRC = Old->getTrailingRequiresClause();
1299     if ((NewRC != nullptr) != (OldRC != nullptr))
1300       // RC are most certainly different - these are overloads.
1301       return true;
1302 
1303     if (NewRC) {
1304       llvm::FoldingSetNodeID NewID, OldID;
1305       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307       if (NewID != OldID)
1308         // RCs are not equivalent - these are overloads.
1309         return true;
1310     }
1311   }
1312 
1313   // The signatures match; this is not an overload.
1314   return false;
1315 }
1316 
1317 /// Tries a user-defined conversion from From to ToType.
1318 ///
1319 /// Produces an implicit conversion sequence for when a standard conversion
1320 /// is not an option. See TryImplicitConversion for more information.
1321 static ImplicitConversionSequence
1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323                          bool SuppressUserConversions,
1324                          AllowedExplicit AllowExplicit,
1325                          bool InOverloadResolution,
1326                          bool CStyle,
1327                          bool AllowObjCWritebackConversion,
1328                          bool AllowObjCConversionOnExplicit) {
1329   ImplicitConversionSequence ICS;
1330 
1331   if (SuppressUserConversions) {
1332     // We're not in the case above, so there is no conversion that
1333     // we can perform.
1334     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335     return ICS;
1336   }
1337 
1338   // Attempt user-defined conversion.
1339   OverloadCandidateSet Conversions(From->getExprLoc(),
1340                                    OverloadCandidateSet::CSK_Normal);
1341   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342                                   Conversions, AllowExplicit,
1343                                   AllowObjCConversionOnExplicit)) {
1344   case OR_Success:
1345   case OR_Deleted:
1346     ICS.setUserDefined();
1347     // C++ [over.ics.user]p4:
1348     //   A conversion of an expression of class type to the same class
1349     //   type is given Exact Match rank, and a conversion of an
1350     //   expression of class type to a base class of that type is
1351     //   given Conversion rank, in spite of the fact that a copy
1352     //   constructor (i.e., a user-defined conversion function) is
1353     //   called for those cases.
1354     if (CXXConstructorDecl *Constructor
1355           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356       QualType FromCanon
1357         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358       QualType ToCanon
1359         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360       if (Constructor->isCopyConstructor() &&
1361           (FromCanon == ToCanon ||
1362            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363         // Turn this into a "standard" conversion sequence, so that it
1364         // gets ranked with standard conversion sequences.
1365         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366         ICS.setStandard();
1367         ICS.Standard.setAsIdentityConversion();
1368         ICS.Standard.setFromType(From->getType());
1369         ICS.Standard.setAllToTypes(ToType);
1370         ICS.Standard.CopyConstructor = Constructor;
1371         ICS.Standard.FoundCopyConstructor = Found;
1372         if (ToCanon != FromCanon)
1373           ICS.Standard.Second = ICK_Derived_To_Base;
1374       }
1375     }
1376     break;
1377 
1378   case OR_Ambiguous:
1379     ICS.setAmbiguous();
1380     ICS.Ambiguous.setFromType(From->getType());
1381     ICS.Ambiguous.setToType(ToType);
1382     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383          Cand != Conversions.end(); ++Cand)
1384       if (Cand->Best)
1385         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386     break;
1387 
1388     // Fall through.
1389   case OR_No_Viable_Function:
1390     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391     break;
1392   }
1393 
1394   return ICS;
1395 }
1396 
1397 /// TryImplicitConversion - Attempt to perform an implicit conversion
1398 /// from the given expression (Expr) to the given type (ToType). This
1399 /// function returns an implicit conversion sequence that can be used
1400 /// to perform the initialization. Given
1401 ///
1402 ///   void f(float f);
1403 ///   void g(int i) { f(i); }
1404 ///
1405 /// this routine would produce an implicit conversion sequence to
1406 /// describe the initialization of f from i, which will be a standard
1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409 //
1410 /// Note that this routine only determines how the conversion can be
1411 /// performed; it does not actually perform the conversion. As such,
1412 /// it will not produce any diagnostics if no conversion is available,
1413 /// but will instead return an implicit conversion sequence of kind
1414 /// "BadConversion".
1415 ///
1416 /// If @p SuppressUserConversions, then user-defined conversions are
1417 /// not permitted.
1418 /// If @p AllowExplicit, then explicit user-defined conversions are
1419 /// permitted.
1420 ///
1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422 /// writeback conversion, which allows __autoreleasing id* parameters to
1423 /// be initialized with __strong id* or __weak id* arguments.
1424 static ImplicitConversionSequence
1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426                       bool SuppressUserConversions,
1427                       AllowedExplicit AllowExplicit,
1428                       bool InOverloadResolution,
1429                       bool CStyle,
1430                       bool AllowObjCWritebackConversion,
1431                       bool AllowObjCConversionOnExplicit) {
1432   ImplicitConversionSequence ICS;
1433   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435     ICS.setStandard();
1436     return ICS;
1437   }
1438 
1439   if (!S.getLangOpts().CPlusPlus) {
1440     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441     return ICS;
1442   }
1443 
1444   // C++ [over.ics.user]p4:
1445   //   A conversion of an expression of class type to the same class
1446   //   type is given Exact Match rank, and a conversion of an
1447   //   expression of class type to a base class of that type is
1448   //   given Conversion rank, in spite of the fact that a copy/move
1449   //   constructor (i.e., a user-defined conversion function) is
1450   //   called for those cases.
1451   QualType FromType = From->getType();
1452   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455     ICS.setStandard();
1456     ICS.Standard.setAsIdentityConversion();
1457     ICS.Standard.setFromType(FromType);
1458     ICS.Standard.setAllToTypes(ToType);
1459 
1460     // We don't actually check at this point whether there is a valid
1461     // copy/move constructor, since overloading just assumes that it
1462     // exists. When we actually perform initialization, we'll find the
1463     // appropriate constructor to copy the returned object, if needed.
1464     ICS.Standard.CopyConstructor = nullptr;
1465 
1466     // Determine whether this is considered a derived-to-base conversion.
1467     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468       ICS.Standard.Second = ICK_Derived_To_Base;
1469 
1470     return ICS;
1471   }
1472 
1473   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474                                   AllowExplicit, InOverloadResolution, CStyle,
1475                                   AllowObjCWritebackConversion,
1476                                   AllowObjCConversionOnExplicit);
1477 }
1478 
1479 ImplicitConversionSequence
1480 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481                             bool SuppressUserConversions,
1482                             AllowedExplicit AllowExplicit,
1483                             bool InOverloadResolution,
1484                             bool CStyle,
1485                             bool AllowObjCWritebackConversion) {
1486   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487                                  AllowExplicit, InOverloadResolution, CStyle,
1488                                  AllowObjCWritebackConversion,
1489                                  /*AllowObjCConversionOnExplicit=*/false);
1490 }
1491 
1492 /// PerformImplicitConversion - Perform an implicit conversion of the
1493 /// expression From to the type ToType. Returns the
1494 /// converted expression. Flavor is the kind of conversion we're
1495 /// performing, used in the error message. If @p AllowExplicit,
1496 /// explicit user-defined conversions are permitted.
1497 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498                                            AssignmentAction Action,
1499                                            bool AllowExplicit) {
1500   if (checkPlaceholderForOverload(*this, From))
1501     return ExprError();
1502 
1503   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504   bool AllowObjCWritebackConversion
1505     = getLangOpts().ObjCAutoRefCount &&
1506       (Action == AA_Passing || Action == AA_Sending);
1507   if (getLangOpts().ObjC)
1508     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509                                       From->getType(), From);
1510   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511       *this, From, ToType,
1512       /*SuppressUserConversions=*/false,
1513       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514       /*InOverloadResolution=*/false,
1515       /*CStyle=*/false, AllowObjCWritebackConversion,
1516       /*AllowObjCConversionOnExplicit=*/false);
1517   return PerformImplicitConversion(From, ToType, ICS, Action);
1518 }
1519 
1520 /// Determine whether the conversion from FromType to ToType is a valid
1521 /// conversion that strips "noexcept" or "noreturn" off the nested function
1522 /// type.
1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524                                 QualType &ResultTy) {
1525   if (Context.hasSameUnqualifiedType(FromType, ToType))
1526     return false;
1527 
1528   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529   //                    or F(t noexcept) -> F(t)
1530   // where F adds one of the following at most once:
1531   //   - a pointer
1532   //   - a member pointer
1533   //   - a block pointer
1534   // Changes here need matching changes in FindCompositePointerType.
1535   CanQualType CanTo = Context.getCanonicalType(ToType);
1536   CanQualType CanFrom = Context.getCanonicalType(FromType);
1537   Type::TypeClass TyClass = CanTo->getTypeClass();
1538   if (TyClass != CanFrom->getTypeClass()) return false;
1539   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540     if (TyClass == Type::Pointer) {
1541       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543     } else if (TyClass == Type::BlockPointer) {
1544       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546     } else if (TyClass == Type::MemberPointer) {
1547       auto ToMPT = CanTo.castAs<MemberPointerType>();
1548       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549       // A function pointer conversion cannot change the class of the function.
1550       if (ToMPT->getClass() != FromMPT->getClass())
1551         return false;
1552       CanTo = ToMPT->getPointeeType();
1553       CanFrom = FromMPT->getPointeeType();
1554     } else {
1555       return false;
1556     }
1557 
1558     TyClass = CanTo->getTypeClass();
1559     if (TyClass != CanFrom->getTypeClass()) return false;
1560     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561       return false;
1562   }
1563 
1564   const auto *FromFn = cast<FunctionType>(CanFrom);
1565   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566 
1567   const auto *ToFn = cast<FunctionType>(CanTo);
1568   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569 
1570   bool Changed = false;
1571 
1572   // Drop 'noreturn' if not present in target type.
1573   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575     Changed = true;
1576   }
1577 
1578   // Drop 'noexcept' if not present in target type.
1579   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582       FromFn = cast<FunctionType>(
1583           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584                                                    EST_None)
1585                  .getTypePtr());
1586       Changed = true;
1587     }
1588 
1589     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590     // only if the ExtParameterInfo lists of the two function prototypes can be
1591     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593     bool CanUseToFPT, CanUseFromFPT;
1594     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595                                       CanUseFromFPT, NewParamInfos) &&
1596         CanUseToFPT && !CanUseFromFPT) {
1597       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598       ExtInfo.ExtParameterInfos =
1599           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601                                             FromFPT->getParamTypes(), ExtInfo);
1602       FromFn = QT->getAs<FunctionType>();
1603       Changed = true;
1604     }
1605   }
1606 
1607   if (!Changed)
1608     return false;
1609 
1610   assert(QualType(FromFn, 0).isCanonical());
1611   if (QualType(FromFn, 0) != CanTo) return false;
1612 
1613   ResultTy = ToType;
1614   return true;
1615 }
1616 
1617 /// Determine whether the conversion from FromType to ToType is a valid
1618 /// vector conversion.
1619 ///
1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1621 /// conversion.
1622 static bool IsVectorConversion(Sema &S, QualType FromType,
1623                                QualType ToType, ImplicitConversionKind &ICK) {
1624   // We need at least one of these types to be a vector type to have a vector
1625   // conversion.
1626   if (!ToType->isVectorType() && !FromType->isVectorType())
1627     return false;
1628 
1629   // Identical types require no conversions.
1630   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631     return false;
1632 
1633   // There are no conversions between extended vector types, only identity.
1634   if (ToType->isExtVectorType()) {
1635     // There are no conversions between extended vector types other than the
1636     // identity conversion.
1637     if (FromType->isExtVectorType())
1638       return false;
1639 
1640     // Vector splat from any arithmetic type to a vector.
1641     if (FromType->isArithmeticType()) {
1642       ICK = ICK_Vector_Splat;
1643       return true;
1644     }
1645   }
1646 
1647   if ((ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) &&
1648       S.Context.areCompatibleSveTypes(FromType, ToType)) {
1649     ICK = ICK_SVE_Vector_Conversion;
1650     return true;
1651   }
1652 
1653   // We can perform the conversion between vector types in the following cases:
1654   // 1)vector types are equivalent AltiVec and GCC vector types
1655   // 2)lax vector conversions are permitted and the vector types are of the
1656   //   same size
1657   // 3)the destination type does not have the ARM MVE strict-polymorphism
1658   //   attribute, which inhibits lax vector conversion for overload resolution
1659   //   only
1660   if (ToType->isVectorType() && FromType->isVectorType()) {
1661     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662         (S.isLaxVectorConversion(FromType, ToType) &&
1663          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664       ICK = ICK_Vector_Conversion;
1665       return true;
1666     }
1667   }
1668 
1669   return false;
1670 }
1671 
1672 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1673                                 bool InOverloadResolution,
1674                                 StandardConversionSequence &SCS,
1675                                 bool CStyle);
1676 
1677 /// IsStandardConversion - Determines whether there is a standard
1678 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1679 /// expression From to the type ToType. Standard conversion sequences
1680 /// only consider non-class types; for conversions that involve class
1681 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1682 /// contain the standard conversion sequence required to perform this
1683 /// conversion and this routine will return true. Otherwise, this
1684 /// routine will return false and the value of SCS is unspecified.
1685 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1686                                  bool InOverloadResolution,
1687                                  StandardConversionSequence &SCS,
1688                                  bool CStyle,
1689                                  bool AllowObjCWritebackConversion) {
1690   QualType FromType = From->getType();
1691 
1692   // Standard conversions (C++ [conv])
1693   SCS.setAsIdentityConversion();
1694   SCS.IncompatibleObjC = false;
1695   SCS.setFromType(FromType);
1696   SCS.CopyConstructor = nullptr;
1697 
1698   // There are no standard conversions for class types in C++, so
1699   // abort early. When overloading in C, however, we do permit them.
1700   if (S.getLangOpts().CPlusPlus &&
1701       (FromType->isRecordType() || ToType->isRecordType()))
1702     return false;
1703 
1704   // The first conversion can be an lvalue-to-rvalue conversion,
1705   // array-to-pointer conversion, or function-to-pointer conversion
1706   // (C++ 4p1).
1707 
1708   if (FromType == S.Context.OverloadTy) {
1709     DeclAccessPair AccessPair;
1710     if (FunctionDecl *Fn
1711           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1712                                                  AccessPair)) {
1713       // We were able to resolve the address of the overloaded function,
1714       // so we can convert to the type of that function.
1715       FromType = Fn->getType();
1716       SCS.setFromType(FromType);
1717 
1718       // we can sometimes resolve &foo<int> regardless of ToType, so check
1719       // if the type matches (identity) or we are converting to bool
1720       if (!S.Context.hasSameUnqualifiedType(
1721                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1722         QualType resultTy;
1723         // if the function type matches except for [[noreturn]], it's ok
1724         if (!S.IsFunctionConversion(FromType,
1725               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1726           // otherwise, only a boolean conversion is standard
1727           if (!ToType->isBooleanType())
1728             return false;
1729       }
1730 
1731       // Check if the "from" expression is taking the address of an overloaded
1732       // function and recompute the FromType accordingly. Take advantage of the
1733       // fact that non-static member functions *must* have such an address-of
1734       // expression.
1735       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1736       if (Method && !Method->isStatic()) {
1737         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1738                "Non-unary operator on non-static member address");
1739         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1740                == UO_AddrOf &&
1741                "Non-address-of operator on non-static member address");
1742         const Type *ClassType
1743           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1744         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1745       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1746         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1747                UO_AddrOf &&
1748                "Non-address-of operator for overloaded function expression");
1749         FromType = S.Context.getPointerType(FromType);
1750       }
1751 
1752       // Check that we've computed the proper type after overload resolution.
1753       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1754       // be calling it from within an NDEBUG block.
1755       assert(S.Context.hasSameType(
1756         FromType,
1757         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1758     } else {
1759       return false;
1760     }
1761   }
1762   // Lvalue-to-rvalue conversion (C++11 4.1):
1763   //   A glvalue (3.10) of a non-function, non-array type T can
1764   //   be converted to a prvalue.
1765   bool argIsLValue = From->isGLValue();
1766   if (argIsLValue &&
1767       !FromType->isFunctionType() && !FromType->isArrayType() &&
1768       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769     SCS.First = ICK_Lvalue_To_Rvalue;
1770 
1771     // C11 6.3.2.1p2:
1772     //   ... if the lvalue has atomic type, the value has the non-atomic version
1773     //   of the type of the lvalue ...
1774     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775       FromType = Atomic->getValueType();
1776 
1777     // If T is a non-class type, the type of the rvalue is the
1778     // cv-unqualified version of T. Otherwise, the type of the rvalue
1779     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780     // just strip the qualifiers because they don't matter.
1781     FromType = FromType.getUnqualifiedType();
1782   } else if (FromType->isArrayType()) {
1783     // Array-to-pointer conversion (C++ 4.2)
1784     SCS.First = ICK_Array_To_Pointer;
1785 
1786     // An lvalue or rvalue of type "array of N T" or "array of unknown
1787     // bound of T" can be converted to an rvalue of type "pointer to
1788     // T" (C++ 4.2p1).
1789     FromType = S.Context.getArrayDecayedType(FromType);
1790 
1791     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792       // This conversion is deprecated in C++03 (D.4)
1793       SCS.DeprecatedStringLiteralToCharPtr = true;
1794 
1795       // For the purpose of ranking in overload resolution
1796       // (13.3.3.1.1), this conversion is considered an
1797       // array-to-pointer conversion followed by a qualification
1798       // conversion (4.4). (C++ 4.2p2)
1799       SCS.Second = ICK_Identity;
1800       SCS.Third = ICK_Qualification;
1801       SCS.QualificationIncludesObjCLifetime = false;
1802       SCS.setAllToTypes(FromType);
1803       return true;
1804     }
1805   } else if (FromType->isFunctionType() && argIsLValue) {
1806     // Function-to-pointer conversion (C++ 4.3).
1807     SCS.First = ICK_Function_To_Pointer;
1808 
1809     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811         if (!S.checkAddressOfFunctionIsAvailable(FD))
1812           return false;
1813 
1814     // An lvalue of function type T can be converted to an rvalue of
1815     // type "pointer to T." The result is a pointer to the
1816     // function. (C++ 4.3p1).
1817     FromType = S.Context.getPointerType(FromType);
1818   } else {
1819     // We don't require any conversions for the first step.
1820     SCS.First = ICK_Identity;
1821   }
1822   SCS.setToType(0, FromType);
1823 
1824   // The second conversion can be an integral promotion, floating
1825   // point promotion, integral conversion, floating point conversion,
1826   // floating-integral conversion, pointer conversion,
1827   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828   // For overloading in C, this can also be a "compatible-type"
1829   // conversion.
1830   bool IncompatibleObjC = false;
1831   ImplicitConversionKind SecondICK = ICK_Identity;
1832   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833     // The unqualified versions of the types are the same: there's no
1834     // conversion to do.
1835     SCS.Second = ICK_Identity;
1836   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837     // Integral promotion (C++ 4.5).
1838     SCS.Second = ICK_Integral_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841     // Floating point promotion (C++ 4.6).
1842     SCS.Second = ICK_Floating_Promotion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (S.IsComplexPromotion(FromType, ToType)) {
1845     // Complex promotion (Clang extension)
1846     SCS.Second = ICK_Complex_Promotion;
1847     FromType = ToType.getUnqualifiedType();
1848   } else if (ToType->isBooleanType() &&
1849              (FromType->isArithmeticType() ||
1850               FromType->isAnyPointerType() ||
1851               FromType->isBlockPointerType() ||
1852               FromType->isMemberPointerType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double and __float128 if
1872     // their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874 
1875     // Conversions between bfloat and other floats are not permitted.
1876     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877       return false;
1878     if (&S.Context.getFloatTypeSemantics(FromType) !=
1879         &S.Context.getFloatTypeSemantics(ToType)) {
1880       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1881                                     ToType == S.Context.LongDoubleTy) ||
1882                                    (FromType == S.Context.LongDoubleTy &&
1883                                     ToType == S.Context.Float128Ty));
1884       if (Float128AndLongDouble &&
1885           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1886            &llvm::APFloat::PPCDoubleDouble()))
1887         return false;
1888     }
1889     // Floating point conversions (C++ 4.8).
1890     SCS.Second = ICK_Floating_Conversion;
1891     FromType = ToType.getUnqualifiedType();
1892   } else if ((FromType->isRealFloatingType() &&
1893               ToType->isIntegralType(S.Context)) ||
1894              (FromType->isIntegralOrUnscopedEnumerationType() &&
1895               ToType->isRealFloatingType())) {
1896     // Conversions between bfloat and int are not permitted.
1897     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1898       return false;
1899 
1900     // Floating-integral conversions (C++ 4.9).
1901     SCS.Second = ICK_Floating_Integral;
1902     FromType = ToType.getUnqualifiedType();
1903   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1904     SCS.Second = ICK_Block_Pointer_Conversion;
1905   } else if (AllowObjCWritebackConversion &&
1906              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1907     SCS.Second = ICK_Writeback_Conversion;
1908   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1909                                    FromType, IncompatibleObjC)) {
1910     // Pointer conversions (C++ 4.10).
1911     SCS.Second = ICK_Pointer_Conversion;
1912     SCS.IncompatibleObjC = IncompatibleObjC;
1913     FromType = FromType.getUnqualifiedType();
1914   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1915                                          InOverloadResolution, FromType)) {
1916     // Pointer to member conversions (4.11).
1917     SCS.Second = ICK_Pointer_Member;
1918   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1919     SCS.Second = SecondICK;
1920     FromType = ToType.getUnqualifiedType();
1921   } else if (!S.getLangOpts().CPlusPlus &&
1922              S.Context.typesAreCompatible(ToType, FromType)) {
1923     // Compatible conversions (Clang extension for C function overloading)
1924     SCS.Second = ICK_Compatible_Conversion;
1925     FromType = ToType.getUnqualifiedType();
1926   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1927                                              InOverloadResolution,
1928                                              SCS, CStyle)) {
1929     SCS.Second = ICK_TransparentUnionConversion;
1930     FromType = ToType;
1931   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1932                                  CStyle)) {
1933     // tryAtomicConversion has updated the standard conversion sequence
1934     // appropriately.
1935     return true;
1936   } else if (ToType->isEventT() &&
1937              From->isIntegerConstantExpr(S.getASTContext()) &&
1938              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1939     SCS.Second = ICK_Zero_Event_Conversion;
1940     FromType = ToType;
1941   } else if (ToType->isQueueT() &&
1942              From->isIntegerConstantExpr(S.getASTContext()) &&
1943              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1944     SCS.Second = ICK_Zero_Queue_Conversion;
1945     FromType = ToType;
1946   } else if (ToType->isSamplerT() &&
1947              From->isIntegerConstantExpr(S.getASTContext())) {
1948     SCS.Second = ICK_Compatible_Conversion;
1949     FromType = ToType;
1950   } else {
1951     // No second conversion required.
1952     SCS.Second = ICK_Identity;
1953   }
1954   SCS.setToType(1, FromType);
1955 
1956   // The third conversion can be a function pointer conversion or a
1957   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1958   bool ObjCLifetimeConversion;
1959   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1960     // Function pointer conversions (removing 'noexcept') including removal of
1961     // 'noreturn' (Clang extension).
1962     SCS.Third = ICK_Function_Conversion;
1963   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1964                                          ObjCLifetimeConversion)) {
1965     SCS.Third = ICK_Qualification;
1966     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1967     FromType = ToType;
1968   } else {
1969     // No conversion required
1970     SCS.Third = ICK_Identity;
1971   }
1972 
1973   // C++ [over.best.ics]p6:
1974   //   [...] Any difference in top-level cv-qualification is
1975   //   subsumed by the initialization itself and does not constitute
1976   //   a conversion. [...]
1977   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1978   QualType CanonTo = S.Context.getCanonicalType(ToType);
1979   if (CanonFrom.getLocalUnqualifiedType()
1980                                      == CanonTo.getLocalUnqualifiedType() &&
1981       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1982     FromType = ToType;
1983     CanonFrom = CanonTo;
1984   }
1985 
1986   SCS.setToType(2, FromType);
1987 
1988   if (CanonFrom == CanonTo)
1989     return true;
1990 
1991   // If we have not converted the argument type to the parameter type,
1992   // this is a bad conversion sequence, unless we're resolving an overload in C.
1993   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1994     return false;
1995 
1996   ExprResult ER = ExprResult{From};
1997   Sema::AssignConvertType Conv =
1998       S.CheckSingleAssignmentConstraints(ToType, ER,
1999                                          /*Diagnose=*/false,
2000                                          /*DiagnoseCFAudited=*/false,
2001                                          /*ConvertRHS=*/false);
2002   ImplicitConversionKind SecondConv;
2003   switch (Conv) {
2004   case Sema::Compatible:
2005     SecondConv = ICK_C_Only_Conversion;
2006     break;
2007   // For our purposes, discarding qualifiers is just as bad as using an
2008   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2009   // qualifiers, as well.
2010   case Sema::CompatiblePointerDiscardsQualifiers:
2011   case Sema::IncompatiblePointer:
2012   case Sema::IncompatiblePointerSign:
2013     SecondConv = ICK_Incompatible_Pointer_Conversion;
2014     break;
2015   default:
2016     return false;
2017   }
2018 
2019   // First can only be an lvalue conversion, so we pretend that this was the
2020   // second conversion. First should already be valid from earlier in the
2021   // function.
2022   SCS.Second = SecondConv;
2023   SCS.setToType(1, ToType);
2024 
2025   // Third is Identity, because Second should rank us worse than any other
2026   // conversion. This could also be ICK_Qualification, but it's simpler to just
2027   // lump everything in with the second conversion, and we don't gain anything
2028   // from making this ICK_Qualification.
2029   SCS.Third = ICK_Identity;
2030   SCS.setToType(2, ToType);
2031   return true;
2032 }
2033 
2034 static bool
2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2036                                      QualType &ToType,
2037                                      bool InOverloadResolution,
2038                                      StandardConversionSequence &SCS,
2039                                      bool CStyle) {
2040 
2041   const RecordType *UT = ToType->getAsUnionType();
2042   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2043     return false;
2044   // The field to initialize within the transparent union.
2045   RecordDecl *UD = UT->getDecl();
2046   // It's compatible if the expression matches any of the fields.
2047   for (const auto *it : UD->fields()) {
2048     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2049                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2050       ToType = it->getType();
2051       return true;
2052     }
2053   }
2054   return false;
2055 }
2056 
2057 /// IsIntegralPromotion - Determines whether the conversion from the
2058 /// expression From (whose potentially-adjusted type is FromType) to
2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2060 /// sets PromotedType to the promoted type.
2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2062   const BuiltinType *To = ToType->getAs<BuiltinType>();
2063   // All integers are built-in.
2064   if (!To) {
2065     return false;
2066   }
2067 
2068   // An rvalue of type char, signed char, unsigned char, short int, or
2069   // unsigned short int can be converted to an rvalue of type int if
2070   // int can represent all the values of the source type; otherwise,
2071   // the source rvalue can be converted to an rvalue of type unsigned
2072   // int (C++ 4.5p1).
2073   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2074       !FromType->isEnumeralType()) {
2075     if (// We can promote any signed, promotable integer type to an int
2076         (FromType->isSignedIntegerType() ||
2077          // We can promote any unsigned integer type whose size is
2078          // less than int to an int.
2079          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2080       return To->getKind() == BuiltinType::Int;
2081     }
2082 
2083     return To->getKind() == BuiltinType::UInt;
2084   }
2085 
2086   // C++11 [conv.prom]p3:
2087   //   A prvalue of an unscoped enumeration type whose underlying type is not
2088   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2089   //   following types that can represent all the values of the enumeration
2090   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2091   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2092   //   long long int. If none of the types in that list can represent all the
2093   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2094   //   type can be converted to an rvalue a prvalue of the extended integer type
2095   //   with lowest integer conversion rank (4.13) greater than the rank of long
2096   //   long in which all the values of the enumeration can be represented. If
2097   //   there are two such extended types, the signed one is chosen.
2098   // C++11 [conv.prom]p4:
2099   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2100   //   can be converted to a prvalue of its underlying type. Moreover, if
2101   //   integral promotion can be applied to its underlying type, a prvalue of an
2102   //   unscoped enumeration type whose underlying type is fixed can also be
2103   //   converted to a prvalue of the promoted underlying type.
2104   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2105     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2106     // provided for a scoped enumeration.
2107     if (FromEnumType->getDecl()->isScoped())
2108       return false;
2109 
2110     // We can perform an integral promotion to the underlying type of the enum,
2111     // even if that's not the promoted type. Note that the check for promoting
2112     // the underlying type is based on the type alone, and does not consider
2113     // the bitfield-ness of the actual source expression.
2114     if (FromEnumType->getDecl()->isFixed()) {
2115       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2116       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2117              IsIntegralPromotion(nullptr, Underlying, ToType);
2118     }
2119 
2120     // We have already pre-calculated the promotion type, so this is trivial.
2121     if (ToType->isIntegerType() &&
2122         isCompleteType(From->getBeginLoc(), FromType))
2123       return Context.hasSameUnqualifiedType(
2124           ToType, FromEnumType->getDecl()->getPromotionType());
2125 
2126     // C++ [conv.prom]p5:
2127     //   If the bit-field has an enumerated type, it is treated as any other
2128     //   value of that type for promotion purposes.
2129     //
2130     // ... so do not fall through into the bit-field checks below in C++.
2131     if (getLangOpts().CPlusPlus)
2132       return false;
2133   }
2134 
2135   // C++0x [conv.prom]p2:
2136   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2137   //   to an rvalue a prvalue of the first of the following types that can
2138   //   represent all the values of its underlying type: int, unsigned int,
2139   //   long int, unsigned long int, long long int, or unsigned long long int.
2140   //   If none of the types in that list can represent all the values of its
2141   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2142   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2143   //   type.
2144   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2145       ToType->isIntegerType()) {
2146     // Determine whether the type we're converting from is signed or
2147     // unsigned.
2148     bool FromIsSigned = FromType->isSignedIntegerType();
2149     uint64_t FromSize = Context.getTypeSize(FromType);
2150 
2151     // The types we'll try to promote to, in the appropriate
2152     // order. Try each of these types.
2153     QualType PromoteTypes[6] = {
2154       Context.IntTy, Context.UnsignedIntTy,
2155       Context.LongTy, Context.UnsignedLongTy ,
2156       Context.LongLongTy, Context.UnsignedLongLongTy
2157     };
2158     for (int Idx = 0; Idx < 6; ++Idx) {
2159       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2160       if (FromSize < ToSize ||
2161           (FromSize == ToSize &&
2162            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2163         // We found the type that we can promote to. If this is the
2164         // type we wanted, we have a promotion. Otherwise, no
2165         // promotion.
2166         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2167       }
2168     }
2169   }
2170 
2171   // An rvalue for an integral bit-field (9.6) can be converted to an
2172   // rvalue of type int if int can represent all the values of the
2173   // bit-field; otherwise, it can be converted to unsigned int if
2174   // unsigned int can represent all the values of the bit-field. If
2175   // the bit-field is larger yet, no integral promotion applies to
2176   // it. If the bit-field has an enumerated type, it is treated as any
2177   // other value of that type for promotion purposes (C++ 4.5p3).
2178   // FIXME: We should delay checking of bit-fields until we actually perform the
2179   // conversion.
2180   //
2181   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2182   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2183   // bit-fields and those whose underlying type is larger than int) for GCC
2184   // compatibility.
2185   if (From) {
2186     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2187       Optional<llvm::APSInt> BitWidth;
2188       if (FromType->isIntegralType(Context) &&
2189           (BitWidth =
2190                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2191         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2192         ToSize = Context.getTypeSize(ToType);
2193 
2194         // Are we promoting to an int from a bitfield that fits in an int?
2195         if (*BitWidth < ToSize ||
2196             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2197           return To->getKind() == BuiltinType::Int;
2198         }
2199 
2200         // Are we promoting to an unsigned int from an unsigned bitfield
2201         // that fits into an unsigned int?
2202         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2203           return To->getKind() == BuiltinType::UInt;
2204         }
2205 
2206         return false;
2207       }
2208     }
2209   }
2210 
2211   // An rvalue of type bool can be converted to an rvalue of type int,
2212   // with false becoming zero and true becoming one (C++ 4.5p4).
2213   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2214     return true;
2215   }
2216 
2217   return false;
2218 }
2219 
2220 /// IsFloatingPointPromotion - Determines whether the conversion from
2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2222 /// returns true and sets PromotedType to the promoted type.
2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2224   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2225     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2226       /// An rvalue of type float can be converted to an rvalue of type
2227       /// double. (C++ 4.6p1).
2228       if (FromBuiltin->getKind() == BuiltinType::Float &&
2229           ToBuiltin->getKind() == BuiltinType::Double)
2230         return true;
2231 
2232       // C99 6.3.1.5p1:
2233       //   When a float is promoted to double or long double, or a
2234       //   double is promoted to long double [...].
2235       if (!getLangOpts().CPlusPlus &&
2236           (FromBuiltin->getKind() == BuiltinType::Float ||
2237            FromBuiltin->getKind() == BuiltinType::Double) &&
2238           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2239            ToBuiltin->getKind() == BuiltinType::Float128))
2240         return true;
2241 
2242       // Half can be promoted to float.
2243       if (!getLangOpts().NativeHalfType &&
2244            FromBuiltin->getKind() == BuiltinType::Half &&
2245           ToBuiltin->getKind() == BuiltinType::Float)
2246         return true;
2247     }
2248 
2249   return false;
2250 }
2251 
2252 /// Determine if a conversion is a complex promotion.
2253 ///
2254 /// A complex promotion is defined as a complex -> complex conversion
2255 /// where the conversion between the underlying real types is a
2256 /// floating-point or integral promotion.
2257 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2258   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2259   if (!FromComplex)
2260     return false;
2261 
2262   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2263   if (!ToComplex)
2264     return false;
2265 
2266   return IsFloatingPointPromotion(FromComplex->getElementType(),
2267                                   ToComplex->getElementType()) ||
2268     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2269                         ToComplex->getElementType());
2270 }
2271 
2272 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2273 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2274 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2275 /// if non-empty, will be a pointer to ToType that may or may not have
2276 /// the right set of qualifiers on its pointee.
2277 ///
2278 static QualType
2279 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2280                                    QualType ToPointee, QualType ToType,
2281                                    ASTContext &Context,
2282                                    bool StripObjCLifetime = false) {
2283   assert((FromPtr->getTypeClass() == Type::Pointer ||
2284           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2285          "Invalid similarly-qualified pointer type");
2286 
2287   /// Conversions to 'id' subsume cv-qualifier conversions.
2288   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2289     return ToType.getUnqualifiedType();
2290 
2291   QualType CanonFromPointee
2292     = Context.getCanonicalType(FromPtr->getPointeeType());
2293   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2294   Qualifiers Quals = CanonFromPointee.getQualifiers();
2295 
2296   if (StripObjCLifetime)
2297     Quals.removeObjCLifetime();
2298 
2299   // Exact qualifier match -> return the pointer type we're converting to.
2300   if (CanonToPointee.getLocalQualifiers() == Quals) {
2301     // ToType is exactly what we need. Return it.
2302     if (!ToType.isNull())
2303       return ToType.getUnqualifiedType();
2304 
2305     // Build a pointer to ToPointee. It has the right qualifiers
2306     // already.
2307     if (isa<ObjCObjectPointerType>(ToType))
2308       return Context.getObjCObjectPointerType(ToPointee);
2309     return Context.getPointerType(ToPointee);
2310   }
2311 
2312   // Just build a canonical type that has the right qualifiers.
2313   QualType QualifiedCanonToPointee
2314     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2315 
2316   if (isa<ObjCObjectPointerType>(ToType))
2317     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2318   return Context.getPointerType(QualifiedCanonToPointee);
2319 }
2320 
2321 static bool isNullPointerConstantForConversion(Expr *Expr,
2322                                                bool InOverloadResolution,
2323                                                ASTContext &Context) {
2324   // Handle value-dependent integral null pointer constants correctly.
2325   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2326   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2327       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2328     return !InOverloadResolution;
2329 
2330   return Expr->isNullPointerConstant(Context,
2331                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2332                                         : Expr::NPC_ValueDependentIsNull);
2333 }
2334 
2335 /// IsPointerConversion - Determines whether the conversion of the
2336 /// expression From, which has the (possibly adjusted) type FromType,
2337 /// can be converted to the type ToType via a pointer conversion (C++
2338 /// 4.10). If so, returns true and places the converted type (that
2339 /// might differ from ToType in its cv-qualifiers at some level) into
2340 /// ConvertedType.
2341 ///
2342 /// This routine also supports conversions to and from block pointers
2343 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2344 /// pointers to interfaces. FIXME: Once we've determined the
2345 /// appropriate overloading rules for Objective-C, we may want to
2346 /// split the Objective-C checks into a different routine; however,
2347 /// GCC seems to consider all of these conversions to be pointer
2348 /// conversions, so for now they live here. IncompatibleObjC will be
2349 /// set if the conversion is an allowed Objective-C conversion that
2350 /// should result in a warning.
2351 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2352                                bool InOverloadResolution,
2353                                QualType& ConvertedType,
2354                                bool &IncompatibleObjC) {
2355   IncompatibleObjC = false;
2356   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2357                               IncompatibleObjC))
2358     return true;
2359 
2360   // Conversion from a null pointer constant to any Objective-C pointer type.
2361   if (ToType->isObjCObjectPointerType() &&
2362       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2363     ConvertedType = ToType;
2364     return true;
2365   }
2366 
2367   // Blocks: Block pointers can be converted to void*.
2368   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2369       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2370     ConvertedType = ToType;
2371     return true;
2372   }
2373   // Blocks: A null pointer constant can be converted to a block
2374   // pointer type.
2375   if (ToType->isBlockPointerType() &&
2376       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2377     ConvertedType = ToType;
2378     return true;
2379   }
2380 
2381   // If the left-hand-side is nullptr_t, the right side can be a null
2382   // pointer constant.
2383   if (ToType->isNullPtrType() &&
2384       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385     ConvertedType = ToType;
2386     return true;
2387   }
2388 
2389   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2390   if (!ToTypePtr)
2391     return false;
2392 
2393   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2394   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2395     ConvertedType = ToType;
2396     return true;
2397   }
2398 
2399   // Beyond this point, both types need to be pointers
2400   // , including objective-c pointers.
2401   QualType ToPointeeType = ToTypePtr->getPointeeType();
2402   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2403       !getLangOpts().ObjCAutoRefCount) {
2404     ConvertedType = BuildSimilarlyQualifiedPointerType(
2405                                       FromType->getAs<ObjCObjectPointerType>(),
2406                                                        ToPointeeType,
2407                                                        ToType, Context);
2408     return true;
2409   }
2410   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2411   if (!FromTypePtr)
2412     return false;
2413 
2414   QualType FromPointeeType = FromTypePtr->getPointeeType();
2415 
2416   // If the unqualified pointee types are the same, this can't be a
2417   // pointer conversion, so don't do all of the work below.
2418   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2419     return false;
2420 
2421   // An rvalue of type "pointer to cv T," where T is an object type,
2422   // can be converted to an rvalue of type "pointer to cv void" (C++
2423   // 4.10p2).
2424   if (FromPointeeType->isIncompleteOrObjectType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context,
2429                                                    /*StripObjCLifetime=*/true);
2430     return true;
2431   }
2432 
2433   // MSVC allows implicit function to void* type conversion.
2434   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2435       ToPointeeType->isVoidType()) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // When we're overloading in C, we allow a special kind of pointer
2443   // conversion for compatible-but-not-identical pointee types.
2444   if (!getLangOpts().CPlusPlus &&
2445       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2446     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2447                                                        ToPointeeType,
2448                                                        ToType, Context);
2449     return true;
2450   }
2451 
2452   // C++ [conv.ptr]p3:
2453   //
2454   //   An rvalue of type "pointer to cv D," where D is a class type,
2455   //   can be converted to an rvalue of type "pointer to cv B," where
2456   //   B is a base class (clause 10) of D. If B is an inaccessible
2457   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2458   //   necessitates this conversion is ill-formed. The result of the
2459   //   conversion is a pointer to the base class sub-object of the
2460   //   derived class object. The null pointer value is converted to
2461   //   the null pointer value of the destination type.
2462   //
2463   // Note that we do not check for ambiguity or inaccessibility
2464   // here. That is handled by CheckPointerConversion.
2465   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2466       ToPointeeType->isRecordType() &&
2467       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2468       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2469     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2470                                                        ToPointeeType,
2471                                                        ToType, Context);
2472     return true;
2473   }
2474 
2475   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2476       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2477     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478                                                        ToPointeeType,
2479                                                        ToType, Context);
2480     return true;
2481   }
2482 
2483   return false;
2484 }
2485 
2486 /// Adopt the given qualifiers for the given type.
2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2488   Qualifiers TQs = T.getQualifiers();
2489 
2490   // Check whether qualifiers already match.
2491   if (TQs == Qs)
2492     return T;
2493 
2494   if (Qs.compatiblyIncludes(TQs))
2495     return Context.getQualifiedType(T, Qs);
2496 
2497   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2498 }
2499 
2500 /// isObjCPointerConversion - Determines whether this is an
2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2502 /// with the same arguments and return values.
2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2504                                    QualType& ConvertedType,
2505                                    bool &IncompatibleObjC) {
2506   if (!getLangOpts().ObjC)
2507     return false;
2508 
2509   // The set of qualifiers on the type we're converting from.
2510   Qualifiers FromQualifiers = FromType.getQualifiers();
2511 
2512   // First, we handle all conversions on ObjC object pointer types.
2513   const ObjCObjectPointerType* ToObjCPtr =
2514     ToType->getAs<ObjCObjectPointerType>();
2515   const ObjCObjectPointerType *FromObjCPtr =
2516     FromType->getAs<ObjCObjectPointerType>();
2517 
2518   if (ToObjCPtr && FromObjCPtr) {
2519     // If the pointee types are the same (ignoring qualifications),
2520     // then this is not a pointer conversion.
2521     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2522                                        FromObjCPtr->getPointeeType()))
2523       return false;
2524 
2525     // Conversion between Objective-C pointers.
2526     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2527       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2528       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2529       if (getLangOpts().CPlusPlus && LHS && RHS &&
2530           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2531                                                 FromObjCPtr->getPointeeType()))
2532         return false;
2533       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2534                                                    ToObjCPtr->getPointeeType(),
2535                                                          ToType, Context);
2536       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2537       return true;
2538     }
2539 
2540     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2541       // Okay: this is some kind of implicit downcast of Objective-C
2542       // interfaces, which is permitted. However, we're going to
2543       // complain about it.
2544       IncompatibleObjC = true;
2545       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2546                                                    ToObjCPtr->getPointeeType(),
2547                                                          ToType, Context);
2548       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2549       return true;
2550     }
2551   }
2552   // Beyond this point, both types need to be C pointers or block pointers.
2553   QualType ToPointeeType;
2554   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2555     ToPointeeType = ToCPtr->getPointeeType();
2556   else if (const BlockPointerType *ToBlockPtr =
2557             ToType->getAs<BlockPointerType>()) {
2558     // Objective C++: We're able to convert from a pointer to any object
2559     // to a block pointer type.
2560     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2561       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562       return true;
2563     }
2564     ToPointeeType = ToBlockPtr->getPointeeType();
2565   }
2566   else if (FromType->getAs<BlockPointerType>() &&
2567            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2568     // Objective C++: We're able to convert from a block pointer type to a
2569     // pointer to any object.
2570     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2571     return true;
2572   }
2573   else
2574     return false;
2575 
2576   QualType FromPointeeType;
2577   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2578     FromPointeeType = FromCPtr->getPointeeType();
2579   else if (const BlockPointerType *FromBlockPtr =
2580            FromType->getAs<BlockPointerType>())
2581     FromPointeeType = FromBlockPtr->getPointeeType();
2582   else
2583     return false;
2584 
2585   // If we have pointers to pointers, recursively check whether this
2586   // is an Objective-C conversion.
2587   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2588       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2589                               IncompatibleObjC)) {
2590     // We always complain about this conversion.
2591     IncompatibleObjC = true;
2592     ConvertedType = Context.getPointerType(ConvertedType);
2593     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2594     return true;
2595   }
2596   // Allow conversion of pointee being objective-c pointer to another one;
2597   // as in I* to id.
2598   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2599       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2600       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2601                               IncompatibleObjC)) {
2602 
2603     ConvertedType = Context.getPointerType(ConvertedType);
2604     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2605     return true;
2606   }
2607 
2608   // If we have pointers to functions or blocks, check whether the only
2609   // differences in the argument and result types are in Objective-C
2610   // pointer conversions. If so, we permit the conversion (but
2611   // complain about it).
2612   const FunctionProtoType *FromFunctionType
2613     = FromPointeeType->getAs<FunctionProtoType>();
2614   const FunctionProtoType *ToFunctionType
2615     = ToPointeeType->getAs<FunctionProtoType>();
2616   if (FromFunctionType && ToFunctionType) {
2617     // If the function types are exactly the same, this isn't an
2618     // Objective-C pointer conversion.
2619     if (Context.getCanonicalType(FromPointeeType)
2620           == Context.getCanonicalType(ToPointeeType))
2621       return false;
2622 
2623     // Perform the quick checks that will tell us whether these
2624     // function types are obviously different.
2625     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2626         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2627         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2628       return false;
2629 
2630     bool HasObjCConversion = false;
2631     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2632         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2633       // Okay, the types match exactly. Nothing to do.
2634     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2635                                        ToFunctionType->getReturnType(),
2636                                        ConvertedType, IncompatibleObjC)) {
2637       // Okay, we have an Objective-C pointer conversion.
2638       HasObjCConversion = true;
2639     } else {
2640       // Function types are too different. Abort.
2641       return false;
2642     }
2643 
2644     // Check argument types.
2645     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2646          ArgIdx != NumArgs; ++ArgIdx) {
2647       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2648       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2649       if (Context.getCanonicalType(FromArgType)
2650             == Context.getCanonicalType(ToArgType)) {
2651         // Okay, the types match exactly. Nothing to do.
2652       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2653                                          ConvertedType, IncompatibleObjC)) {
2654         // Okay, we have an Objective-C pointer conversion.
2655         HasObjCConversion = true;
2656       } else {
2657         // Argument types are too different. Abort.
2658         return false;
2659       }
2660     }
2661 
2662     if (HasObjCConversion) {
2663       // We had an Objective-C conversion. Allow this pointer
2664       // conversion, but complain about it.
2665       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2666       IncompatibleObjC = true;
2667       return true;
2668     }
2669   }
2670 
2671   return false;
2672 }
2673 
2674 /// Determine whether this is an Objective-C writeback conversion,
2675 /// used for parameter passing when performing automatic reference counting.
2676 ///
2677 /// \param FromType The type we're converting form.
2678 ///
2679 /// \param ToType The type we're converting to.
2680 ///
2681 /// \param ConvertedType The type that will be produced after applying
2682 /// this conversion.
2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2684                                      QualType &ConvertedType) {
2685   if (!getLangOpts().ObjCAutoRefCount ||
2686       Context.hasSameUnqualifiedType(FromType, ToType))
2687     return false;
2688 
2689   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2690   QualType ToPointee;
2691   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2692     ToPointee = ToPointer->getPointeeType();
2693   else
2694     return false;
2695 
2696   Qualifiers ToQuals = ToPointee.getQualifiers();
2697   if (!ToPointee->isObjCLifetimeType() ||
2698       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2699       !ToQuals.withoutObjCLifetime().empty())
2700     return false;
2701 
2702   // Argument must be a pointer to __strong to __weak.
2703   QualType FromPointee;
2704   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2705     FromPointee = FromPointer->getPointeeType();
2706   else
2707     return false;
2708 
2709   Qualifiers FromQuals = FromPointee.getQualifiers();
2710   if (!FromPointee->isObjCLifetimeType() ||
2711       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2712        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2713     return false;
2714 
2715   // Make sure that we have compatible qualifiers.
2716   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2717   if (!ToQuals.compatiblyIncludes(FromQuals))
2718     return false;
2719 
2720   // Remove qualifiers from the pointee type we're converting from; they
2721   // aren't used in the compatibility check belong, and we'll be adding back
2722   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2723   FromPointee = FromPointee.getUnqualifiedType();
2724 
2725   // The unqualified form of the pointee types must be compatible.
2726   ToPointee = ToPointee.getUnqualifiedType();
2727   bool IncompatibleObjC;
2728   if (Context.typesAreCompatible(FromPointee, ToPointee))
2729     FromPointee = ToPointee;
2730   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2731                                     IncompatibleObjC))
2732     return false;
2733 
2734   /// Construct the type we're converting to, which is a pointer to
2735   /// __autoreleasing pointee.
2736   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2737   ConvertedType = Context.getPointerType(FromPointee);
2738   return true;
2739 }
2740 
2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2742                                     QualType& ConvertedType) {
2743   QualType ToPointeeType;
2744   if (const BlockPointerType *ToBlockPtr =
2745         ToType->getAs<BlockPointerType>())
2746     ToPointeeType = ToBlockPtr->getPointeeType();
2747   else
2748     return false;
2749 
2750   QualType FromPointeeType;
2751   if (const BlockPointerType *FromBlockPtr =
2752       FromType->getAs<BlockPointerType>())
2753     FromPointeeType = FromBlockPtr->getPointeeType();
2754   else
2755     return false;
2756   // We have pointer to blocks, check whether the only
2757   // differences in the argument and result types are in Objective-C
2758   // pointer conversions. If so, we permit the conversion.
2759 
2760   const FunctionProtoType *FromFunctionType
2761     = FromPointeeType->getAs<FunctionProtoType>();
2762   const FunctionProtoType *ToFunctionType
2763     = ToPointeeType->getAs<FunctionProtoType>();
2764 
2765   if (!FromFunctionType || !ToFunctionType)
2766     return false;
2767 
2768   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2769     return true;
2770 
2771   // Perform the quick checks that will tell us whether these
2772   // function types are obviously different.
2773   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2774       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2775     return false;
2776 
2777   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2778   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2779   if (FromEInfo != ToEInfo)
2780     return false;
2781 
2782   bool IncompatibleObjC = false;
2783   if (Context.hasSameType(FromFunctionType->getReturnType(),
2784                           ToFunctionType->getReturnType())) {
2785     // Okay, the types match exactly. Nothing to do.
2786   } else {
2787     QualType RHS = FromFunctionType->getReturnType();
2788     QualType LHS = ToFunctionType->getReturnType();
2789     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2790         !RHS.hasQualifiers() && LHS.hasQualifiers())
2791        LHS = LHS.getUnqualifiedType();
2792 
2793      if (Context.hasSameType(RHS,LHS)) {
2794        // OK exact match.
2795      } else if (isObjCPointerConversion(RHS, LHS,
2796                                         ConvertedType, IncompatibleObjC)) {
2797      if (IncompatibleObjC)
2798        return false;
2799      // Okay, we have an Objective-C pointer conversion.
2800      }
2801      else
2802        return false;
2803    }
2804 
2805    // Check argument types.
2806    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2807         ArgIdx != NumArgs; ++ArgIdx) {
2808      IncompatibleObjC = false;
2809      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2810      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2811      if (Context.hasSameType(FromArgType, ToArgType)) {
2812        // Okay, the types match exactly. Nothing to do.
2813      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2814                                         ConvertedType, IncompatibleObjC)) {
2815        if (IncompatibleObjC)
2816          return false;
2817        // Okay, we have an Objective-C pointer conversion.
2818      } else
2819        // Argument types are too different. Abort.
2820        return false;
2821    }
2822 
2823    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2824    bool CanUseToFPT, CanUseFromFPT;
2825    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2826                                       CanUseToFPT, CanUseFromFPT,
2827                                       NewParamInfos))
2828      return false;
2829 
2830    ConvertedType = ToType;
2831    return true;
2832 }
2833 
2834 enum {
2835   ft_default,
2836   ft_different_class,
2837   ft_parameter_arity,
2838   ft_parameter_mismatch,
2839   ft_return_type,
2840   ft_qualifer_mismatch,
2841   ft_noexcept
2842 };
2843 
2844 /// Attempts to get the FunctionProtoType from a Type. Handles
2845 /// MemberFunctionPointers properly.
2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2847   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2848     return FPT;
2849 
2850   if (auto *MPT = FromType->getAs<MemberPointerType>())
2851     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2852 
2853   return nullptr;
2854 }
2855 
2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2857 /// function types.  Catches different number of parameter, mismatch in
2858 /// parameter types, and different return types.
2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2860                                       QualType FromType, QualType ToType) {
2861   // If either type is not valid, include no extra info.
2862   if (FromType.isNull() || ToType.isNull()) {
2863     PDiag << ft_default;
2864     return;
2865   }
2866 
2867   // Get the function type from the pointers.
2868   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2869     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2870                *ToMember = ToType->castAs<MemberPointerType>();
2871     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2872       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2873             << QualType(FromMember->getClass(), 0);
2874       return;
2875     }
2876     FromType = FromMember->getPointeeType();
2877     ToType = ToMember->getPointeeType();
2878   }
2879 
2880   if (FromType->isPointerType())
2881     FromType = FromType->getPointeeType();
2882   if (ToType->isPointerType())
2883     ToType = ToType->getPointeeType();
2884 
2885   // Remove references.
2886   FromType = FromType.getNonReferenceType();
2887   ToType = ToType.getNonReferenceType();
2888 
2889   // Don't print extra info for non-specialized template functions.
2890   if (FromType->isInstantiationDependentType() &&
2891       !FromType->getAs<TemplateSpecializationType>()) {
2892     PDiag << ft_default;
2893     return;
2894   }
2895 
2896   // No extra info for same types.
2897   if (Context.hasSameType(FromType, ToType)) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2903                           *ToFunction = tryGetFunctionProtoType(ToType);
2904 
2905   // Both types need to be function types.
2906   if (!FromFunction || !ToFunction) {
2907     PDiag << ft_default;
2908     return;
2909   }
2910 
2911   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2912     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2913           << FromFunction->getNumParams();
2914     return;
2915   }
2916 
2917   // Handle different parameter types.
2918   unsigned ArgPos;
2919   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2920     PDiag << ft_parameter_mismatch << ArgPos + 1
2921           << ToFunction->getParamType(ArgPos)
2922           << FromFunction->getParamType(ArgPos);
2923     return;
2924   }
2925 
2926   // Handle different return type.
2927   if (!Context.hasSameType(FromFunction->getReturnType(),
2928                            ToFunction->getReturnType())) {
2929     PDiag << ft_return_type << ToFunction->getReturnType()
2930           << FromFunction->getReturnType();
2931     return;
2932   }
2933 
2934   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2935     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2936           << FromFunction->getMethodQuals();
2937     return;
2938   }
2939 
2940   // Handle exception specification differences on canonical type (in C++17
2941   // onwards).
2942   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2943           ->isNothrow() !=
2944       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow()) {
2946     PDiag << ft_noexcept;
2947     return;
2948   }
2949 
2950   // Unable to find a difference, so add no extra info.
2951   PDiag << ft_default;
2952 }
2953 
2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2955 /// for equality of their argument types. Caller has already checked that
2956 /// they have same number of arguments.  If the parameters are different,
2957 /// ArgPos will have the parameter index of the first different parameter.
2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2959                                       const FunctionProtoType *NewType,
2960                                       unsigned *ArgPos) {
2961   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2962                                               N = NewType->param_type_begin(),
2963                                               E = OldType->param_type_end();
2964        O && (O != E); ++O, ++N) {
2965     // Ignore address spaces in pointee type. This is to disallow overloading
2966     // on __ptr32/__ptr64 address spaces.
2967     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2968     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2969 
2970     if (!Context.hasSameType(Old, New)) {
2971       if (ArgPos)
2972         *ArgPos = O - OldType->param_type_begin();
2973       return false;
2974     }
2975   }
2976   return true;
2977 }
2978 
2979 /// CheckPointerConversion - Check the pointer conversion from the
2980 /// expression From to the type ToType. This routine checks for
2981 /// ambiguous or inaccessible derived-to-base pointer
2982 /// conversions for which IsPointerConversion has already returned
2983 /// true. It returns true and produces a diagnostic if there was an
2984 /// error, or returns false otherwise.
2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2986                                   CastKind &Kind,
2987                                   CXXCastPath& BasePath,
2988                                   bool IgnoreBaseAccess,
2989                                   bool Diagnose) {
2990   QualType FromType = From->getType();
2991   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2992 
2993   Kind = CK_BitCast;
2994 
2995   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2996       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2997           Expr::NPCK_ZeroExpression) {
2998     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2999       DiagRuntimeBehavior(From->getExprLoc(), From,
3000                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3001                             << ToType << From->getSourceRange());
3002     else if (!isUnevaluatedContext())
3003       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3004         << ToType << From->getSourceRange();
3005   }
3006   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3007     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3008       QualType FromPointeeType = FromPtrType->getPointeeType(),
3009                ToPointeeType   = ToPtrType->getPointeeType();
3010 
3011       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3012           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3013         // We must have a derived-to-base conversion. Check an
3014         // ambiguous or inaccessible conversion.
3015         unsigned InaccessibleID = 0;
3016         unsigned AmbiguousID = 0;
3017         if (Diagnose) {
3018           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3019           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3020         }
3021         if (CheckDerivedToBaseConversion(
3022                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3023                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3024                 &BasePath, IgnoreBaseAccess))
3025           return true;
3026 
3027         // The conversion was successful.
3028         Kind = CK_DerivedToBase;
3029       }
3030 
3031       if (Diagnose && !IsCStyleOrFunctionalCast &&
3032           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3033         assert(getLangOpts().MSVCCompat &&
3034                "this should only be possible with MSVCCompat!");
3035         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3036             << From->getSourceRange();
3037       }
3038     }
3039   } else if (const ObjCObjectPointerType *ToPtrType =
3040                ToType->getAs<ObjCObjectPointerType>()) {
3041     if (const ObjCObjectPointerType *FromPtrType =
3042           FromType->getAs<ObjCObjectPointerType>()) {
3043       // Objective-C++ conversions are always okay.
3044       // FIXME: We should have a different class of conversions for the
3045       // Objective-C++ implicit conversions.
3046       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3047         return false;
3048     } else if (FromType->isBlockPointerType()) {
3049       Kind = CK_BlockPointerToObjCPointerCast;
3050     } else {
3051       Kind = CK_CPointerToObjCPointerCast;
3052     }
3053   } else if (ToType->isBlockPointerType()) {
3054     if (!FromType->isBlockPointerType())
3055       Kind = CK_AnyPointerToBlockPointerCast;
3056   }
3057 
3058   // We shouldn't fall into this case unless it's valid for other
3059   // reasons.
3060   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3061     Kind = CK_NullToPointer;
3062 
3063   return false;
3064 }
3065 
3066 /// IsMemberPointerConversion - Determines whether the conversion of the
3067 /// expression From, which has the (possibly adjusted) type FromType, can be
3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3069 /// If so, returns true and places the converted type (that might differ from
3070 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3072                                      QualType ToType,
3073                                      bool InOverloadResolution,
3074                                      QualType &ConvertedType) {
3075   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3076   if (!ToTypePtr)
3077     return false;
3078 
3079   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3080   if (From->isNullPointerConstant(Context,
3081                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082                                         : Expr::NPC_ValueDependentIsNull)) {
3083     ConvertedType = ToType;
3084     return true;
3085   }
3086 
3087   // Otherwise, both types have to be member pointers.
3088   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3089   if (!FromTypePtr)
3090     return false;
3091 
3092   // A pointer to member of B can be converted to a pointer to member of D,
3093   // where D is derived from B (C++ 4.11p2).
3094   QualType FromClass(FromTypePtr->getClass(), 0);
3095   QualType ToClass(ToTypePtr->getClass(), 0);
3096 
3097   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3098       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3099     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3100                                                  ToClass.getTypePtr());
3101     return true;
3102   }
3103 
3104   return false;
3105 }
3106 
3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3108 /// expression From to the type ToType. This routine checks for ambiguous or
3109 /// virtual or inaccessible base-to-derived member pointer conversions
3110 /// for which IsMemberPointerConversion has already returned true. It returns
3111 /// true and produces a diagnostic if there was an error, or returns false
3112 /// otherwise.
3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3114                                         CastKind &Kind,
3115                                         CXXCastPath &BasePath,
3116                                         bool IgnoreBaseAccess) {
3117   QualType FromType = From->getType();
3118   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3119   if (!FromPtrType) {
3120     // This must be a null pointer to member pointer conversion
3121     assert(From->isNullPointerConstant(Context,
3122                                        Expr::NPC_ValueDependentIsNull) &&
3123            "Expr must be null pointer constant!");
3124     Kind = CK_NullToMemberPointer;
3125     return false;
3126   }
3127 
3128   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3129   assert(ToPtrType && "No member pointer cast has a target type "
3130                       "that is not a member pointer.");
3131 
3132   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3133   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3134 
3135   // FIXME: What about dependent types?
3136   assert(FromClass->isRecordType() && "Pointer into non-class.");
3137   assert(ToClass->isRecordType() && "Pointer into non-class.");
3138 
3139   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140                      /*DetectVirtual=*/true);
3141   bool DerivationOkay =
3142       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3143   assert(DerivationOkay &&
3144          "Should not have been called if derivation isn't OK.");
3145   (void)DerivationOkay;
3146 
3147   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3148                                   getUnqualifiedType())) {
3149     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3150     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3151       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3152     return true;
3153   }
3154 
3155   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3156     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3157       << FromClass << ToClass << QualType(VBase, 0)
3158       << From->getSourceRange();
3159     return true;
3160   }
3161 
3162   if (!IgnoreBaseAccess)
3163     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3164                          Paths.front(),
3165                          diag::err_downcast_from_inaccessible_base);
3166 
3167   // Must be a base to derived member conversion.
3168   BuildBasePathArray(Paths, BasePath);
3169   Kind = CK_BaseToDerivedMemberPointer;
3170   return false;
3171 }
3172 
3173 /// Determine whether the lifetime conversion between the two given
3174 /// qualifiers sets is nontrivial.
3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3176                                                Qualifiers ToQuals) {
3177   // Converting anything to const __unsafe_unretained is trivial.
3178   if (ToQuals.hasConst() &&
3179       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3180     return false;
3181 
3182   return true;
3183 }
3184 
3185 /// Perform a single iteration of the loop for checking if a qualification
3186 /// conversion is valid.
3187 ///
3188 /// Specifically, check whether any change between the qualifiers of \p
3189 /// FromType and \p ToType is permissible, given knowledge about whether every
3190 /// outer layer is const-qualified.
3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3192                                           bool CStyle, bool IsTopLevel,
3193                                           bool &PreviousToQualsIncludeConst,
3194                                           bool &ObjCLifetimeConversion) {
3195   Qualifiers FromQuals = FromType.getQualifiers();
3196   Qualifiers ToQuals = ToType.getQualifiers();
3197 
3198   // Ignore __unaligned qualifier if this type is void.
3199   if (ToType.getUnqualifiedType()->isVoidType())
3200     FromQuals.removeUnaligned();
3201 
3202   // Objective-C ARC:
3203   //   Check Objective-C lifetime conversions.
3204   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3205     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3206       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3207         ObjCLifetimeConversion = true;
3208       FromQuals.removeObjCLifetime();
3209       ToQuals.removeObjCLifetime();
3210     } else {
3211       // Qualification conversions cannot cast between different
3212       // Objective-C lifetime qualifiers.
3213       return false;
3214     }
3215   }
3216 
3217   // Allow addition/removal of GC attributes but not changing GC attributes.
3218   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3219       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3220     FromQuals.removeObjCGCAttr();
3221     ToQuals.removeObjCGCAttr();
3222   }
3223 
3224   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3225   //      2,j, and similarly for volatile.
3226   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3227     return false;
3228 
3229   // If address spaces mismatch:
3230   //  - in top level it is only valid to convert to addr space that is a
3231   //    superset in all cases apart from C-style casts where we allow
3232   //    conversions between overlapping address spaces.
3233   //  - in non-top levels it is not a valid conversion.
3234   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3235       (!IsTopLevel ||
3236        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3237          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3238     return false;
3239 
3240   //   -- if the cv 1,j and cv 2,j are different, then const is in
3241   //      every cv for 0 < k < j.
3242   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3243       !PreviousToQualsIncludeConst)
3244     return false;
3245 
3246   // Keep track of whether all prior cv-qualifiers in the "to" type
3247   // include const.
3248   PreviousToQualsIncludeConst =
3249       PreviousToQualsIncludeConst && ToQuals.hasConst();
3250   return true;
3251 }
3252 
3253 /// IsQualificationConversion - Determines whether the conversion from
3254 /// an rvalue of type FromType to ToType is a qualification conversion
3255 /// (C++ 4.4).
3256 ///
3257 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3258 /// when the qualification conversion involves a change in the Objective-C
3259 /// object lifetime.
3260 bool
3261 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3262                                 bool CStyle, bool &ObjCLifetimeConversion) {
3263   FromType = Context.getCanonicalType(FromType);
3264   ToType = Context.getCanonicalType(ToType);
3265   ObjCLifetimeConversion = false;
3266 
3267   // If FromType and ToType are the same type, this is not a
3268   // qualification conversion.
3269   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3270     return false;
3271 
3272   // (C++ 4.4p4):
3273   //   A conversion can add cv-qualifiers at levels other than the first
3274   //   in multi-level pointers, subject to the following rules: [...]
3275   bool PreviousToQualsIncludeConst = true;
3276   bool UnwrappedAnyPointer = false;
3277   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3278     if (!isQualificationConversionStep(
3279             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3280             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3281       return false;
3282     UnwrappedAnyPointer = true;
3283   }
3284 
3285   // We are left with FromType and ToType being the pointee types
3286   // after unwrapping the original FromType and ToType the same number
3287   // of times. If we unwrapped any pointers, and if FromType and
3288   // ToType have the same unqualified type (since we checked
3289   // qualifiers above), then this is a qualification conversion.
3290   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3291 }
3292 
3293 /// - Determine whether this is a conversion from a scalar type to an
3294 /// atomic type.
3295 ///
3296 /// If successful, updates \c SCS's second and third steps in the conversion
3297 /// sequence to finish the conversion.
3298 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3299                                 bool InOverloadResolution,
3300                                 StandardConversionSequence &SCS,
3301                                 bool CStyle) {
3302   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3303   if (!ToAtomic)
3304     return false;
3305 
3306   StandardConversionSequence InnerSCS;
3307   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3308                             InOverloadResolution, InnerSCS,
3309                             CStyle, /*AllowObjCWritebackConversion=*/false))
3310     return false;
3311 
3312   SCS.Second = InnerSCS.Second;
3313   SCS.setToType(1, InnerSCS.getToType(1));
3314   SCS.Third = InnerSCS.Third;
3315   SCS.QualificationIncludesObjCLifetime
3316     = InnerSCS.QualificationIncludesObjCLifetime;
3317   SCS.setToType(2, InnerSCS.getToType(2));
3318   return true;
3319 }
3320 
3321 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3322                                               CXXConstructorDecl *Constructor,
3323                                               QualType Type) {
3324   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3325   if (CtorType->getNumParams() > 0) {
3326     QualType FirstArg = CtorType->getParamType(0);
3327     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3328       return true;
3329   }
3330   return false;
3331 }
3332 
3333 static OverloadingResult
3334 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3335                                        CXXRecordDecl *To,
3336                                        UserDefinedConversionSequence &User,
3337                                        OverloadCandidateSet &CandidateSet,
3338                                        bool AllowExplicit) {
3339   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340   for (auto *D : S.LookupConstructors(To)) {
3341     auto Info = getConstructorInfo(D);
3342     if (!Info)
3343       continue;
3344 
3345     bool Usable = !Info.Constructor->isInvalidDecl() &&
3346                   S.isInitListConstructor(Info.Constructor);
3347     if (Usable) {
3348       // If the first argument is (a reference to) the target type,
3349       // suppress conversions.
3350       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3351           S.Context, Info.Constructor, ToType);
3352       if (Info.ConstructorTmpl)
3353         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3354                                        /*ExplicitArgs*/ nullptr, From,
3355                                        CandidateSet, SuppressUserConversions,
3356                                        /*PartialOverloading*/ false,
3357                                        AllowExplicit);
3358       else
3359         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3360                                CandidateSet, SuppressUserConversions,
3361                                /*PartialOverloading*/ false, AllowExplicit);
3362     }
3363   }
3364 
3365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3366 
3367   OverloadCandidateSet::iterator Best;
3368   switch (auto Result =
3369               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3370   case OR_Deleted:
3371   case OR_Success: {
3372     // Record the standard conversion we used and the conversion function.
3373     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3374     QualType ThisType = Constructor->getThisType();
3375     // Initializer lists don't have conversions as such.
3376     User.Before.setAsIdentityConversion();
3377     User.HadMultipleCandidates = HadMultipleCandidates;
3378     User.ConversionFunction = Constructor;
3379     User.FoundConversionFunction = Best->FoundDecl;
3380     User.After.setAsIdentityConversion();
3381     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3382     User.After.setAllToTypes(ToType);
3383     return Result;
3384   }
3385 
3386   case OR_No_Viable_Function:
3387     return OR_No_Viable_Function;
3388   case OR_Ambiguous:
3389     return OR_Ambiguous;
3390   }
3391 
3392   llvm_unreachable("Invalid OverloadResult!");
3393 }
3394 
3395 /// Determines whether there is a user-defined conversion sequence
3396 /// (C++ [over.ics.user]) that converts expression From to the type
3397 /// ToType. If such a conversion exists, User will contain the
3398 /// user-defined conversion sequence that performs such a conversion
3399 /// and this routine will return true. Otherwise, this routine returns
3400 /// false and User is unspecified.
3401 ///
3402 /// \param AllowExplicit  true if the conversion should consider C++0x
3403 /// "explicit" conversion functions as well as non-explicit conversion
3404 /// functions (C++0x [class.conv.fct]p2).
3405 ///
3406 /// \param AllowObjCConversionOnExplicit true if the conversion should
3407 /// allow an extra Objective-C pointer conversion on uses of explicit
3408 /// constructors. Requires \c AllowExplicit to also be set.
3409 static OverloadingResult
3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3411                         UserDefinedConversionSequence &User,
3412                         OverloadCandidateSet &CandidateSet,
3413                         AllowedExplicit AllowExplicit,
3414                         bool AllowObjCConversionOnExplicit) {
3415   assert(AllowExplicit != AllowedExplicit::None ||
3416          !AllowObjCConversionOnExplicit);
3417   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3418 
3419   // Whether we will only visit constructors.
3420   bool ConstructorsOnly = false;
3421 
3422   // If the type we are conversion to is a class type, enumerate its
3423   // constructors.
3424   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3425     // C++ [over.match.ctor]p1:
3426     //   When objects of class type are direct-initialized (8.5), or
3427     //   copy-initialized from an expression of the same or a
3428     //   derived class type (8.5), overload resolution selects the
3429     //   constructor. [...] For copy-initialization, the candidate
3430     //   functions are all the converting constructors (12.3.1) of
3431     //   that class. The argument list is the expression-list within
3432     //   the parentheses of the initializer.
3433     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3434         (From->getType()->getAs<RecordType>() &&
3435          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3436       ConstructorsOnly = true;
3437 
3438     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3439       // We're not going to find any constructors.
3440     } else if (CXXRecordDecl *ToRecordDecl
3441                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3442 
3443       Expr **Args = &From;
3444       unsigned NumArgs = 1;
3445       bool ListInitializing = false;
3446       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3447         // But first, see if there is an init-list-constructor that will work.
3448         OverloadingResult Result = IsInitializerListConstructorConversion(
3449             S, From, ToType, ToRecordDecl, User, CandidateSet,
3450             AllowExplicit == AllowedExplicit::All);
3451         if (Result != OR_No_Viable_Function)
3452           return Result;
3453         // Never mind.
3454         CandidateSet.clear(
3455             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3456 
3457         // If we're list-initializing, we pass the individual elements as
3458         // arguments, not the entire list.
3459         Args = InitList->getInits();
3460         NumArgs = InitList->getNumInits();
3461         ListInitializing = true;
3462       }
3463 
3464       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3465         auto Info = getConstructorInfo(D);
3466         if (!Info)
3467           continue;
3468 
3469         bool Usable = !Info.Constructor->isInvalidDecl();
3470         if (!ListInitializing)
3471           Usable = Usable && Info.Constructor->isConvertingConstructor(
3472                                  /*AllowExplicit*/ true);
3473         if (Usable) {
3474           bool SuppressUserConversions = !ConstructorsOnly;
3475           if (SuppressUserConversions && ListInitializing) {
3476             SuppressUserConversions = false;
3477             if (NumArgs == 1) {
3478               // If the first argument is (a reference to) the target type,
3479               // suppress conversions.
3480               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3481                   S.Context, Info.Constructor, ToType);
3482             }
3483           }
3484           if (Info.ConstructorTmpl)
3485             S.AddTemplateOverloadCandidate(
3486                 Info.ConstructorTmpl, Info.FoundDecl,
3487                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3488                 CandidateSet, SuppressUserConversions,
3489                 /*PartialOverloading*/ false,
3490                 AllowExplicit == AllowedExplicit::All);
3491           else
3492             // Allow one user-defined conversion when user specifies a
3493             // From->ToType conversion via an static cast (c-style, etc).
3494             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3495                                    llvm::makeArrayRef(Args, NumArgs),
3496                                    CandidateSet, SuppressUserConversions,
3497                                    /*PartialOverloading*/ false,
3498                                    AllowExplicit == AllowedExplicit::All);
3499         }
3500       }
3501     }
3502   }
3503 
3504   // Enumerate conversion functions, if we're allowed to.
3505   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3506   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3507     // No conversion functions from incomplete types.
3508   } else if (const RecordType *FromRecordType =
3509                  From->getType()->getAs<RecordType>()) {
3510     if (CXXRecordDecl *FromRecordDecl
3511          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3512       // Add all of the conversion functions as candidates.
3513       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3514       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3515         DeclAccessPair FoundDecl = I.getPair();
3516         NamedDecl *D = FoundDecl.getDecl();
3517         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3518         if (isa<UsingShadowDecl>(D))
3519           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3520 
3521         CXXConversionDecl *Conv;
3522         FunctionTemplateDecl *ConvTemplate;
3523         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3524           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3525         else
3526           Conv = cast<CXXConversionDecl>(D);
3527 
3528         if (ConvTemplate)
3529           S.AddTemplateConversionCandidate(
3530               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3531               CandidateSet, AllowObjCConversionOnExplicit,
3532               AllowExplicit != AllowedExplicit::None);
3533         else
3534           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3535                                    CandidateSet, AllowObjCConversionOnExplicit,
3536                                    AllowExplicit != AllowedExplicit::None);
3537       }
3538     }
3539   }
3540 
3541   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3542 
3543   OverloadCandidateSet::iterator Best;
3544   switch (auto Result =
3545               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3546   case OR_Success:
3547   case OR_Deleted:
3548     // Record the standard conversion we used and the conversion function.
3549     if (CXXConstructorDecl *Constructor
3550           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3551       // C++ [over.ics.user]p1:
3552       //   If the user-defined conversion is specified by a
3553       //   constructor (12.3.1), the initial standard conversion
3554       //   sequence converts the source type to the type required by
3555       //   the argument of the constructor.
3556       //
3557       QualType ThisType = Constructor->getThisType();
3558       if (isa<InitListExpr>(From)) {
3559         // Initializer lists don't have conversions as such.
3560         User.Before.setAsIdentityConversion();
3561       } else {
3562         if (Best->Conversions[0].isEllipsis())
3563           User.EllipsisConversion = true;
3564         else {
3565           User.Before = Best->Conversions[0].Standard;
3566           User.EllipsisConversion = false;
3567         }
3568       }
3569       User.HadMultipleCandidates = HadMultipleCandidates;
3570       User.ConversionFunction = Constructor;
3571       User.FoundConversionFunction = Best->FoundDecl;
3572       User.After.setAsIdentityConversion();
3573       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3574       User.After.setAllToTypes(ToType);
3575       return Result;
3576     }
3577     if (CXXConversionDecl *Conversion
3578                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3579       // C++ [over.ics.user]p1:
3580       //
3581       //   [...] If the user-defined conversion is specified by a
3582       //   conversion function (12.3.2), the initial standard
3583       //   conversion sequence converts the source type to the
3584       //   implicit object parameter of the conversion function.
3585       User.Before = Best->Conversions[0].Standard;
3586       User.HadMultipleCandidates = HadMultipleCandidates;
3587       User.ConversionFunction = Conversion;
3588       User.FoundConversionFunction = Best->FoundDecl;
3589       User.EllipsisConversion = false;
3590 
3591       // C++ [over.ics.user]p2:
3592       //   The second standard conversion sequence converts the
3593       //   result of the user-defined conversion to the target type
3594       //   for the sequence. Since an implicit conversion sequence
3595       //   is an initialization, the special rules for
3596       //   initialization by user-defined conversion apply when
3597       //   selecting the best user-defined conversion for a
3598       //   user-defined conversion sequence (see 13.3.3 and
3599       //   13.3.3.1).
3600       User.After = Best->FinalConversion;
3601       return Result;
3602     }
3603     llvm_unreachable("Not a constructor or conversion function?");
3604 
3605   case OR_No_Viable_Function:
3606     return OR_No_Viable_Function;
3607 
3608   case OR_Ambiguous:
3609     return OR_Ambiguous;
3610   }
3611 
3612   llvm_unreachable("Invalid OverloadResult!");
3613 }
3614 
3615 bool
3616 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3617   ImplicitConversionSequence ICS;
3618   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3619                                     OverloadCandidateSet::CSK_Normal);
3620   OverloadingResult OvResult =
3621     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3622                             CandidateSet, AllowedExplicit::None, false);
3623 
3624   if (!(OvResult == OR_Ambiguous ||
3625         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3626     return false;
3627 
3628   auto Cands = CandidateSet.CompleteCandidates(
3629       *this,
3630       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3631       From);
3632   if (OvResult == OR_Ambiguous)
3633     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3634         << From->getType() << ToType << From->getSourceRange();
3635   else { // OR_No_Viable_Function && !CandidateSet.empty()
3636     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3637                              diag::err_typecheck_nonviable_condition_incomplete,
3638                              From->getType(), From->getSourceRange()))
3639       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3640           << false << From->getType() << From->getSourceRange() << ToType;
3641   }
3642 
3643   CandidateSet.NoteCandidates(
3644                               *this, From, Cands);
3645   return true;
3646 }
3647 
3648 /// Compare the user-defined conversion functions or constructors
3649 /// of two user-defined conversion sequences to determine whether any ordering
3650 /// is possible.
3651 static ImplicitConversionSequence::CompareKind
3652 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3653                            FunctionDecl *Function2) {
3654   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   // Objective-C++:
3658   //   If both conversion functions are implicitly-declared conversions from
3659   //   a lambda closure type to a function pointer and a block pointer,
3660   //   respectively, always prefer the conversion to a function pointer,
3661   //   because the function pointer is more lightweight and is more likely
3662   //   to keep code working.
3663   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3664   if (!Conv1)
3665     return ImplicitConversionSequence::Indistinguishable;
3666 
3667   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3668   if (!Conv2)
3669     return ImplicitConversionSequence::Indistinguishable;
3670 
3671   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3672     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3673     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3674     if (Block1 != Block2)
3675       return Block1 ? ImplicitConversionSequence::Worse
3676                     : ImplicitConversionSequence::Better;
3677   }
3678 
3679   return ImplicitConversionSequence::Indistinguishable;
3680 }
3681 
3682 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3683     const ImplicitConversionSequence &ICS) {
3684   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3685          (ICS.isUserDefined() &&
3686           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3687 }
3688 
3689 /// CompareImplicitConversionSequences - Compare two implicit
3690 /// conversion sequences to determine whether one is better than the
3691 /// other or if they are indistinguishable (C++ 13.3.3.2).
3692 static ImplicitConversionSequence::CompareKind
3693 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3694                                    const ImplicitConversionSequence& ICS1,
3695                                    const ImplicitConversionSequence& ICS2)
3696 {
3697   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3698   // conversion sequences (as defined in 13.3.3.1)
3699   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3700   //      conversion sequence than a user-defined conversion sequence or
3701   //      an ellipsis conversion sequence, and
3702   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3703   //      conversion sequence than an ellipsis conversion sequence
3704   //      (13.3.3.1.3).
3705   //
3706   // C++0x [over.best.ics]p10:
3707   //   For the purpose of ranking implicit conversion sequences as
3708   //   described in 13.3.3.2, the ambiguous conversion sequence is
3709   //   treated as a user-defined sequence that is indistinguishable
3710   //   from any other user-defined conversion sequence.
3711 
3712   // String literal to 'char *' conversion has been deprecated in C++03. It has
3713   // been removed from C++11. We still accept this conversion, if it happens at
3714   // the best viable function. Otherwise, this conversion is considered worse
3715   // than ellipsis conversion. Consider this as an extension; this is not in the
3716   // standard. For example:
3717   //
3718   // int &f(...);    // #1
3719   // void f(char*);  // #2
3720   // void g() { int &r = f("foo"); }
3721   //
3722   // In C++03, we pick #2 as the best viable function.
3723   // In C++11, we pick #1 as the best viable function, because ellipsis
3724   // conversion is better than string-literal to char* conversion (since there
3725   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3726   // convert arguments, #2 would be the best viable function in C++11.
3727   // If the best viable function has this conversion, a warning will be issued
3728   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3729 
3730   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3731       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3732       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3733     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3734                ? ImplicitConversionSequence::Worse
3735                : ImplicitConversionSequence::Better;
3736 
3737   if (ICS1.getKindRank() < ICS2.getKindRank())
3738     return ImplicitConversionSequence::Better;
3739   if (ICS2.getKindRank() < ICS1.getKindRank())
3740     return ImplicitConversionSequence::Worse;
3741 
3742   // The following checks require both conversion sequences to be of
3743   // the same kind.
3744   if (ICS1.getKind() != ICS2.getKind())
3745     return ImplicitConversionSequence::Indistinguishable;
3746 
3747   ImplicitConversionSequence::CompareKind Result =
3748       ImplicitConversionSequence::Indistinguishable;
3749 
3750   // Two implicit conversion sequences of the same form are
3751   // indistinguishable conversion sequences unless one of the
3752   // following rules apply: (C++ 13.3.3.2p3):
3753 
3754   // List-initialization sequence L1 is a better conversion sequence than
3755   // list-initialization sequence L2 if:
3756   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3757   //   if not that,
3758   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3759   //   and N1 is smaller than N2.,
3760   // even if one of the other rules in this paragraph would otherwise apply.
3761   if (!ICS1.isBad()) {
3762     if (ICS1.isStdInitializerListElement() &&
3763         !ICS2.isStdInitializerListElement())
3764       return ImplicitConversionSequence::Better;
3765     if (!ICS1.isStdInitializerListElement() &&
3766         ICS2.isStdInitializerListElement())
3767       return ImplicitConversionSequence::Worse;
3768   }
3769 
3770   if (ICS1.isStandard())
3771     // Standard conversion sequence S1 is a better conversion sequence than
3772     // standard conversion sequence S2 if [...]
3773     Result = CompareStandardConversionSequences(S, Loc,
3774                                                 ICS1.Standard, ICS2.Standard);
3775   else if (ICS1.isUserDefined()) {
3776     // User-defined conversion sequence U1 is a better conversion
3777     // sequence than another user-defined conversion sequence U2 if
3778     // they contain the same user-defined conversion function or
3779     // constructor and if the second standard conversion sequence of
3780     // U1 is better than the second standard conversion sequence of
3781     // U2 (C++ 13.3.3.2p3).
3782     if (ICS1.UserDefined.ConversionFunction ==
3783           ICS2.UserDefined.ConversionFunction)
3784       Result = CompareStandardConversionSequences(S, Loc,
3785                                                   ICS1.UserDefined.After,
3786                                                   ICS2.UserDefined.After);
3787     else
3788       Result = compareConversionFunctions(S,
3789                                           ICS1.UserDefined.ConversionFunction,
3790                                           ICS2.UserDefined.ConversionFunction);
3791   }
3792 
3793   return Result;
3794 }
3795 
3796 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3797 // determine if one is a proper subset of the other.
3798 static ImplicitConversionSequence::CompareKind
3799 compareStandardConversionSubsets(ASTContext &Context,
3800                                  const StandardConversionSequence& SCS1,
3801                                  const StandardConversionSequence& SCS2) {
3802   ImplicitConversionSequence::CompareKind Result
3803     = ImplicitConversionSequence::Indistinguishable;
3804 
3805   // the identity conversion sequence is considered to be a subsequence of
3806   // any non-identity conversion sequence
3807   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3808     return ImplicitConversionSequence::Better;
3809   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3810     return ImplicitConversionSequence::Worse;
3811 
3812   if (SCS1.Second != SCS2.Second) {
3813     if (SCS1.Second == ICK_Identity)
3814       Result = ImplicitConversionSequence::Better;
3815     else if (SCS2.Second == ICK_Identity)
3816       Result = ImplicitConversionSequence::Worse;
3817     else
3818       return ImplicitConversionSequence::Indistinguishable;
3819   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3820     return ImplicitConversionSequence::Indistinguishable;
3821 
3822   if (SCS1.Third == SCS2.Third) {
3823     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3824                              : ImplicitConversionSequence::Indistinguishable;
3825   }
3826 
3827   if (SCS1.Third == ICK_Identity)
3828     return Result == ImplicitConversionSequence::Worse
3829              ? ImplicitConversionSequence::Indistinguishable
3830              : ImplicitConversionSequence::Better;
3831 
3832   if (SCS2.Third == ICK_Identity)
3833     return Result == ImplicitConversionSequence::Better
3834              ? ImplicitConversionSequence::Indistinguishable
3835              : ImplicitConversionSequence::Worse;
3836 
3837   return ImplicitConversionSequence::Indistinguishable;
3838 }
3839 
3840 /// Determine whether one of the given reference bindings is better
3841 /// than the other based on what kind of bindings they are.
3842 static bool
3843 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3844                              const StandardConversionSequence &SCS2) {
3845   // C++0x [over.ics.rank]p3b4:
3846   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3847   //      implicit object parameter of a non-static member function declared
3848   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3849   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3850   //      lvalue reference to a function lvalue and S2 binds an rvalue
3851   //      reference*.
3852   //
3853   // FIXME: Rvalue references. We're going rogue with the above edits,
3854   // because the semantics in the current C++0x working paper (N3225 at the
3855   // time of this writing) break the standard definition of std::forward
3856   // and std::reference_wrapper when dealing with references to functions.
3857   // Proposed wording changes submitted to CWG for consideration.
3858   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3859       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3860     return false;
3861 
3862   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3863           SCS2.IsLvalueReference) ||
3864          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3865           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3866 }
3867 
3868 enum class FixedEnumPromotion {
3869   None,
3870   ToUnderlyingType,
3871   ToPromotedUnderlyingType
3872 };
3873 
3874 /// Returns kind of fixed enum promotion the \a SCS uses.
3875 static FixedEnumPromotion
3876 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3877 
3878   if (SCS.Second != ICK_Integral_Promotion)
3879     return FixedEnumPromotion::None;
3880 
3881   QualType FromType = SCS.getFromType();
3882   if (!FromType->isEnumeralType())
3883     return FixedEnumPromotion::None;
3884 
3885   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3886   if (!Enum->isFixed())
3887     return FixedEnumPromotion::None;
3888 
3889   QualType UnderlyingType = Enum->getIntegerType();
3890   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3891     return FixedEnumPromotion::ToUnderlyingType;
3892 
3893   return FixedEnumPromotion::ToPromotedUnderlyingType;
3894 }
3895 
3896 /// CompareStandardConversionSequences - Compare two standard
3897 /// conversion sequences to determine whether one is better than the
3898 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3899 static ImplicitConversionSequence::CompareKind
3900 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3901                                    const StandardConversionSequence& SCS1,
3902                                    const StandardConversionSequence& SCS2)
3903 {
3904   // Standard conversion sequence S1 is a better conversion sequence
3905   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3906 
3907   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3908   //     sequences in the canonical form defined by 13.3.3.1.1,
3909   //     excluding any Lvalue Transformation; the identity conversion
3910   //     sequence is considered to be a subsequence of any
3911   //     non-identity conversion sequence) or, if not that,
3912   if (ImplicitConversionSequence::CompareKind CK
3913         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3914     return CK;
3915 
3916   //  -- the rank of S1 is better than the rank of S2 (by the rules
3917   //     defined below), or, if not that,
3918   ImplicitConversionRank Rank1 = SCS1.getRank();
3919   ImplicitConversionRank Rank2 = SCS2.getRank();
3920   if (Rank1 < Rank2)
3921     return ImplicitConversionSequence::Better;
3922   else if (Rank2 < Rank1)
3923     return ImplicitConversionSequence::Worse;
3924 
3925   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3926   // are indistinguishable unless one of the following rules
3927   // applies:
3928 
3929   //   A conversion that is not a conversion of a pointer, or
3930   //   pointer to member, to bool is better than another conversion
3931   //   that is such a conversion.
3932   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3933     return SCS2.isPointerConversionToBool()
3934              ? ImplicitConversionSequence::Better
3935              : ImplicitConversionSequence::Worse;
3936 
3937   // C++14 [over.ics.rank]p4b2:
3938   // This is retroactively applied to C++11 by CWG 1601.
3939   //
3940   //   A conversion that promotes an enumeration whose underlying type is fixed
3941   //   to its underlying type is better than one that promotes to the promoted
3942   //   underlying type, if the two are different.
3943   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3944   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3945   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3946       FEP1 != FEP2)
3947     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3948                ? ImplicitConversionSequence::Better
3949                : ImplicitConversionSequence::Worse;
3950 
3951   // C++ [over.ics.rank]p4b2:
3952   //
3953   //   If class B is derived directly or indirectly from class A,
3954   //   conversion of B* to A* is better than conversion of B* to
3955   //   void*, and conversion of A* to void* is better than conversion
3956   //   of B* to void*.
3957   bool SCS1ConvertsToVoid
3958     = SCS1.isPointerConversionToVoidPointer(S.Context);
3959   bool SCS2ConvertsToVoid
3960     = SCS2.isPointerConversionToVoidPointer(S.Context);
3961   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3962     // Exactly one of the conversion sequences is a conversion to
3963     // a void pointer; it's the worse conversion.
3964     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3965                               : ImplicitConversionSequence::Worse;
3966   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3967     // Neither conversion sequence converts to a void pointer; compare
3968     // their derived-to-base conversions.
3969     if (ImplicitConversionSequence::CompareKind DerivedCK
3970           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3971       return DerivedCK;
3972   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3973              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3974     // Both conversion sequences are conversions to void
3975     // pointers. Compare the source types to determine if there's an
3976     // inheritance relationship in their sources.
3977     QualType FromType1 = SCS1.getFromType();
3978     QualType FromType2 = SCS2.getFromType();
3979 
3980     // Adjust the types we're converting from via the array-to-pointer
3981     // conversion, if we need to.
3982     if (SCS1.First == ICK_Array_To_Pointer)
3983       FromType1 = S.Context.getArrayDecayedType(FromType1);
3984     if (SCS2.First == ICK_Array_To_Pointer)
3985       FromType2 = S.Context.getArrayDecayedType(FromType2);
3986 
3987     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3988     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3989 
3990     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3991       return ImplicitConversionSequence::Better;
3992     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3993       return ImplicitConversionSequence::Worse;
3994 
3995     // Objective-C++: If one interface is more specific than the
3996     // other, it is the better one.
3997     const ObjCObjectPointerType* FromObjCPtr1
3998       = FromType1->getAs<ObjCObjectPointerType>();
3999     const ObjCObjectPointerType* FromObjCPtr2
4000       = FromType2->getAs<ObjCObjectPointerType>();
4001     if (FromObjCPtr1 && FromObjCPtr2) {
4002       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4003                                                           FromObjCPtr2);
4004       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4005                                                            FromObjCPtr1);
4006       if (AssignLeft != AssignRight) {
4007         return AssignLeft? ImplicitConversionSequence::Better
4008                          : ImplicitConversionSequence::Worse;
4009       }
4010     }
4011   }
4012 
4013   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4014     // Check for a better reference binding based on the kind of bindings.
4015     if (isBetterReferenceBindingKind(SCS1, SCS2))
4016       return ImplicitConversionSequence::Better;
4017     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4018       return ImplicitConversionSequence::Worse;
4019   }
4020 
4021   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4022   // bullet 3).
4023   if (ImplicitConversionSequence::CompareKind QualCK
4024         = CompareQualificationConversions(S, SCS1, SCS2))
4025     return QualCK;
4026 
4027   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4028     // C++ [over.ics.rank]p3b4:
4029     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4030     //      which the references refer are the same type except for
4031     //      top-level cv-qualifiers, and the type to which the reference
4032     //      initialized by S2 refers is more cv-qualified than the type
4033     //      to which the reference initialized by S1 refers.
4034     QualType T1 = SCS1.getToType(2);
4035     QualType T2 = SCS2.getToType(2);
4036     T1 = S.Context.getCanonicalType(T1);
4037     T2 = S.Context.getCanonicalType(T2);
4038     Qualifiers T1Quals, T2Quals;
4039     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4040     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4041     if (UnqualT1 == UnqualT2) {
4042       // Objective-C++ ARC: If the references refer to objects with different
4043       // lifetimes, prefer bindings that don't change lifetime.
4044       if (SCS1.ObjCLifetimeConversionBinding !=
4045                                           SCS2.ObjCLifetimeConversionBinding) {
4046         return SCS1.ObjCLifetimeConversionBinding
4047                                            ? ImplicitConversionSequence::Worse
4048                                            : ImplicitConversionSequence::Better;
4049       }
4050 
4051       // If the type is an array type, promote the element qualifiers to the
4052       // type for comparison.
4053       if (isa<ArrayType>(T1) && T1Quals)
4054         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4055       if (isa<ArrayType>(T2) && T2Quals)
4056         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4057       if (T2.isMoreQualifiedThan(T1))
4058         return ImplicitConversionSequence::Better;
4059       if (T1.isMoreQualifiedThan(T2))
4060         return ImplicitConversionSequence::Worse;
4061     }
4062   }
4063 
4064   // In Microsoft mode, prefer an integral conversion to a
4065   // floating-to-integral conversion if the integral conversion
4066   // is between types of the same size.
4067   // For example:
4068   // void f(float);
4069   // void f(int);
4070   // int main {
4071   //    long a;
4072   //    f(a);
4073   // }
4074   // Here, MSVC will call f(int) instead of generating a compile error
4075   // as clang will do in standard mode.
4076   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4077       SCS2.Second == ICK_Floating_Integral &&
4078       S.Context.getTypeSize(SCS1.getFromType()) ==
4079           S.Context.getTypeSize(SCS1.getToType(2)))
4080     return ImplicitConversionSequence::Better;
4081 
4082   // Prefer a compatible vector conversion over a lax vector conversion
4083   // For example:
4084   //
4085   // typedef float __v4sf __attribute__((__vector_size__(16)));
4086   // void f(vector float);
4087   // void f(vector signed int);
4088   // int main() {
4089   //   __v4sf a;
4090   //   f(a);
4091   // }
4092   // Here, we'd like to choose f(vector float) and not
4093   // report an ambiguous call error
4094   if (SCS1.Second == ICK_Vector_Conversion &&
4095       SCS2.Second == ICK_Vector_Conversion) {
4096     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4097         SCS1.getFromType(), SCS1.getToType(2));
4098     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4099         SCS2.getFromType(), SCS2.getToType(2));
4100 
4101     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4102       return SCS1IsCompatibleVectorConversion
4103                  ? ImplicitConversionSequence::Better
4104                  : ImplicitConversionSequence::Worse;
4105   }
4106 
4107   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4108       SCS2.Second == ICK_SVE_Vector_Conversion) {
4109     bool SCS1IsCompatibleSVEVectorConversion =
4110         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4111     bool SCS2IsCompatibleSVEVectorConversion =
4112         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4113 
4114     if (SCS1IsCompatibleSVEVectorConversion !=
4115         SCS2IsCompatibleSVEVectorConversion)
4116       return SCS1IsCompatibleSVEVectorConversion
4117                  ? ImplicitConversionSequence::Better
4118                  : ImplicitConversionSequence::Worse;
4119   }
4120 
4121   return ImplicitConversionSequence::Indistinguishable;
4122 }
4123 
4124 /// CompareQualificationConversions - Compares two standard conversion
4125 /// sequences to determine whether they can be ranked based on their
4126 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4127 static ImplicitConversionSequence::CompareKind
4128 CompareQualificationConversions(Sema &S,
4129                                 const StandardConversionSequence& SCS1,
4130                                 const StandardConversionSequence& SCS2) {
4131   // C++ 13.3.3.2p3:
4132   //  -- S1 and S2 differ only in their qualification conversion and
4133   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4134   //     cv-qualification signature of type T1 is a proper subset of
4135   //     the cv-qualification signature of type T2, and S1 is not the
4136   //     deprecated string literal array-to-pointer conversion (4.2).
4137   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4138       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4139     return ImplicitConversionSequence::Indistinguishable;
4140 
4141   // FIXME: the example in the standard doesn't use a qualification
4142   // conversion (!)
4143   QualType T1 = SCS1.getToType(2);
4144   QualType T2 = SCS2.getToType(2);
4145   T1 = S.Context.getCanonicalType(T1);
4146   T2 = S.Context.getCanonicalType(T2);
4147   assert(!T1->isReferenceType() && !T2->isReferenceType());
4148   Qualifiers T1Quals, T2Quals;
4149   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4150   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4151 
4152   // If the types are the same, we won't learn anything by unwrapping
4153   // them.
4154   if (UnqualT1 == UnqualT2)
4155     return ImplicitConversionSequence::Indistinguishable;
4156 
4157   ImplicitConversionSequence::CompareKind Result
4158     = ImplicitConversionSequence::Indistinguishable;
4159 
4160   // Objective-C++ ARC:
4161   //   Prefer qualification conversions not involving a change in lifetime
4162   //   to qualification conversions that do not change lifetime.
4163   if (SCS1.QualificationIncludesObjCLifetime !=
4164                                       SCS2.QualificationIncludesObjCLifetime) {
4165     Result = SCS1.QualificationIncludesObjCLifetime
4166                ? ImplicitConversionSequence::Worse
4167                : ImplicitConversionSequence::Better;
4168   }
4169 
4170   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4171     // Within each iteration of the loop, we check the qualifiers to
4172     // determine if this still looks like a qualification
4173     // conversion. Then, if all is well, we unwrap one more level of
4174     // pointers or pointers-to-members and do it all again
4175     // until there are no more pointers or pointers-to-members left
4176     // to unwrap. This essentially mimics what
4177     // IsQualificationConversion does, but here we're checking for a
4178     // strict subset of qualifiers.
4179     if (T1.getQualifiers().withoutObjCLifetime() ==
4180         T2.getQualifiers().withoutObjCLifetime())
4181       // The qualifiers are the same, so this doesn't tell us anything
4182       // about how the sequences rank.
4183       // ObjC ownership quals are omitted above as they interfere with
4184       // the ARC overload rule.
4185       ;
4186     else if (T2.isMoreQualifiedThan(T1)) {
4187       // T1 has fewer qualifiers, so it could be the better sequence.
4188       if (Result == ImplicitConversionSequence::Worse)
4189         // Neither has qualifiers that are a subset of the other's
4190         // qualifiers.
4191         return ImplicitConversionSequence::Indistinguishable;
4192 
4193       Result = ImplicitConversionSequence::Better;
4194     } else if (T1.isMoreQualifiedThan(T2)) {
4195       // T2 has fewer qualifiers, so it could be the better sequence.
4196       if (Result == ImplicitConversionSequence::Better)
4197         // Neither has qualifiers that are a subset of the other's
4198         // qualifiers.
4199         return ImplicitConversionSequence::Indistinguishable;
4200 
4201       Result = ImplicitConversionSequence::Worse;
4202     } else {
4203       // Qualifiers are disjoint.
4204       return ImplicitConversionSequence::Indistinguishable;
4205     }
4206 
4207     // If the types after this point are equivalent, we're done.
4208     if (S.Context.hasSameUnqualifiedType(T1, T2))
4209       break;
4210   }
4211 
4212   // Check that the winning standard conversion sequence isn't using
4213   // the deprecated string literal array to pointer conversion.
4214   switch (Result) {
4215   case ImplicitConversionSequence::Better:
4216     if (SCS1.DeprecatedStringLiteralToCharPtr)
4217       Result = ImplicitConversionSequence::Indistinguishable;
4218     break;
4219 
4220   case ImplicitConversionSequence::Indistinguishable:
4221     break;
4222 
4223   case ImplicitConversionSequence::Worse:
4224     if (SCS2.DeprecatedStringLiteralToCharPtr)
4225       Result = ImplicitConversionSequence::Indistinguishable;
4226     break;
4227   }
4228 
4229   return Result;
4230 }
4231 
4232 /// CompareDerivedToBaseConversions - Compares two standard conversion
4233 /// sequences to determine whether they can be ranked based on their
4234 /// various kinds of derived-to-base conversions (C++
4235 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4236 /// conversions between Objective-C interface types.
4237 static ImplicitConversionSequence::CompareKind
4238 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4239                                 const StandardConversionSequence& SCS1,
4240                                 const StandardConversionSequence& SCS2) {
4241   QualType FromType1 = SCS1.getFromType();
4242   QualType ToType1 = SCS1.getToType(1);
4243   QualType FromType2 = SCS2.getFromType();
4244   QualType ToType2 = SCS2.getToType(1);
4245 
4246   // Adjust the types we're converting from via the array-to-pointer
4247   // conversion, if we need to.
4248   if (SCS1.First == ICK_Array_To_Pointer)
4249     FromType1 = S.Context.getArrayDecayedType(FromType1);
4250   if (SCS2.First == ICK_Array_To_Pointer)
4251     FromType2 = S.Context.getArrayDecayedType(FromType2);
4252 
4253   // Canonicalize all of the types.
4254   FromType1 = S.Context.getCanonicalType(FromType1);
4255   ToType1 = S.Context.getCanonicalType(ToType1);
4256   FromType2 = S.Context.getCanonicalType(FromType2);
4257   ToType2 = S.Context.getCanonicalType(ToType2);
4258 
4259   // C++ [over.ics.rank]p4b3:
4260   //
4261   //   If class B is derived directly or indirectly from class A and
4262   //   class C is derived directly or indirectly from B,
4263   //
4264   // Compare based on pointer conversions.
4265   if (SCS1.Second == ICK_Pointer_Conversion &&
4266       SCS2.Second == ICK_Pointer_Conversion &&
4267       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4268       FromType1->isPointerType() && FromType2->isPointerType() &&
4269       ToType1->isPointerType() && ToType2->isPointerType()) {
4270     QualType FromPointee1 =
4271         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4272     QualType ToPointee1 =
4273         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4274     QualType FromPointee2 =
4275         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4276     QualType ToPointee2 =
4277         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4278 
4279     //   -- conversion of C* to B* is better than conversion of C* to A*,
4280     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4281       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4282         return ImplicitConversionSequence::Better;
4283       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4284         return ImplicitConversionSequence::Worse;
4285     }
4286 
4287     //   -- conversion of B* to A* is better than conversion of C* to A*,
4288     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4289       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4290         return ImplicitConversionSequence::Better;
4291       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4292         return ImplicitConversionSequence::Worse;
4293     }
4294   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4295              SCS2.Second == ICK_Pointer_Conversion) {
4296     const ObjCObjectPointerType *FromPtr1
4297       = FromType1->getAs<ObjCObjectPointerType>();
4298     const ObjCObjectPointerType *FromPtr2
4299       = FromType2->getAs<ObjCObjectPointerType>();
4300     const ObjCObjectPointerType *ToPtr1
4301       = ToType1->getAs<ObjCObjectPointerType>();
4302     const ObjCObjectPointerType *ToPtr2
4303       = ToType2->getAs<ObjCObjectPointerType>();
4304 
4305     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4306       // Apply the same conversion ranking rules for Objective-C pointer types
4307       // that we do for C++ pointers to class types. However, we employ the
4308       // Objective-C pseudo-subtyping relationship used for assignment of
4309       // Objective-C pointer types.
4310       bool FromAssignLeft
4311         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4312       bool FromAssignRight
4313         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4314       bool ToAssignLeft
4315         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4316       bool ToAssignRight
4317         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4318 
4319       // A conversion to an a non-id object pointer type or qualified 'id'
4320       // type is better than a conversion to 'id'.
4321       if (ToPtr1->isObjCIdType() &&
4322           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4323         return ImplicitConversionSequence::Worse;
4324       if (ToPtr2->isObjCIdType() &&
4325           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4326         return ImplicitConversionSequence::Better;
4327 
4328       // A conversion to a non-id object pointer type is better than a
4329       // conversion to a qualified 'id' type
4330       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4331         return ImplicitConversionSequence::Worse;
4332       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4333         return ImplicitConversionSequence::Better;
4334 
4335       // A conversion to an a non-Class object pointer type or qualified 'Class'
4336       // type is better than a conversion to 'Class'.
4337       if (ToPtr1->isObjCClassType() &&
4338           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4339         return ImplicitConversionSequence::Worse;
4340       if (ToPtr2->isObjCClassType() &&
4341           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4342         return ImplicitConversionSequence::Better;
4343 
4344       // A conversion to a non-Class object pointer type is better than a
4345       // conversion to a qualified 'Class' type.
4346       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4347         return ImplicitConversionSequence::Worse;
4348       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4349         return ImplicitConversionSequence::Better;
4350 
4351       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4352       if (S.Context.hasSameType(FromType1, FromType2) &&
4353           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4354           (ToAssignLeft != ToAssignRight)) {
4355         if (FromPtr1->isSpecialized()) {
4356           // "conversion of B<A> * to B * is better than conversion of B * to
4357           // C *.
4358           bool IsFirstSame =
4359               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4360           bool IsSecondSame =
4361               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4362           if (IsFirstSame) {
4363             if (!IsSecondSame)
4364               return ImplicitConversionSequence::Better;
4365           } else if (IsSecondSame)
4366             return ImplicitConversionSequence::Worse;
4367         }
4368         return ToAssignLeft? ImplicitConversionSequence::Worse
4369                            : ImplicitConversionSequence::Better;
4370       }
4371 
4372       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4373       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4374           (FromAssignLeft != FromAssignRight))
4375         return FromAssignLeft? ImplicitConversionSequence::Better
4376         : ImplicitConversionSequence::Worse;
4377     }
4378   }
4379 
4380   // Ranking of member-pointer types.
4381   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4382       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4383       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4384     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4385     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4386     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4387     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4388     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4389     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4390     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4391     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4392     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4393     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4394     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4395     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4396     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4397     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4398       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4399         return ImplicitConversionSequence::Worse;
4400       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4401         return ImplicitConversionSequence::Better;
4402     }
4403     // conversion of B::* to C::* is better than conversion of A::* to C::*
4404     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4405       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4406         return ImplicitConversionSequence::Better;
4407       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4408         return ImplicitConversionSequence::Worse;
4409     }
4410   }
4411 
4412   if (SCS1.Second == ICK_Derived_To_Base) {
4413     //   -- conversion of C to B is better than conversion of C to A,
4414     //   -- binding of an expression of type C to a reference of type
4415     //      B& is better than binding an expression of type C to a
4416     //      reference of type A&,
4417     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4418         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4419       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4420         return ImplicitConversionSequence::Better;
4421       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4422         return ImplicitConversionSequence::Worse;
4423     }
4424 
4425     //   -- conversion of B to A is better than conversion of C to A.
4426     //   -- binding of an expression of type B to a reference of type
4427     //      A& is better than binding an expression of type C to a
4428     //      reference of type A&,
4429     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4430         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4431       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4432         return ImplicitConversionSequence::Better;
4433       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4434         return ImplicitConversionSequence::Worse;
4435     }
4436   }
4437 
4438   return ImplicitConversionSequence::Indistinguishable;
4439 }
4440 
4441 /// Determine whether the given type is valid, e.g., it is not an invalid
4442 /// C++ class.
4443 static bool isTypeValid(QualType T) {
4444   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4445     return !Record->isInvalidDecl();
4446 
4447   return true;
4448 }
4449 
4450 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4451   if (!T.getQualifiers().hasUnaligned())
4452     return T;
4453 
4454   Qualifiers Q;
4455   T = Ctx.getUnqualifiedArrayType(T, Q);
4456   Q.removeUnaligned();
4457   return Ctx.getQualifiedType(T, Q);
4458 }
4459 
4460 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4461 /// determine whether they are reference-compatible,
4462 /// reference-related, or incompatible, for use in C++ initialization by
4463 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4464 /// type, and the first type (T1) is the pointee type of the reference
4465 /// type being initialized.
4466 Sema::ReferenceCompareResult
4467 Sema::CompareReferenceRelationship(SourceLocation Loc,
4468                                    QualType OrigT1, QualType OrigT2,
4469                                    ReferenceConversions *ConvOut) {
4470   assert(!OrigT1->isReferenceType() &&
4471     "T1 must be the pointee type of the reference type");
4472   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4473 
4474   QualType T1 = Context.getCanonicalType(OrigT1);
4475   QualType T2 = Context.getCanonicalType(OrigT2);
4476   Qualifiers T1Quals, T2Quals;
4477   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4478   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4479 
4480   ReferenceConversions ConvTmp;
4481   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4482   Conv = ReferenceConversions();
4483 
4484   // C++2a [dcl.init.ref]p4:
4485   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4486   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4487   //   T1 is a base class of T2.
4488   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4489   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4490   //   "pointer to cv1 T1" via a standard conversion sequence.
4491 
4492   // Check for standard conversions we can apply to pointers: derived-to-base
4493   // conversions, ObjC pointer conversions, and function pointer conversions.
4494   // (Qualification conversions are checked last.)
4495   QualType ConvertedT2;
4496   if (UnqualT1 == UnqualT2) {
4497     // Nothing to do.
4498   } else if (isCompleteType(Loc, OrigT2) &&
4499              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4500              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4501     Conv |= ReferenceConversions::DerivedToBase;
4502   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4503            UnqualT2->isObjCObjectOrInterfaceType() &&
4504            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4505     Conv |= ReferenceConversions::ObjC;
4506   else if (UnqualT2->isFunctionType() &&
4507            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4508     Conv |= ReferenceConversions::Function;
4509     // No need to check qualifiers; function types don't have them.
4510     return Ref_Compatible;
4511   }
4512   bool ConvertedReferent = Conv != 0;
4513 
4514   // We can have a qualification conversion. Compute whether the types are
4515   // similar at the same time.
4516   bool PreviousToQualsIncludeConst = true;
4517   bool TopLevel = true;
4518   do {
4519     if (T1 == T2)
4520       break;
4521 
4522     // We will need a qualification conversion.
4523     Conv |= ReferenceConversions::Qualification;
4524 
4525     // Track whether we performed a qualification conversion anywhere other
4526     // than the top level. This matters for ranking reference bindings in
4527     // overload resolution.
4528     if (!TopLevel)
4529       Conv |= ReferenceConversions::NestedQualification;
4530 
4531     // MS compiler ignores __unaligned qualifier for references; do the same.
4532     T1 = withoutUnaligned(Context, T1);
4533     T2 = withoutUnaligned(Context, T2);
4534 
4535     // If we find a qualifier mismatch, the types are not reference-compatible,
4536     // but are still be reference-related if they're similar.
4537     bool ObjCLifetimeConversion = false;
4538     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4539                                        PreviousToQualsIncludeConst,
4540                                        ObjCLifetimeConversion))
4541       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4542                  ? Ref_Related
4543                  : Ref_Incompatible;
4544 
4545     // FIXME: Should we track this for any level other than the first?
4546     if (ObjCLifetimeConversion)
4547       Conv |= ReferenceConversions::ObjCLifetime;
4548 
4549     TopLevel = false;
4550   } while (Context.UnwrapSimilarTypes(T1, T2));
4551 
4552   // At this point, if the types are reference-related, we must either have the
4553   // same inner type (ignoring qualifiers), or must have already worked out how
4554   // to convert the referent.
4555   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4556              ? Ref_Compatible
4557              : Ref_Incompatible;
4558 }
4559 
4560 /// Look for a user-defined conversion to a value reference-compatible
4561 ///        with DeclType. Return true if something definite is found.
4562 static bool
4563 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4564                          QualType DeclType, SourceLocation DeclLoc,
4565                          Expr *Init, QualType T2, bool AllowRvalues,
4566                          bool AllowExplicit) {
4567   assert(T2->isRecordType() && "Can only find conversions of record types.");
4568   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4569 
4570   OverloadCandidateSet CandidateSet(
4571       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4572   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4573   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4574     NamedDecl *D = *I;
4575     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4576     if (isa<UsingShadowDecl>(D))
4577       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4578 
4579     FunctionTemplateDecl *ConvTemplate
4580       = dyn_cast<FunctionTemplateDecl>(D);
4581     CXXConversionDecl *Conv;
4582     if (ConvTemplate)
4583       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4584     else
4585       Conv = cast<CXXConversionDecl>(D);
4586 
4587     if (AllowRvalues) {
4588       // If we are initializing an rvalue reference, don't permit conversion
4589       // functions that return lvalues.
4590       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4591         const ReferenceType *RefType
4592           = Conv->getConversionType()->getAs<LValueReferenceType>();
4593         if (RefType && !RefType->getPointeeType()->isFunctionType())
4594           continue;
4595       }
4596 
4597       if (!ConvTemplate &&
4598           S.CompareReferenceRelationship(
4599               DeclLoc,
4600               Conv->getConversionType()
4601                   .getNonReferenceType()
4602                   .getUnqualifiedType(),
4603               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4604               Sema::Ref_Incompatible)
4605         continue;
4606     } else {
4607       // If the conversion function doesn't return a reference type,
4608       // it can't be considered for this conversion. An rvalue reference
4609       // is only acceptable if its referencee is a function type.
4610 
4611       const ReferenceType *RefType =
4612         Conv->getConversionType()->getAs<ReferenceType>();
4613       if (!RefType ||
4614           (!RefType->isLValueReferenceType() &&
4615            !RefType->getPointeeType()->isFunctionType()))
4616         continue;
4617     }
4618 
4619     if (ConvTemplate)
4620       S.AddTemplateConversionCandidate(
4621           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4622           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4623     else
4624       S.AddConversionCandidate(
4625           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4626           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4627   }
4628 
4629   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4630 
4631   OverloadCandidateSet::iterator Best;
4632   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4633   case OR_Success:
4634     // C++ [over.ics.ref]p1:
4635     //
4636     //   [...] If the parameter binds directly to the result of
4637     //   applying a conversion function to the argument
4638     //   expression, the implicit conversion sequence is a
4639     //   user-defined conversion sequence (13.3.3.1.2), with the
4640     //   second standard conversion sequence either an identity
4641     //   conversion or, if the conversion function returns an
4642     //   entity of a type that is a derived class of the parameter
4643     //   type, a derived-to-base Conversion.
4644     if (!Best->FinalConversion.DirectBinding)
4645       return false;
4646 
4647     ICS.setUserDefined();
4648     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4649     ICS.UserDefined.After = Best->FinalConversion;
4650     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4651     ICS.UserDefined.ConversionFunction = Best->Function;
4652     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4653     ICS.UserDefined.EllipsisConversion = false;
4654     assert(ICS.UserDefined.After.ReferenceBinding &&
4655            ICS.UserDefined.After.DirectBinding &&
4656            "Expected a direct reference binding!");
4657     return true;
4658 
4659   case OR_Ambiguous:
4660     ICS.setAmbiguous();
4661     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4662          Cand != CandidateSet.end(); ++Cand)
4663       if (Cand->Best)
4664         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4665     return true;
4666 
4667   case OR_No_Viable_Function:
4668   case OR_Deleted:
4669     // There was no suitable conversion, or we found a deleted
4670     // conversion; continue with other checks.
4671     return false;
4672   }
4673 
4674   llvm_unreachable("Invalid OverloadResult!");
4675 }
4676 
4677 /// Compute an implicit conversion sequence for reference
4678 /// initialization.
4679 static ImplicitConversionSequence
4680 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4681                  SourceLocation DeclLoc,
4682                  bool SuppressUserConversions,
4683                  bool AllowExplicit) {
4684   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4685 
4686   // Most paths end in a failed conversion.
4687   ImplicitConversionSequence ICS;
4688   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4689 
4690   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4691   QualType T2 = Init->getType();
4692 
4693   // If the initializer is the address of an overloaded function, try
4694   // to resolve the overloaded function. If all goes well, T2 is the
4695   // type of the resulting function.
4696   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4697     DeclAccessPair Found;
4698     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4699                                                                 false, Found))
4700       T2 = Fn->getType();
4701   }
4702 
4703   // Compute some basic properties of the types and the initializer.
4704   bool isRValRef = DeclType->isRValueReferenceType();
4705   Expr::Classification InitCategory = Init->Classify(S.Context);
4706 
4707   Sema::ReferenceConversions RefConv;
4708   Sema::ReferenceCompareResult RefRelationship =
4709       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4710 
4711   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4712     ICS.setStandard();
4713     ICS.Standard.First = ICK_Identity;
4714     // FIXME: A reference binding can be a function conversion too. We should
4715     // consider that when ordering reference-to-function bindings.
4716     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4717                               ? ICK_Derived_To_Base
4718                               : (RefConv & Sema::ReferenceConversions::ObjC)
4719                                     ? ICK_Compatible_Conversion
4720                                     : ICK_Identity;
4721     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4722     // a reference binding that performs a non-top-level qualification
4723     // conversion as a qualification conversion, not as an identity conversion.
4724     ICS.Standard.Third = (RefConv &
4725                               Sema::ReferenceConversions::NestedQualification)
4726                              ? ICK_Qualification
4727                              : ICK_Identity;
4728     ICS.Standard.setFromType(T2);
4729     ICS.Standard.setToType(0, T2);
4730     ICS.Standard.setToType(1, T1);
4731     ICS.Standard.setToType(2, T1);
4732     ICS.Standard.ReferenceBinding = true;
4733     ICS.Standard.DirectBinding = BindsDirectly;
4734     ICS.Standard.IsLvalueReference = !isRValRef;
4735     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4736     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4737     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4738     ICS.Standard.ObjCLifetimeConversionBinding =
4739         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4740     ICS.Standard.CopyConstructor = nullptr;
4741     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4742   };
4743 
4744   // C++0x [dcl.init.ref]p5:
4745   //   A reference to type "cv1 T1" is initialized by an expression
4746   //   of type "cv2 T2" as follows:
4747 
4748   //     -- If reference is an lvalue reference and the initializer expression
4749   if (!isRValRef) {
4750     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4751     //        reference-compatible with "cv2 T2," or
4752     //
4753     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4754     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4755       // C++ [over.ics.ref]p1:
4756       //   When a parameter of reference type binds directly (8.5.3)
4757       //   to an argument expression, the implicit conversion sequence
4758       //   is the identity conversion, unless the argument expression
4759       //   has a type that is a derived class of the parameter type,
4760       //   in which case the implicit conversion sequence is a
4761       //   derived-to-base Conversion (13.3.3.1).
4762       SetAsReferenceBinding(/*BindsDirectly=*/true);
4763 
4764       // Nothing more to do: the inaccessibility/ambiguity check for
4765       // derived-to-base conversions is suppressed when we're
4766       // computing the implicit conversion sequence (C++
4767       // [over.best.ics]p2).
4768       return ICS;
4769     }
4770 
4771     //       -- has a class type (i.e., T2 is a class type), where T1 is
4772     //          not reference-related to T2, and can be implicitly
4773     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4774     //          is reference-compatible with "cv3 T3" 92) (this
4775     //          conversion is selected by enumerating the applicable
4776     //          conversion functions (13.3.1.6) and choosing the best
4777     //          one through overload resolution (13.3)),
4778     if (!SuppressUserConversions && T2->isRecordType() &&
4779         S.isCompleteType(DeclLoc, T2) &&
4780         RefRelationship == Sema::Ref_Incompatible) {
4781       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4782                                    Init, T2, /*AllowRvalues=*/false,
4783                                    AllowExplicit))
4784         return ICS;
4785     }
4786   }
4787 
4788   //     -- Otherwise, the reference shall be an lvalue reference to a
4789   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4790   //        shall be an rvalue reference.
4791   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4792     return ICS;
4793 
4794   //       -- If the initializer expression
4795   //
4796   //            -- is an xvalue, class prvalue, array prvalue or function
4797   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4798   if (RefRelationship == Sema::Ref_Compatible &&
4799       (InitCategory.isXValue() ||
4800        (InitCategory.isPRValue() &&
4801           (T2->isRecordType() || T2->isArrayType())) ||
4802        (InitCategory.isLValue() && T2->isFunctionType()))) {
4803     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4804     // binding unless we're binding to a class prvalue.
4805     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4806     // allow the use of rvalue references in C++98/03 for the benefit of
4807     // standard library implementors; therefore, we need the xvalue check here.
4808     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4809                           !(InitCategory.isPRValue() || T2->isRecordType()));
4810     return ICS;
4811   }
4812 
4813   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4814   //               reference-related to T2, and can be implicitly converted to
4815   //               an xvalue, class prvalue, or function lvalue of type
4816   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4817   //               "cv3 T3",
4818   //
4819   //          then the reference is bound to the value of the initializer
4820   //          expression in the first case and to the result of the conversion
4821   //          in the second case (or, in either case, to an appropriate base
4822   //          class subobject).
4823   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4824       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4825       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4826                                Init, T2, /*AllowRvalues=*/true,
4827                                AllowExplicit)) {
4828     // In the second case, if the reference is an rvalue reference
4829     // and the second standard conversion sequence of the
4830     // user-defined conversion sequence includes an lvalue-to-rvalue
4831     // conversion, the program is ill-formed.
4832     if (ICS.isUserDefined() && isRValRef &&
4833         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4834       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4835 
4836     return ICS;
4837   }
4838 
4839   // A temporary of function type cannot be created; don't even try.
4840   if (T1->isFunctionType())
4841     return ICS;
4842 
4843   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4844   //          initialized from the initializer expression using the
4845   //          rules for a non-reference copy initialization (8.5). The
4846   //          reference is then bound to the temporary. If T1 is
4847   //          reference-related to T2, cv1 must be the same
4848   //          cv-qualification as, or greater cv-qualification than,
4849   //          cv2; otherwise, the program is ill-formed.
4850   if (RefRelationship == Sema::Ref_Related) {
4851     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4852     // we would be reference-compatible or reference-compatible with
4853     // added qualification. But that wasn't the case, so the reference
4854     // initialization fails.
4855     //
4856     // Note that we only want to check address spaces and cvr-qualifiers here.
4857     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4858     Qualifiers T1Quals = T1.getQualifiers();
4859     Qualifiers T2Quals = T2.getQualifiers();
4860     T1Quals.removeObjCGCAttr();
4861     T1Quals.removeObjCLifetime();
4862     T2Quals.removeObjCGCAttr();
4863     T2Quals.removeObjCLifetime();
4864     // MS compiler ignores __unaligned qualifier for references; do the same.
4865     T1Quals.removeUnaligned();
4866     T2Quals.removeUnaligned();
4867     if (!T1Quals.compatiblyIncludes(T2Quals))
4868       return ICS;
4869   }
4870 
4871   // If at least one of the types is a class type, the types are not
4872   // related, and we aren't allowed any user conversions, the
4873   // reference binding fails. This case is important for breaking
4874   // recursion, since TryImplicitConversion below will attempt to
4875   // create a temporary through the use of a copy constructor.
4876   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4877       (T1->isRecordType() || T2->isRecordType()))
4878     return ICS;
4879 
4880   // If T1 is reference-related to T2 and the reference is an rvalue
4881   // reference, the initializer expression shall not be an lvalue.
4882   if (RefRelationship >= Sema::Ref_Related &&
4883       isRValRef && Init->Classify(S.Context).isLValue())
4884     return ICS;
4885 
4886   // C++ [over.ics.ref]p2:
4887   //   When a parameter of reference type is not bound directly to
4888   //   an argument expression, the conversion sequence is the one
4889   //   required to convert the argument expression to the
4890   //   underlying type of the reference according to
4891   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4892   //   to copy-initializing a temporary of the underlying type with
4893   //   the argument expression. Any difference in top-level
4894   //   cv-qualification is subsumed by the initialization itself
4895   //   and does not constitute a conversion.
4896   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4897                               AllowedExplicit::None,
4898                               /*InOverloadResolution=*/false,
4899                               /*CStyle=*/false,
4900                               /*AllowObjCWritebackConversion=*/false,
4901                               /*AllowObjCConversionOnExplicit=*/false);
4902 
4903   // Of course, that's still a reference binding.
4904   if (ICS.isStandard()) {
4905     ICS.Standard.ReferenceBinding = true;
4906     ICS.Standard.IsLvalueReference = !isRValRef;
4907     ICS.Standard.BindsToFunctionLvalue = false;
4908     ICS.Standard.BindsToRvalue = true;
4909     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4910     ICS.Standard.ObjCLifetimeConversionBinding = false;
4911   } else if (ICS.isUserDefined()) {
4912     const ReferenceType *LValRefType =
4913         ICS.UserDefined.ConversionFunction->getReturnType()
4914             ->getAs<LValueReferenceType>();
4915 
4916     // C++ [over.ics.ref]p3:
4917     //   Except for an implicit object parameter, for which see 13.3.1, a
4918     //   standard conversion sequence cannot be formed if it requires [...]
4919     //   binding an rvalue reference to an lvalue other than a function
4920     //   lvalue.
4921     // Note that the function case is not possible here.
4922     if (DeclType->isRValueReferenceType() && LValRefType) {
4923       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4924       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4925       // reference to an rvalue!
4926       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4927       return ICS;
4928     }
4929 
4930     ICS.UserDefined.After.ReferenceBinding = true;
4931     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4932     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4933     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4934     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4935     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4936   }
4937 
4938   return ICS;
4939 }
4940 
4941 static ImplicitConversionSequence
4942 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4943                       bool SuppressUserConversions,
4944                       bool InOverloadResolution,
4945                       bool AllowObjCWritebackConversion,
4946                       bool AllowExplicit = false);
4947 
4948 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4949 /// initializer list From.
4950 static ImplicitConversionSequence
4951 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4952                   bool SuppressUserConversions,
4953                   bool InOverloadResolution,
4954                   bool AllowObjCWritebackConversion) {
4955   // C++11 [over.ics.list]p1:
4956   //   When an argument is an initializer list, it is not an expression and
4957   //   special rules apply for converting it to a parameter type.
4958 
4959   ImplicitConversionSequence Result;
4960   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4961 
4962   // We need a complete type for what follows. Incomplete types can never be
4963   // initialized from init lists.
4964   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4965     return Result;
4966 
4967   // Per DR1467:
4968   //   If the parameter type is a class X and the initializer list has a single
4969   //   element of type cv U, where U is X or a class derived from X, the
4970   //   implicit conversion sequence is the one required to convert the element
4971   //   to the parameter type.
4972   //
4973   //   Otherwise, if the parameter type is a character array [... ]
4974   //   and the initializer list has a single element that is an
4975   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4976   //   implicit conversion sequence is the identity conversion.
4977   if (From->getNumInits() == 1) {
4978     if (ToType->isRecordType()) {
4979       QualType InitType = From->getInit(0)->getType();
4980       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4981           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4982         return TryCopyInitialization(S, From->getInit(0), ToType,
4983                                      SuppressUserConversions,
4984                                      InOverloadResolution,
4985                                      AllowObjCWritebackConversion);
4986     }
4987 
4988     if (const auto *AT = S.Context.getAsArrayType(ToType)) {
4989       if (S.IsStringInit(From->getInit(0), AT)) {
4990         InitializedEntity Entity =
4991           InitializedEntity::InitializeParameter(S.Context, ToType,
4992                                                  /*Consumed=*/false);
4993         if (S.CanPerformCopyInitialization(Entity, From)) {
4994           Result.setStandard();
4995           Result.Standard.setAsIdentityConversion();
4996           Result.Standard.setFromType(ToType);
4997           Result.Standard.setAllToTypes(ToType);
4998           return Result;
4999         }
5000       }
5001     }
5002   }
5003 
5004   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5005   // C++11 [over.ics.list]p2:
5006   //   If the parameter type is std::initializer_list<X> or "array of X" and
5007   //   all the elements can be implicitly converted to X, the implicit
5008   //   conversion sequence is the worst conversion necessary to convert an
5009   //   element of the list to X.
5010   //
5011   // C++14 [over.ics.list]p3:
5012   //   Otherwise, if the parameter type is "array of N X", if the initializer
5013   //   list has exactly N elements or if it has fewer than N elements and X is
5014   //   default-constructible, and if all the elements of the initializer list
5015   //   can be implicitly converted to X, the implicit conversion sequence is
5016   //   the worst conversion necessary to convert an element of the list to X.
5017   //
5018   // FIXME: We're missing a lot of these checks.
5019   bool toStdInitializerList = false;
5020   QualType X;
5021   if (ToType->isArrayType())
5022     X = S.Context.getAsArrayType(ToType)->getElementType();
5023   else
5024     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5025   if (!X.isNull()) {
5026     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5027       Expr *Init = From->getInit(i);
5028       ImplicitConversionSequence ICS =
5029           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5030                                 InOverloadResolution,
5031                                 AllowObjCWritebackConversion);
5032       // If a single element isn't convertible, fail.
5033       if (ICS.isBad()) {
5034         Result = ICS;
5035         break;
5036       }
5037       // Otherwise, look for the worst conversion.
5038       if (Result.isBad() || CompareImplicitConversionSequences(
5039                                 S, From->getBeginLoc(), ICS, Result) ==
5040                                 ImplicitConversionSequence::Worse)
5041         Result = ICS;
5042     }
5043 
5044     // For an empty list, we won't have computed any conversion sequence.
5045     // Introduce the identity conversion sequence.
5046     if (From->getNumInits() == 0) {
5047       Result.setStandard();
5048       Result.Standard.setAsIdentityConversion();
5049       Result.Standard.setFromType(ToType);
5050       Result.Standard.setAllToTypes(ToType);
5051     }
5052 
5053     Result.setStdInitializerListElement(toStdInitializerList);
5054     return Result;
5055   }
5056 
5057   // C++14 [over.ics.list]p4:
5058   // C++11 [over.ics.list]p3:
5059   //   Otherwise, if the parameter is a non-aggregate class X and overload
5060   //   resolution chooses a single best constructor [...] the implicit
5061   //   conversion sequence is a user-defined conversion sequence. If multiple
5062   //   constructors are viable but none is better than the others, the
5063   //   implicit conversion sequence is a user-defined conversion sequence.
5064   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5065     // This function can deal with initializer lists.
5066     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5067                                     AllowedExplicit::None,
5068                                     InOverloadResolution, /*CStyle=*/false,
5069                                     AllowObjCWritebackConversion,
5070                                     /*AllowObjCConversionOnExplicit=*/false);
5071   }
5072 
5073   // C++14 [over.ics.list]p5:
5074   // C++11 [over.ics.list]p4:
5075   //   Otherwise, if the parameter has an aggregate type which can be
5076   //   initialized from the initializer list [...] the implicit conversion
5077   //   sequence is a user-defined conversion sequence.
5078   if (ToType->isAggregateType()) {
5079     // Type is an aggregate, argument is an init list. At this point it comes
5080     // down to checking whether the initialization works.
5081     // FIXME: Find out whether this parameter is consumed or not.
5082     InitializedEntity Entity =
5083         InitializedEntity::InitializeParameter(S.Context, ToType,
5084                                                /*Consumed=*/false);
5085     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5086                                                                  From)) {
5087       Result.setUserDefined();
5088       Result.UserDefined.Before.setAsIdentityConversion();
5089       // Initializer lists don't have a type.
5090       Result.UserDefined.Before.setFromType(QualType());
5091       Result.UserDefined.Before.setAllToTypes(QualType());
5092 
5093       Result.UserDefined.After.setAsIdentityConversion();
5094       Result.UserDefined.After.setFromType(ToType);
5095       Result.UserDefined.After.setAllToTypes(ToType);
5096       Result.UserDefined.ConversionFunction = nullptr;
5097     }
5098     return Result;
5099   }
5100 
5101   // C++14 [over.ics.list]p6:
5102   // C++11 [over.ics.list]p5:
5103   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5104   if (ToType->isReferenceType()) {
5105     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5106     // mention initializer lists in any way. So we go by what list-
5107     // initialization would do and try to extrapolate from that.
5108 
5109     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5110 
5111     // If the initializer list has a single element that is reference-related
5112     // to the parameter type, we initialize the reference from that.
5113     if (From->getNumInits() == 1) {
5114       Expr *Init = From->getInit(0);
5115 
5116       QualType T2 = Init->getType();
5117 
5118       // If the initializer is the address of an overloaded function, try
5119       // to resolve the overloaded function. If all goes well, T2 is the
5120       // type of the resulting function.
5121       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5122         DeclAccessPair Found;
5123         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5124                                    Init, ToType, false, Found))
5125           T2 = Fn->getType();
5126       }
5127 
5128       // Compute some basic properties of the types and the initializer.
5129       Sema::ReferenceCompareResult RefRelationship =
5130           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5131 
5132       if (RefRelationship >= Sema::Ref_Related) {
5133         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5134                                 SuppressUserConversions,
5135                                 /*AllowExplicit=*/false);
5136       }
5137     }
5138 
5139     // Otherwise, we bind the reference to a temporary created from the
5140     // initializer list.
5141     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5142                                InOverloadResolution,
5143                                AllowObjCWritebackConversion);
5144     if (Result.isFailure())
5145       return Result;
5146     assert(!Result.isEllipsis() &&
5147            "Sub-initialization cannot result in ellipsis conversion.");
5148 
5149     // Can we even bind to a temporary?
5150     if (ToType->isRValueReferenceType() ||
5151         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5152       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5153                                             Result.UserDefined.After;
5154       SCS.ReferenceBinding = true;
5155       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5156       SCS.BindsToRvalue = true;
5157       SCS.BindsToFunctionLvalue = false;
5158       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5159       SCS.ObjCLifetimeConversionBinding = false;
5160     } else
5161       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5162                     From, ToType);
5163     return Result;
5164   }
5165 
5166   // C++14 [over.ics.list]p7:
5167   // C++11 [over.ics.list]p6:
5168   //   Otherwise, if the parameter type is not a class:
5169   if (!ToType->isRecordType()) {
5170     //    - if the initializer list has one element that is not itself an
5171     //      initializer list, the implicit conversion sequence is the one
5172     //      required to convert the element to the parameter type.
5173     unsigned NumInits = From->getNumInits();
5174     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5175       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5176                                      SuppressUserConversions,
5177                                      InOverloadResolution,
5178                                      AllowObjCWritebackConversion);
5179     //    - if the initializer list has no elements, the implicit conversion
5180     //      sequence is the identity conversion.
5181     else if (NumInits == 0) {
5182       Result.setStandard();
5183       Result.Standard.setAsIdentityConversion();
5184       Result.Standard.setFromType(ToType);
5185       Result.Standard.setAllToTypes(ToType);
5186     }
5187     return Result;
5188   }
5189 
5190   // C++14 [over.ics.list]p8:
5191   // C++11 [over.ics.list]p7:
5192   //   In all cases other than those enumerated above, no conversion is possible
5193   return Result;
5194 }
5195 
5196 /// TryCopyInitialization - Try to copy-initialize a value of type
5197 /// ToType from the expression From. Return the implicit conversion
5198 /// sequence required to pass this argument, which may be a bad
5199 /// conversion sequence (meaning that the argument cannot be passed to
5200 /// a parameter of this type). If @p SuppressUserConversions, then we
5201 /// do not permit any user-defined conversion sequences.
5202 static ImplicitConversionSequence
5203 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5204                       bool SuppressUserConversions,
5205                       bool InOverloadResolution,
5206                       bool AllowObjCWritebackConversion,
5207                       bool AllowExplicit) {
5208   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5209     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5210                              InOverloadResolution,AllowObjCWritebackConversion);
5211 
5212   if (ToType->isReferenceType())
5213     return TryReferenceInit(S, From, ToType,
5214                             /*FIXME:*/ From->getBeginLoc(),
5215                             SuppressUserConversions, AllowExplicit);
5216 
5217   return TryImplicitConversion(S, From, ToType,
5218                                SuppressUserConversions,
5219                                AllowedExplicit::None,
5220                                InOverloadResolution,
5221                                /*CStyle=*/false,
5222                                AllowObjCWritebackConversion,
5223                                /*AllowObjCConversionOnExplicit=*/false);
5224 }
5225 
5226 static bool TryCopyInitialization(const CanQualType FromQTy,
5227                                   const CanQualType ToQTy,
5228                                   Sema &S,
5229                                   SourceLocation Loc,
5230                                   ExprValueKind FromVK) {
5231   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5232   ImplicitConversionSequence ICS =
5233     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5234 
5235   return !ICS.isBad();
5236 }
5237 
5238 /// TryObjectArgumentInitialization - Try to initialize the object
5239 /// parameter of the given member function (@c Method) from the
5240 /// expression @p From.
5241 static ImplicitConversionSequence
5242 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5243                                 Expr::Classification FromClassification,
5244                                 CXXMethodDecl *Method,
5245                                 CXXRecordDecl *ActingContext) {
5246   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5247   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5248   //                 const volatile object.
5249   Qualifiers Quals = Method->getMethodQualifiers();
5250   if (isa<CXXDestructorDecl>(Method)) {
5251     Quals.addConst();
5252     Quals.addVolatile();
5253   }
5254 
5255   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5256 
5257   // Set up the conversion sequence as a "bad" conversion, to allow us
5258   // to exit early.
5259   ImplicitConversionSequence ICS;
5260 
5261   // We need to have an object of class type.
5262   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5263     FromType = PT->getPointeeType();
5264 
5265     // When we had a pointer, it's implicitly dereferenced, so we
5266     // better have an lvalue.
5267     assert(FromClassification.isLValue());
5268   }
5269 
5270   assert(FromType->isRecordType());
5271 
5272   // C++0x [over.match.funcs]p4:
5273   //   For non-static member functions, the type of the implicit object
5274   //   parameter is
5275   //
5276   //     - "lvalue reference to cv X" for functions declared without a
5277   //        ref-qualifier or with the & ref-qualifier
5278   //     - "rvalue reference to cv X" for functions declared with the &&
5279   //        ref-qualifier
5280   //
5281   // where X is the class of which the function is a member and cv is the
5282   // cv-qualification on the member function declaration.
5283   //
5284   // However, when finding an implicit conversion sequence for the argument, we
5285   // are not allowed to perform user-defined conversions
5286   // (C++ [over.match.funcs]p5). We perform a simplified version of
5287   // reference binding here, that allows class rvalues to bind to
5288   // non-constant references.
5289 
5290   // First check the qualifiers.
5291   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5292   if (ImplicitParamType.getCVRQualifiers()
5293                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5294       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5295     ICS.setBad(BadConversionSequence::bad_qualifiers,
5296                FromType, ImplicitParamType);
5297     return ICS;
5298   }
5299 
5300   if (FromTypeCanon.hasAddressSpace()) {
5301     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5302     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5303     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5304       ICS.setBad(BadConversionSequence::bad_qualifiers,
5305                  FromType, ImplicitParamType);
5306       return ICS;
5307     }
5308   }
5309 
5310   // Check that we have either the same type or a derived type. It
5311   // affects the conversion rank.
5312   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5313   ImplicitConversionKind SecondKind;
5314   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5315     SecondKind = ICK_Identity;
5316   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5317     SecondKind = ICK_Derived_To_Base;
5318   else {
5319     ICS.setBad(BadConversionSequence::unrelated_class,
5320                FromType, ImplicitParamType);
5321     return ICS;
5322   }
5323 
5324   // Check the ref-qualifier.
5325   switch (Method->getRefQualifier()) {
5326   case RQ_None:
5327     // Do nothing; we don't care about lvalueness or rvalueness.
5328     break;
5329 
5330   case RQ_LValue:
5331     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5332       // non-const lvalue reference cannot bind to an rvalue
5333       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5334                  ImplicitParamType);
5335       return ICS;
5336     }
5337     break;
5338 
5339   case RQ_RValue:
5340     if (!FromClassification.isRValue()) {
5341       // rvalue reference cannot bind to an lvalue
5342       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5343                  ImplicitParamType);
5344       return ICS;
5345     }
5346     break;
5347   }
5348 
5349   // Success. Mark this as a reference binding.
5350   ICS.setStandard();
5351   ICS.Standard.setAsIdentityConversion();
5352   ICS.Standard.Second = SecondKind;
5353   ICS.Standard.setFromType(FromType);
5354   ICS.Standard.setAllToTypes(ImplicitParamType);
5355   ICS.Standard.ReferenceBinding = true;
5356   ICS.Standard.DirectBinding = true;
5357   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5358   ICS.Standard.BindsToFunctionLvalue = false;
5359   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5360   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5361     = (Method->getRefQualifier() == RQ_None);
5362   return ICS;
5363 }
5364 
5365 /// PerformObjectArgumentInitialization - Perform initialization of
5366 /// the implicit object parameter for the given Method with the given
5367 /// expression.
5368 ExprResult
5369 Sema::PerformObjectArgumentInitialization(Expr *From,
5370                                           NestedNameSpecifier *Qualifier,
5371                                           NamedDecl *FoundDecl,
5372                                           CXXMethodDecl *Method) {
5373   QualType FromRecordType, DestType;
5374   QualType ImplicitParamRecordType  =
5375     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5376 
5377   Expr::Classification FromClassification;
5378   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5379     FromRecordType = PT->getPointeeType();
5380     DestType = Method->getThisType();
5381     FromClassification = Expr::Classification::makeSimpleLValue();
5382   } else {
5383     FromRecordType = From->getType();
5384     DestType = ImplicitParamRecordType;
5385     FromClassification = From->Classify(Context);
5386 
5387     // When performing member access on an rvalue, materialize a temporary.
5388     if (From->isRValue()) {
5389       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5390                                             Method->getRefQualifier() !=
5391                                                 RefQualifierKind::RQ_RValue);
5392     }
5393   }
5394 
5395   // Note that we always use the true parent context when performing
5396   // the actual argument initialization.
5397   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5398       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5399       Method->getParent());
5400   if (ICS.isBad()) {
5401     switch (ICS.Bad.Kind) {
5402     case BadConversionSequence::bad_qualifiers: {
5403       Qualifiers FromQs = FromRecordType.getQualifiers();
5404       Qualifiers ToQs = DestType.getQualifiers();
5405       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5406       if (CVR) {
5407         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5408             << Method->getDeclName() << FromRecordType << (CVR - 1)
5409             << From->getSourceRange();
5410         Diag(Method->getLocation(), diag::note_previous_decl)
5411           << Method->getDeclName();
5412         return ExprError();
5413       }
5414       break;
5415     }
5416 
5417     case BadConversionSequence::lvalue_ref_to_rvalue:
5418     case BadConversionSequence::rvalue_ref_to_lvalue: {
5419       bool IsRValueQualified =
5420         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5421       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5422           << Method->getDeclName() << FromClassification.isRValue()
5423           << IsRValueQualified;
5424       Diag(Method->getLocation(), diag::note_previous_decl)
5425         << Method->getDeclName();
5426       return ExprError();
5427     }
5428 
5429     case BadConversionSequence::no_conversion:
5430     case BadConversionSequence::unrelated_class:
5431       break;
5432     }
5433 
5434     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5435            << ImplicitParamRecordType << FromRecordType
5436            << From->getSourceRange();
5437   }
5438 
5439   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5440     ExprResult FromRes =
5441       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5442     if (FromRes.isInvalid())
5443       return ExprError();
5444     From = FromRes.get();
5445   }
5446 
5447   if (!Context.hasSameType(From->getType(), DestType)) {
5448     CastKind CK;
5449     QualType PteeTy = DestType->getPointeeType();
5450     LangAS DestAS =
5451         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5452     if (FromRecordType.getAddressSpace() != DestAS)
5453       CK = CK_AddressSpaceConversion;
5454     else
5455       CK = CK_NoOp;
5456     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5457   }
5458   return From;
5459 }
5460 
5461 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5462 /// expression From to bool (C++0x [conv]p3).
5463 static ImplicitConversionSequence
5464 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5465   // C++ [dcl.init]/17.8:
5466   //   - Otherwise, if the initialization is direct-initialization, the source
5467   //     type is std::nullptr_t, and the destination type is bool, the initial
5468   //     value of the object being initialized is false.
5469   if (From->getType()->isNullPtrType())
5470     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5471                                                         S.Context.BoolTy,
5472                                                         From->isGLValue());
5473 
5474   // All other direct-initialization of bool is equivalent to an implicit
5475   // conversion to bool in which explicit conversions are permitted.
5476   return TryImplicitConversion(S, From, S.Context.BoolTy,
5477                                /*SuppressUserConversions=*/false,
5478                                AllowedExplicit::Conversions,
5479                                /*InOverloadResolution=*/false,
5480                                /*CStyle=*/false,
5481                                /*AllowObjCWritebackConversion=*/false,
5482                                /*AllowObjCConversionOnExplicit=*/false);
5483 }
5484 
5485 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5486 /// of the expression From to bool (C++0x [conv]p3).
5487 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5488   if (checkPlaceholderForOverload(*this, From))
5489     return ExprError();
5490 
5491   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5492   if (!ICS.isBad())
5493     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5494 
5495   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5496     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5497            << From->getType() << From->getSourceRange();
5498   return ExprError();
5499 }
5500 
5501 /// Check that the specified conversion is permitted in a converted constant
5502 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5503 /// is acceptable.
5504 static bool CheckConvertedConstantConversions(Sema &S,
5505                                               StandardConversionSequence &SCS) {
5506   // Since we know that the target type is an integral or unscoped enumeration
5507   // type, most conversion kinds are impossible. All possible First and Third
5508   // conversions are fine.
5509   switch (SCS.Second) {
5510   case ICK_Identity:
5511   case ICK_Integral_Promotion:
5512   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5513   case ICK_Zero_Queue_Conversion:
5514     return true;
5515 
5516   case ICK_Boolean_Conversion:
5517     // Conversion from an integral or unscoped enumeration type to bool is
5518     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5519     // conversion, so we allow it in a converted constant expression.
5520     //
5521     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5522     // a lot of popular code. We should at least add a warning for this
5523     // (non-conforming) extension.
5524     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5525            SCS.getToType(2)->isBooleanType();
5526 
5527   case ICK_Pointer_Conversion:
5528   case ICK_Pointer_Member:
5529     // C++1z: null pointer conversions and null member pointer conversions are
5530     // only permitted if the source type is std::nullptr_t.
5531     return SCS.getFromType()->isNullPtrType();
5532 
5533   case ICK_Floating_Promotion:
5534   case ICK_Complex_Promotion:
5535   case ICK_Floating_Conversion:
5536   case ICK_Complex_Conversion:
5537   case ICK_Floating_Integral:
5538   case ICK_Compatible_Conversion:
5539   case ICK_Derived_To_Base:
5540   case ICK_Vector_Conversion:
5541   case ICK_SVE_Vector_Conversion:
5542   case ICK_Vector_Splat:
5543   case ICK_Complex_Real:
5544   case ICK_Block_Pointer_Conversion:
5545   case ICK_TransparentUnionConversion:
5546   case ICK_Writeback_Conversion:
5547   case ICK_Zero_Event_Conversion:
5548   case ICK_C_Only_Conversion:
5549   case ICK_Incompatible_Pointer_Conversion:
5550     return false;
5551 
5552   case ICK_Lvalue_To_Rvalue:
5553   case ICK_Array_To_Pointer:
5554   case ICK_Function_To_Pointer:
5555     llvm_unreachable("found a first conversion kind in Second");
5556 
5557   case ICK_Function_Conversion:
5558   case ICK_Qualification:
5559     llvm_unreachable("found a third conversion kind in Second");
5560 
5561   case ICK_Num_Conversion_Kinds:
5562     break;
5563   }
5564 
5565   llvm_unreachable("unknown conversion kind");
5566 }
5567 
5568 /// CheckConvertedConstantExpression - Check that the expression From is a
5569 /// converted constant expression of type T, perform the conversion and produce
5570 /// the converted expression, per C++11 [expr.const]p3.
5571 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5572                                                    QualType T, APValue &Value,
5573                                                    Sema::CCEKind CCE,
5574                                                    bool RequireInt,
5575                                                    NamedDecl *Dest) {
5576   assert(S.getLangOpts().CPlusPlus11 &&
5577          "converted constant expression outside C++11");
5578 
5579   if (checkPlaceholderForOverload(S, From))
5580     return ExprError();
5581 
5582   // C++1z [expr.const]p3:
5583   //  A converted constant expression of type T is an expression,
5584   //  implicitly converted to type T, where the converted
5585   //  expression is a constant expression and the implicit conversion
5586   //  sequence contains only [... list of conversions ...].
5587   // C++1z [stmt.if]p2:
5588   //  If the if statement is of the form if constexpr, the value of the
5589   //  condition shall be a contextually converted constant expression of type
5590   //  bool.
5591   ImplicitConversionSequence ICS =
5592       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5593           ? TryContextuallyConvertToBool(S, From)
5594           : TryCopyInitialization(S, From, T,
5595                                   /*SuppressUserConversions=*/false,
5596                                   /*InOverloadResolution=*/false,
5597                                   /*AllowObjCWritebackConversion=*/false,
5598                                   /*AllowExplicit=*/false);
5599   StandardConversionSequence *SCS = nullptr;
5600   switch (ICS.getKind()) {
5601   case ImplicitConversionSequence::StandardConversion:
5602     SCS = &ICS.Standard;
5603     break;
5604   case ImplicitConversionSequence::UserDefinedConversion:
5605     if (T->isRecordType())
5606       SCS = &ICS.UserDefined.Before;
5607     else
5608       SCS = &ICS.UserDefined.After;
5609     break;
5610   case ImplicitConversionSequence::AmbiguousConversion:
5611   case ImplicitConversionSequence::BadConversion:
5612     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5613       return S.Diag(From->getBeginLoc(),
5614                     diag::err_typecheck_converted_constant_expression)
5615              << From->getType() << From->getSourceRange() << T;
5616     return ExprError();
5617 
5618   case ImplicitConversionSequence::EllipsisConversion:
5619     llvm_unreachable("ellipsis conversion in converted constant expression");
5620   }
5621 
5622   // Check that we would only use permitted conversions.
5623   if (!CheckConvertedConstantConversions(S, *SCS)) {
5624     return S.Diag(From->getBeginLoc(),
5625                   diag::err_typecheck_converted_constant_expression_disallowed)
5626            << From->getType() << From->getSourceRange() << T;
5627   }
5628   // [...] and where the reference binding (if any) binds directly.
5629   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5630     return S.Diag(From->getBeginLoc(),
5631                   diag::err_typecheck_converted_constant_expression_indirect)
5632            << From->getType() << From->getSourceRange() << T;
5633   }
5634 
5635   // Usually we can simply apply the ImplicitConversionSequence we formed
5636   // earlier, but that's not guaranteed to work when initializing an object of
5637   // class type.
5638   ExprResult Result;
5639   if (T->isRecordType()) {
5640     assert(CCE == Sema::CCEK_TemplateArg &&
5641            "unexpected class type converted constant expr");
5642     Result = S.PerformCopyInitialization(
5643         InitializedEntity::InitializeTemplateParameter(
5644             T, cast<NonTypeTemplateParmDecl>(Dest)),
5645         SourceLocation(), From);
5646   } else {
5647     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5648   }
5649   if (Result.isInvalid())
5650     return Result;
5651 
5652   // C++2a [intro.execution]p5:
5653   //   A full-expression is [...] a constant-expression [...]
5654   Result =
5655       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5656                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5657   if (Result.isInvalid())
5658     return Result;
5659 
5660   // Check for a narrowing implicit conversion.
5661   bool ReturnPreNarrowingValue = false;
5662   APValue PreNarrowingValue;
5663   QualType PreNarrowingType;
5664   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5665                                 PreNarrowingType)) {
5666   case NK_Dependent_Narrowing:
5667     // Implicit conversion to a narrower type, but the expression is
5668     // value-dependent so we can't tell whether it's actually narrowing.
5669   case NK_Variable_Narrowing:
5670     // Implicit conversion to a narrower type, and the value is not a constant
5671     // expression. We'll diagnose this in a moment.
5672   case NK_Not_Narrowing:
5673     break;
5674 
5675   case NK_Constant_Narrowing:
5676     if (CCE == Sema::CCEK_ArrayBound &&
5677         PreNarrowingType->isIntegralOrEnumerationType() &&
5678         PreNarrowingValue.isInt()) {
5679       // Don't diagnose array bound narrowing here; we produce more precise
5680       // errors by allowing the un-narrowed value through.
5681       ReturnPreNarrowingValue = true;
5682       break;
5683     }
5684     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5685         << CCE << /*Constant*/ 1
5686         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5687     break;
5688 
5689   case NK_Type_Narrowing:
5690     // FIXME: It would be better to diagnose that the expression is not a
5691     // constant expression.
5692     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5693         << CCE << /*Constant*/ 0 << From->getType() << T;
5694     break;
5695   }
5696 
5697   if (Result.get()->isValueDependent()) {
5698     Value = APValue();
5699     return Result;
5700   }
5701 
5702   // Check the expression is a constant expression.
5703   SmallVector<PartialDiagnosticAt, 8> Notes;
5704   Expr::EvalResult Eval;
5705   Eval.Diag = &Notes;
5706 
5707   ConstantExprKind Kind;
5708   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5709     Kind = ConstantExprKind::ClassTemplateArgument;
5710   else if (CCE == Sema::CCEK_TemplateArg)
5711     Kind = ConstantExprKind::NonClassTemplateArgument;
5712   else
5713     Kind = ConstantExprKind::Normal;
5714 
5715   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5716       (RequireInt && !Eval.Val.isInt())) {
5717     // The expression can't be folded, so we can't keep it at this position in
5718     // the AST.
5719     Result = ExprError();
5720   } else {
5721     Value = Eval.Val;
5722 
5723     if (Notes.empty()) {
5724       // It's a constant expression.
5725       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5726       if (ReturnPreNarrowingValue)
5727         Value = std::move(PreNarrowingValue);
5728       return E;
5729     }
5730   }
5731 
5732   // It's not a constant expression. Produce an appropriate diagnostic.
5733   if (Notes.size() == 1 &&
5734       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5735     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5736   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5737                                    diag::note_constexpr_invalid_template_arg) {
5738     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5739     for (unsigned I = 0; I < Notes.size(); ++I)
5740       S.Diag(Notes[I].first, Notes[I].second);
5741   } else {
5742     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5743         << CCE << From->getSourceRange();
5744     for (unsigned I = 0; I < Notes.size(); ++I)
5745       S.Diag(Notes[I].first, Notes[I].second);
5746   }
5747   return ExprError();
5748 }
5749 
5750 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5751                                                   APValue &Value, CCEKind CCE,
5752                                                   NamedDecl *Dest) {
5753   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5754                                             Dest);
5755 }
5756 
5757 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5758                                                   llvm::APSInt &Value,
5759                                                   CCEKind CCE) {
5760   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5761 
5762   APValue V;
5763   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5764                                               /*Dest=*/nullptr);
5765   if (!R.isInvalid() && !R.get()->isValueDependent())
5766     Value = V.getInt();
5767   return R;
5768 }
5769 
5770 
5771 /// dropPointerConversions - If the given standard conversion sequence
5772 /// involves any pointer conversions, remove them.  This may change
5773 /// the result type of the conversion sequence.
5774 static void dropPointerConversion(StandardConversionSequence &SCS) {
5775   if (SCS.Second == ICK_Pointer_Conversion) {
5776     SCS.Second = ICK_Identity;
5777     SCS.Third = ICK_Identity;
5778     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5779   }
5780 }
5781 
5782 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5783 /// convert the expression From to an Objective-C pointer type.
5784 static ImplicitConversionSequence
5785 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5786   // Do an implicit conversion to 'id'.
5787   QualType Ty = S.Context.getObjCIdType();
5788   ImplicitConversionSequence ICS
5789     = TryImplicitConversion(S, From, Ty,
5790                             // FIXME: Are these flags correct?
5791                             /*SuppressUserConversions=*/false,
5792                             AllowedExplicit::Conversions,
5793                             /*InOverloadResolution=*/false,
5794                             /*CStyle=*/false,
5795                             /*AllowObjCWritebackConversion=*/false,
5796                             /*AllowObjCConversionOnExplicit=*/true);
5797 
5798   // Strip off any final conversions to 'id'.
5799   switch (ICS.getKind()) {
5800   case ImplicitConversionSequence::BadConversion:
5801   case ImplicitConversionSequence::AmbiguousConversion:
5802   case ImplicitConversionSequence::EllipsisConversion:
5803     break;
5804 
5805   case ImplicitConversionSequence::UserDefinedConversion:
5806     dropPointerConversion(ICS.UserDefined.After);
5807     break;
5808 
5809   case ImplicitConversionSequence::StandardConversion:
5810     dropPointerConversion(ICS.Standard);
5811     break;
5812   }
5813 
5814   return ICS;
5815 }
5816 
5817 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5818 /// conversion of the expression From to an Objective-C pointer type.
5819 /// Returns a valid but null ExprResult if no conversion sequence exists.
5820 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5821   if (checkPlaceholderForOverload(*this, From))
5822     return ExprError();
5823 
5824   QualType Ty = Context.getObjCIdType();
5825   ImplicitConversionSequence ICS =
5826     TryContextuallyConvertToObjCPointer(*this, From);
5827   if (!ICS.isBad())
5828     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5829   return ExprResult();
5830 }
5831 
5832 /// Determine whether the provided type is an integral type, or an enumeration
5833 /// type of a permitted flavor.
5834 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5835   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5836                                  : T->isIntegralOrUnscopedEnumerationType();
5837 }
5838 
5839 static ExprResult
5840 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5841                             Sema::ContextualImplicitConverter &Converter,
5842                             QualType T, UnresolvedSetImpl &ViableConversions) {
5843 
5844   if (Converter.Suppress)
5845     return ExprError();
5846 
5847   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5848   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5849     CXXConversionDecl *Conv =
5850         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5851     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5852     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5853   }
5854   return From;
5855 }
5856 
5857 static bool
5858 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5859                            Sema::ContextualImplicitConverter &Converter,
5860                            QualType T, bool HadMultipleCandidates,
5861                            UnresolvedSetImpl &ExplicitConversions) {
5862   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5863     DeclAccessPair Found = ExplicitConversions[0];
5864     CXXConversionDecl *Conversion =
5865         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5866 
5867     // The user probably meant to invoke the given explicit
5868     // conversion; use it.
5869     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5870     std::string TypeStr;
5871     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5872 
5873     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5874         << FixItHint::CreateInsertion(From->getBeginLoc(),
5875                                       "static_cast<" + TypeStr + ">(")
5876         << FixItHint::CreateInsertion(
5877                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5878     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5879 
5880     // If we aren't in a SFINAE context, build a call to the
5881     // explicit conversion function.
5882     if (SemaRef.isSFINAEContext())
5883       return true;
5884 
5885     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5886     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5887                                                        HadMultipleCandidates);
5888     if (Result.isInvalid())
5889       return true;
5890     // Record usage of conversion in an implicit cast.
5891     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5892                                     CK_UserDefinedConversion, Result.get(),
5893                                     nullptr, Result.get()->getValueKind(),
5894                                     SemaRef.CurFPFeatureOverrides());
5895   }
5896   return false;
5897 }
5898 
5899 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5900                              Sema::ContextualImplicitConverter &Converter,
5901                              QualType T, bool HadMultipleCandidates,
5902                              DeclAccessPair &Found) {
5903   CXXConversionDecl *Conversion =
5904       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5905   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5906 
5907   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5908   if (!Converter.SuppressConversion) {
5909     if (SemaRef.isSFINAEContext())
5910       return true;
5911 
5912     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5913         << From->getSourceRange();
5914   }
5915 
5916   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5917                                                      HadMultipleCandidates);
5918   if (Result.isInvalid())
5919     return true;
5920   // Record usage of conversion in an implicit cast.
5921   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5922                                   CK_UserDefinedConversion, Result.get(),
5923                                   nullptr, Result.get()->getValueKind(),
5924                                   SemaRef.CurFPFeatureOverrides());
5925   return false;
5926 }
5927 
5928 static ExprResult finishContextualImplicitConversion(
5929     Sema &SemaRef, SourceLocation Loc, Expr *From,
5930     Sema::ContextualImplicitConverter &Converter) {
5931   if (!Converter.match(From->getType()) && !Converter.Suppress)
5932     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5933         << From->getSourceRange();
5934 
5935   return SemaRef.DefaultLvalueConversion(From);
5936 }
5937 
5938 static void
5939 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5940                                   UnresolvedSetImpl &ViableConversions,
5941                                   OverloadCandidateSet &CandidateSet) {
5942   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5943     DeclAccessPair FoundDecl = ViableConversions[I];
5944     NamedDecl *D = FoundDecl.getDecl();
5945     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5946     if (isa<UsingShadowDecl>(D))
5947       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5948 
5949     CXXConversionDecl *Conv;
5950     FunctionTemplateDecl *ConvTemplate;
5951     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5952       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5953     else
5954       Conv = cast<CXXConversionDecl>(D);
5955 
5956     if (ConvTemplate)
5957       SemaRef.AddTemplateConversionCandidate(
5958           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5959           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5960     else
5961       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5962                                      ToType, CandidateSet,
5963                                      /*AllowObjCConversionOnExplicit=*/false,
5964                                      /*AllowExplicit*/ true);
5965   }
5966 }
5967 
5968 /// Attempt to convert the given expression to a type which is accepted
5969 /// by the given converter.
5970 ///
5971 /// This routine will attempt to convert an expression of class type to a
5972 /// type accepted by the specified converter. In C++11 and before, the class
5973 /// must have a single non-explicit conversion function converting to a matching
5974 /// type. In C++1y, there can be multiple such conversion functions, but only
5975 /// one target type.
5976 ///
5977 /// \param Loc The source location of the construct that requires the
5978 /// conversion.
5979 ///
5980 /// \param From The expression we're converting from.
5981 ///
5982 /// \param Converter Used to control and diagnose the conversion process.
5983 ///
5984 /// \returns The expression, converted to an integral or enumeration type if
5985 /// successful.
5986 ExprResult Sema::PerformContextualImplicitConversion(
5987     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5988   // We can't perform any more checking for type-dependent expressions.
5989   if (From->isTypeDependent())
5990     return From;
5991 
5992   // Process placeholders immediately.
5993   if (From->hasPlaceholderType()) {
5994     ExprResult result = CheckPlaceholderExpr(From);
5995     if (result.isInvalid())
5996       return result;
5997     From = result.get();
5998   }
5999 
6000   // If the expression already has a matching type, we're golden.
6001   QualType T = From->getType();
6002   if (Converter.match(T))
6003     return DefaultLvalueConversion(From);
6004 
6005   // FIXME: Check for missing '()' if T is a function type?
6006 
6007   // We can only perform contextual implicit conversions on objects of class
6008   // type.
6009   const RecordType *RecordTy = T->getAs<RecordType>();
6010   if (!RecordTy || !getLangOpts().CPlusPlus) {
6011     if (!Converter.Suppress)
6012       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6013     return From;
6014   }
6015 
6016   // We must have a complete class type.
6017   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6018     ContextualImplicitConverter &Converter;
6019     Expr *From;
6020 
6021     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6022         : Converter(Converter), From(From) {}
6023 
6024     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6025       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6026     }
6027   } IncompleteDiagnoser(Converter, From);
6028 
6029   if (Converter.Suppress ? !isCompleteType(Loc, T)
6030                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6031     return From;
6032 
6033   // Look for a conversion to an integral or enumeration type.
6034   UnresolvedSet<4>
6035       ViableConversions; // These are *potentially* viable in C++1y.
6036   UnresolvedSet<4> ExplicitConversions;
6037   const auto &Conversions =
6038       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6039 
6040   bool HadMultipleCandidates =
6041       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6042 
6043   // To check that there is only one target type, in C++1y:
6044   QualType ToType;
6045   bool HasUniqueTargetType = true;
6046 
6047   // Collect explicit or viable (potentially in C++1y) conversions.
6048   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6049     NamedDecl *D = (*I)->getUnderlyingDecl();
6050     CXXConversionDecl *Conversion;
6051     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6052     if (ConvTemplate) {
6053       if (getLangOpts().CPlusPlus14)
6054         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6055       else
6056         continue; // C++11 does not consider conversion operator templates(?).
6057     } else
6058       Conversion = cast<CXXConversionDecl>(D);
6059 
6060     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6061            "Conversion operator templates are considered potentially "
6062            "viable in C++1y");
6063 
6064     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6065     if (Converter.match(CurToType) || ConvTemplate) {
6066 
6067       if (Conversion->isExplicit()) {
6068         // FIXME: For C++1y, do we need this restriction?
6069         // cf. diagnoseNoViableConversion()
6070         if (!ConvTemplate)
6071           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6072       } else {
6073         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6074           if (ToType.isNull())
6075             ToType = CurToType.getUnqualifiedType();
6076           else if (HasUniqueTargetType &&
6077                    (CurToType.getUnqualifiedType() != ToType))
6078             HasUniqueTargetType = false;
6079         }
6080         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6081       }
6082     }
6083   }
6084 
6085   if (getLangOpts().CPlusPlus14) {
6086     // C++1y [conv]p6:
6087     // ... An expression e of class type E appearing in such a context
6088     // is said to be contextually implicitly converted to a specified
6089     // type T and is well-formed if and only if e can be implicitly
6090     // converted to a type T that is determined as follows: E is searched
6091     // for conversion functions whose return type is cv T or reference to
6092     // cv T such that T is allowed by the context. There shall be
6093     // exactly one such T.
6094 
6095     // If no unique T is found:
6096     if (ToType.isNull()) {
6097       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6098                                      HadMultipleCandidates,
6099                                      ExplicitConversions))
6100         return ExprError();
6101       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6102     }
6103 
6104     // If more than one unique Ts are found:
6105     if (!HasUniqueTargetType)
6106       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6107                                          ViableConversions);
6108 
6109     // If one unique T is found:
6110     // First, build a candidate set from the previously recorded
6111     // potentially viable conversions.
6112     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6113     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6114                                       CandidateSet);
6115 
6116     // Then, perform overload resolution over the candidate set.
6117     OverloadCandidateSet::iterator Best;
6118     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6119     case OR_Success: {
6120       // Apply this conversion.
6121       DeclAccessPair Found =
6122           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6123       if (recordConversion(*this, Loc, From, Converter, T,
6124                            HadMultipleCandidates, Found))
6125         return ExprError();
6126       break;
6127     }
6128     case OR_Ambiguous:
6129       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6130                                          ViableConversions);
6131     case OR_No_Viable_Function:
6132       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6133                                      HadMultipleCandidates,
6134                                      ExplicitConversions))
6135         return ExprError();
6136       LLVM_FALLTHROUGH;
6137     case OR_Deleted:
6138       // We'll complain below about a non-integral condition type.
6139       break;
6140     }
6141   } else {
6142     switch (ViableConversions.size()) {
6143     case 0: {
6144       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6145                                      HadMultipleCandidates,
6146                                      ExplicitConversions))
6147         return ExprError();
6148 
6149       // We'll complain below about a non-integral condition type.
6150       break;
6151     }
6152     case 1: {
6153       // Apply this conversion.
6154       DeclAccessPair Found = ViableConversions[0];
6155       if (recordConversion(*this, Loc, From, Converter, T,
6156                            HadMultipleCandidates, Found))
6157         return ExprError();
6158       break;
6159     }
6160     default:
6161       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6162                                          ViableConversions);
6163     }
6164   }
6165 
6166   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6167 }
6168 
6169 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6170 /// an acceptable non-member overloaded operator for a call whose
6171 /// arguments have types T1 (and, if non-empty, T2). This routine
6172 /// implements the check in C++ [over.match.oper]p3b2 concerning
6173 /// enumeration types.
6174 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6175                                                    FunctionDecl *Fn,
6176                                                    ArrayRef<Expr *> Args) {
6177   QualType T1 = Args[0]->getType();
6178   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6179 
6180   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6181     return true;
6182 
6183   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6184     return true;
6185 
6186   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6187   if (Proto->getNumParams() < 1)
6188     return false;
6189 
6190   if (T1->isEnumeralType()) {
6191     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6192     if (Context.hasSameUnqualifiedType(T1, ArgType))
6193       return true;
6194   }
6195 
6196   if (Proto->getNumParams() < 2)
6197     return false;
6198 
6199   if (!T2.isNull() && T2->isEnumeralType()) {
6200     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6201     if (Context.hasSameUnqualifiedType(T2, ArgType))
6202       return true;
6203   }
6204 
6205   return false;
6206 }
6207 
6208 /// AddOverloadCandidate - Adds the given function to the set of
6209 /// candidate functions, using the given function call arguments.  If
6210 /// @p SuppressUserConversions, then don't allow user-defined
6211 /// conversions via constructors or conversion operators.
6212 ///
6213 /// \param PartialOverloading true if we are performing "partial" overloading
6214 /// based on an incomplete set of function arguments. This feature is used by
6215 /// code completion.
6216 void Sema::AddOverloadCandidate(
6217     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6218     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6219     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6220     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6221     OverloadCandidateParamOrder PO) {
6222   const FunctionProtoType *Proto
6223     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6224   assert(Proto && "Functions without a prototype cannot be overloaded");
6225   assert(!Function->getDescribedFunctionTemplate() &&
6226          "Use AddTemplateOverloadCandidate for function templates");
6227 
6228   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6229     if (!isa<CXXConstructorDecl>(Method)) {
6230       // If we get here, it's because we're calling a member function
6231       // that is named without a member access expression (e.g.,
6232       // "this->f") that was either written explicitly or created
6233       // implicitly. This can happen with a qualified call to a member
6234       // function, e.g., X::f(). We use an empty type for the implied
6235       // object argument (C++ [over.call.func]p3), and the acting context
6236       // is irrelevant.
6237       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6238                          Expr::Classification::makeSimpleLValue(), Args,
6239                          CandidateSet, SuppressUserConversions,
6240                          PartialOverloading, EarlyConversions, PO);
6241       return;
6242     }
6243     // We treat a constructor like a non-member function, since its object
6244     // argument doesn't participate in overload resolution.
6245   }
6246 
6247   if (!CandidateSet.isNewCandidate(Function, PO))
6248     return;
6249 
6250   // C++11 [class.copy]p11: [DR1402]
6251   //   A defaulted move constructor that is defined as deleted is ignored by
6252   //   overload resolution.
6253   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6254   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6255       Constructor->isMoveConstructor())
6256     return;
6257 
6258   // Overload resolution is always an unevaluated context.
6259   EnterExpressionEvaluationContext Unevaluated(
6260       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6261 
6262   // C++ [over.match.oper]p3:
6263   //   if no operand has a class type, only those non-member functions in the
6264   //   lookup set that have a first parameter of type T1 or "reference to
6265   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6266   //   is a right operand) a second parameter of type T2 or "reference to
6267   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6268   //   candidate functions.
6269   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6270       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6271     return;
6272 
6273   // Add this candidate
6274   OverloadCandidate &Candidate =
6275       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6276   Candidate.FoundDecl = FoundDecl;
6277   Candidate.Function = Function;
6278   Candidate.Viable = true;
6279   Candidate.RewriteKind =
6280       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6281   Candidate.IsSurrogate = false;
6282   Candidate.IsADLCandidate = IsADLCandidate;
6283   Candidate.IgnoreObjectArgument = false;
6284   Candidate.ExplicitCallArguments = Args.size();
6285 
6286   // Explicit functions are not actually candidates at all if we're not
6287   // allowing them in this context, but keep them around so we can point
6288   // to them in diagnostics.
6289   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6290     Candidate.Viable = false;
6291     Candidate.FailureKind = ovl_fail_explicit;
6292     return;
6293   }
6294 
6295   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6296       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6297     Candidate.Viable = false;
6298     Candidate.FailureKind = ovl_non_default_multiversion_function;
6299     return;
6300   }
6301 
6302   if (Constructor) {
6303     // C++ [class.copy]p3:
6304     //   A member function template is never instantiated to perform the copy
6305     //   of a class object to an object of its class type.
6306     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6307     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6308         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6309          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6310                        ClassType))) {
6311       Candidate.Viable = false;
6312       Candidate.FailureKind = ovl_fail_illegal_constructor;
6313       return;
6314     }
6315 
6316     // C++ [over.match.funcs]p8: (proposed DR resolution)
6317     //   A constructor inherited from class type C that has a first parameter
6318     //   of type "reference to P" (including such a constructor instantiated
6319     //   from a template) is excluded from the set of candidate functions when
6320     //   constructing an object of type cv D if the argument list has exactly
6321     //   one argument and D is reference-related to P and P is reference-related
6322     //   to C.
6323     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6324     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6325         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6326       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6327       QualType C = Context.getRecordType(Constructor->getParent());
6328       QualType D = Context.getRecordType(Shadow->getParent());
6329       SourceLocation Loc = Args.front()->getExprLoc();
6330       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6331           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6332         Candidate.Viable = false;
6333         Candidate.FailureKind = ovl_fail_inhctor_slice;
6334         return;
6335       }
6336     }
6337 
6338     // Check that the constructor is capable of constructing an object in the
6339     // destination address space.
6340     if (!Qualifiers::isAddressSpaceSupersetOf(
6341             Constructor->getMethodQualifiers().getAddressSpace(),
6342             CandidateSet.getDestAS())) {
6343       Candidate.Viable = false;
6344       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6345     }
6346   }
6347 
6348   unsigned NumParams = Proto->getNumParams();
6349 
6350   // (C++ 13.3.2p2): A candidate function having fewer than m
6351   // parameters is viable only if it has an ellipsis in its parameter
6352   // list (8.3.5).
6353   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6354       !Proto->isVariadic()) {
6355     Candidate.Viable = false;
6356     Candidate.FailureKind = ovl_fail_too_many_arguments;
6357     return;
6358   }
6359 
6360   // (C++ 13.3.2p2): A candidate function having more than m parameters
6361   // is viable only if the (m+1)st parameter has a default argument
6362   // (8.3.6). For the purposes of overload resolution, the
6363   // parameter list is truncated on the right, so that there are
6364   // exactly m parameters.
6365   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6366   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6367     // Not enough arguments.
6368     Candidate.Viable = false;
6369     Candidate.FailureKind = ovl_fail_too_few_arguments;
6370     return;
6371   }
6372 
6373   // (CUDA B.1): Check for invalid calls between targets.
6374   if (getLangOpts().CUDA)
6375     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6376       // Skip the check for callers that are implicit members, because in this
6377       // case we may not yet know what the member's target is; the target is
6378       // inferred for the member automatically, based on the bases and fields of
6379       // the class.
6380       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6381         Candidate.Viable = false;
6382         Candidate.FailureKind = ovl_fail_bad_target;
6383         return;
6384       }
6385 
6386   if (Function->getTrailingRequiresClause()) {
6387     ConstraintSatisfaction Satisfaction;
6388     if (CheckFunctionConstraints(Function, Satisfaction) ||
6389         !Satisfaction.IsSatisfied) {
6390       Candidate.Viable = false;
6391       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6392       return;
6393     }
6394   }
6395 
6396   // Determine the implicit conversion sequences for each of the
6397   // arguments.
6398   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6399     unsigned ConvIdx =
6400         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6401     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6402       // We already formed a conversion sequence for this parameter during
6403       // template argument deduction.
6404     } else if (ArgIdx < NumParams) {
6405       // (C++ 13.3.2p3): for F to be a viable function, there shall
6406       // exist for each argument an implicit conversion sequence
6407       // (13.3.3.1) that converts that argument to the corresponding
6408       // parameter of F.
6409       QualType ParamType = Proto->getParamType(ArgIdx);
6410       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6411           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6412           /*InOverloadResolution=*/true,
6413           /*AllowObjCWritebackConversion=*/
6414           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6415       if (Candidate.Conversions[ConvIdx].isBad()) {
6416         Candidate.Viable = false;
6417         Candidate.FailureKind = ovl_fail_bad_conversion;
6418         return;
6419       }
6420     } else {
6421       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6422       // argument for which there is no corresponding parameter is
6423       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6424       Candidate.Conversions[ConvIdx].setEllipsis();
6425     }
6426   }
6427 
6428   if (EnableIfAttr *FailedAttr =
6429           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6430     Candidate.Viable = false;
6431     Candidate.FailureKind = ovl_fail_enable_if;
6432     Candidate.DeductionFailure.Data = FailedAttr;
6433     return;
6434   }
6435 
6436   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6437     Candidate.Viable = false;
6438     Candidate.FailureKind = ovl_fail_ext_disabled;
6439     return;
6440   }
6441 }
6442 
6443 ObjCMethodDecl *
6444 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6445                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6446   if (Methods.size() <= 1)
6447     return nullptr;
6448 
6449   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6450     bool Match = true;
6451     ObjCMethodDecl *Method = Methods[b];
6452     unsigned NumNamedArgs = Sel.getNumArgs();
6453     // Method might have more arguments than selector indicates. This is due
6454     // to addition of c-style arguments in method.
6455     if (Method->param_size() > NumNamedArgs)
6456       NumNamedArgs = Method->param_size();
6457     if (Args.size() < NumNamedArgs)
6458       continue;
6459 
6460     for (unsigned i = 0; i < NumNamedArgs; i++) {
6461       // We can't do any type-checking on a type-dependent argument.
6462       if (Args[i]->isTypeDependent()) {
6463         Match = false;
6464         break;
6465       }
6466 
6467       ParmVarDecl *param = Method->parameters()[i];
6468       Expr *argExpr = Args[i];
6469       assert(argExpr && "SelectBestMethod(): missing expression");
6470 
6471       // Strip the unbridged-cast placeholder expression off unless it's
6472       // a consumed argument.
6473       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6474           !param->hasAttr<CFConsumedAttr>())
6475         argExpr = stripARCUnbridgedCast(argExpr);
6476 
6477       // If the parameter is __unknown_anytype, move on to the next method.
6478       if (param->getType() == Context.UnknownAnyTy) {
6479         Match = false;
6480         break;
6481       }
6482 
6483       ImplicitConversionSequence ConversionState
6484         = TryCopyInitialization(*this, argExpr, param->getType(),
6485                                 /*SuppressUserConversions*/false,
6486                                 /*InOverloadResolution=*/true,
6487                                 /*AllowObjCWritebackConversion=*/
6488                                 getLangOpts().ObjCAutoRefCount,
6489                                 /*AllowExplicit*/false);
6490       // This function looks for a reasonably-exact match, so we consider
6491       // incompatible pointer conversions to be a failure here.
6492       if (ConversionState.isBad() ||
6493           (ConversionState.isStandard() &&
6494            ConversionState.Standard.Second ==
6495                ICK_Incompatible_Pointer_Conversion)) {
6496         Match = false;
6497         break;
6498       }
6499     }
6500     // Promote additional arguments to variadic methods.
6501     if (Match && Method->isVariadic()) {
6502       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6503         if (Args[i]->isTypeDependent()) {
6504           Match = false;
6505           break;
6506         }
6507         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6508                                                           nullptr);
6509         if (Arg.isInvalid()) {
6510           Match = false;
6511           break;
6512         }
6513       }
6514     } else {
6515       // Check for extra arguments to non-variadic methods.
6516       if (Args.size() != NumNamedArgs)
6517         Match = false;
6518       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6519         // Special case when selectors have no argument. In this case, select
6520         // one with the most general result type of 'id'.
6521         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6522           QualType ReturnT = Methods[b]->getReturnType();
6523           if (ReturnT->isObjCIdType())
6524             return Methods[b];
6525         }
6526       }
6527     }
6528 
6529     if (Match)
6530       return Method;
6531   }
6532   return nullptr;
6533 }
6534 
6535 static bool convertArgsForAvailabilityChecks(
6536     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6537     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6538     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6539   if (ThisArg) {
6540     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6541     assert(!isa<CXXConstructorDecl>(Method) &&
6542            "Shouldn't have `this` for ctors!");
6543     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6544     ExprResult R = S.PerformObjectArgumentInitialization(
6545         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6546     if (R.isInvalid())
6547       return false;
6548     ConvertedThis = R.get();
6549   } else {
6550     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6551       (void)MD;
6552       assert((MissingImplicitThis || MD->isStatic() ||
6553               isa<CXXConstructorDecl>(MD)) &&
6554              "Expected `this` for non-ctor instance methods");
6555     }
6556     ConvertedThis = nullptr;
6557   }
6558 
6559   // Ignore any variadic arguments. Converting them is pointless, since the
6560   // user can't refer to them in the function condition.
6561   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6562 
6563   // Convert the arguments.
6564   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6565     ExprResult R;
6566     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6567                                         S.Context, Function->getParamDecl(I)),
6568                                     SourceLocation(), Args[I]);
6569 
6570     if (R.isInvalid())
6571       return false;
6572 
6573     ConvertedArgs.push_back(R.get());
6574   }
6575 
6576   if (Trap.hasErrorOccurred())
6577     return false;
6578 
6579   // Push default arguments if needed.
6580   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6581     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6582       ParmVarDecl *P = Function->getParamDecl(i);
6583       if (!P->hasDefaultArg())
6584         return false;
6585       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6586       if (R.isInvalid())
6587         return false;
6588       ConvertedArgs.push_back(R.get());
6589     }
6590 
6591     if (Trap.hasErrorOccurred())
6592       return false;
6593   }
6594   return true;
6595 }
6596 
6597 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6598                                   SourceLocation CallLoc,
6599                                   ArrayRef<Expr *> Args,
6600                                   bool MissingImplicitThis) {
6601   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6602   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6603     return nullptr;
6604 
6605   SFINAETrap Trap(*this);
6606   SmallVector<Expr *, 16> ConvertedArgs;
6607   // FIXME: We should look into making enable_if late-parsed.
6608   Expr *DiscardedThis;
6609   if (!convertArgsForAvailabilityChecks(
6610           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6611           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6612     return *EnableIfAttrs.begin();
6613 
6614   for (auto *EIA : EnableIfAttrs) {
6615     APValue Result;
6616     // FIXME: This doesn't consider value-dependent cases, because doing so is
6617     // very difficult. Ideally, we should handle them more gracefully.
6618     if (EIA->getCond()->isValueDependent() ||
6619         !EIA->getCond()->EvaluateWithSubstitution(
6620             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6621       return EIA;
6622 
6623     if (!Result.isInt() || !Result.getInt().getBoolValue())
6624       return EIA;
6625   }
6626   return nullptr;
6627 }
6628 
6629 template <typename CheckFn>
6630 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6631                                         bool ArgDependent, SourceLocation Loc,
6632                                         CheckFn &&IsSuccessful) {
6633   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6634   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6635     if (ArgDependent == DIA->getArgDependent())
6636       Attrs.push_back(DIA);
6637   }
6638 
6639   // Common case: No diagnose_if attributes, so we can quit early.
6640   if (Attrs.empty())
6641     return false;
6642 
6643   auto WarningBegin = std::stable_partition(
6644       Attrs.begin(), Attrs.end(),
6645       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6646 
6647   // Note that diagnose_if attributes are late-parsed, so they appear in the
6648   // correct order (unlike enable_if attributes).
6649   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6650                                IsSuccessful);
6651   if (ErrAttr != WarningBegin) {
6652     const DiagnoseIfAttr *DIA = *ErrAttr;
6653     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6654     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6655         << DIA->getParent() << DIA->getCond()->getSourceRange();
6656     return true;
6657   }
6658 
6659   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6660     if (IsSuccessful(DIA)) {
6661       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6662       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6663           << DIA->getParent() << DIA->getCond()->getSourceRange();
6664     }
6665 
6666   return false;
6667 }
6668 
6669 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6670                                                const Expr *ThisArg,
6671                                                ArrayRef<const Expr *> Args,
6672                                                SourceLocation Loc) {
6673   return diagnoseDiagnoseIfAttrsWith(
6674       *this, Function, /*ArgDependent=*/true, Loc,
6675       [&](const DiagnoseIfAttr *DIA) {
6676         APValue Result;
6677         // It's sane to use the same Args for any redecl of this function, since
6678         // EvaluateWithSubstitution only cares about the position of each
6679         // argument in the arg list, not the ParmVarDecl* it maps to.
6680         if (!DIA->getCond()->EvaluateWithSubstitution(
6681                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6682           return false;
6683         return Result.isInt() && Result.getInt().getBoolValue();
6684       });
6685 }
6686 
6687 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6688                                                  SourceLocation Loc) {
6689   return diagnoseDiagnoseIfAttrsWith(
6690       *this, ND, /*ArgDependent=*/false, Loc,
6691       [&](const DiagnoseIfAttr *DIA) {
6692         bool Result;
6693         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6694                Result;
6695       });
6696 }
6697 
6698 /// Add all of the function declarations in the given function set to
6699 /// the overload candidate set.
6700 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6701                                  ArrayRef<Expr *> Args,
6702                                  OverloadCandidateSet &CandidateSet,
6703                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6704                                  bool SuppressUserConversions,
6705                                  bool PartialOverloading,
6706                                  bool FirstArgumentIsBase) {
6707   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6708     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6709     ArrayRef<Expr *> FunctionArgs = Args;
6710 
6711     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6712     FunctionDecl *FD =
6713         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6714 
6715     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6716       QualType ObjectType;
6717       Expr::Classification ObjectClassification;
6718       if (Args.size() > 0) {
6719         if (Expr *E = Args[0]) {
6720           // Use the explicit base to restrict the lookup:
6721           ObjectType = E->getType();
6722           // Pointers in the object arguments are implicitly dereferenced, so we
6723           // always classify them as l-values.
6724           if (!ObjectType.isNull() && ObjectType->isPointerType())
6725             ObjectClassification = Expr::Classification::makeSimpleLValue();
6726           else
6727             ObjectClassification = E->Classify(Context);
6728         } // .. else there is an implicit base.
6729         FunctionArgs = Args.slice(1);
6730       }
6731       if (FunTmpl) {
6732         AddMethodTemplateCandidate(
6733             FunTmpl, F.getPair(),
6734             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6735             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6736             FunctionArgs, CandidateSet, SuppressUserConversions,
6737             PartialOverloading);
6738       } else {
6739         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6740                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6741                            ObjectClassification, FunctionArgs, CandidateSet,
6742                            SuppressUserConversions, PartialOverloading);
6743       }
6744     } else {
6745       // This branch handles both standalone functions and static methods.
6746 
6747       // Slice the first argument (which is the base) when we access
6748       // static method as non-static.
6749       if (Args.size() > 0 &&
6750           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6751                         !isa<CXXConstructorDecl>(FD)))) {
6752         assert(cast<CXXMethodDecl>(FD)->isStatic());
6753         FunctionArgs = Args.slice(1);
6754       }
6755       if (FunTmpl) {
6756         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6757                                      ExplicitTemplateArgs, FunctionArgs,
6758                                      CandidateSet, SuppressUserConversions,
6759                                      PartialOverloading);
6760       } else {
6761         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6762                              SuppressUserConversions, PartialOverloading);
6763       }
6764     }
6765   }
6766 }
6767 
6768 /// AddMethodCandidate - Adds a named decl (which is some kind of
6769 /// method) as a method candidate to the given overload set.
6770 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6771                               Expr::Classification ObjectClassification,
6772                               ArrayRef<Expr *> Args,
6773                               OverloadCandidateSet &CandidateSet,
6774                               bool SuppressUserConversions,
6775                               OverloadCandidateParamOrder PO) {
6776   NamedDecl *Decl = FoundDecl.getDecl();
6777   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6778 
6779   if (isa<UsingShadowDecl>(Decl))
6780     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6781 
6782   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6783     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6784            "Expected a member function template");
6785     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6786                                /*ExplicitArgs*/ nullptr, ObjectType,
6787                                ObjectClassification, Args, CandidateSet,
6788                                SuppressUserConversions, false, PO);
6789   } else {
6790     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6791                        ObjectType, ObjectClassification, Args, CandidateSet,
6792                        SuppressUserConversions, false, None, PO);
6793   }
6794 }
6795 
6796 /// AddMethodCandidate - Adds the given C++ member function to the set
6797 /// of candidate functions, using the given function call arguments
6798 /// and the object argument (@c Object). For example, in a call
6799 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6800 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6801 /// allow user-defined conversions via constructors or conversion
6802 /// operators.
6803 void
6804 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6805                          CXXRecordDecl *ActingContext, QualType ObjectType,
6806                          Expr::Classification ObjectClassification,
6807                          ArrayRef<Expr *> Args,
6808                          OverloadCandidateSet &CandidateSet,
6809                          bool SuppressUserConversions,
6810                          bool PartialOverloading,
6811                          ConversionSequenceList EarlyConversions,
6812                          OverloadCandidateParamOrder PO) {
6813   const FunctionProtoType *Proto
6814     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6815   assert(Proto && "Methods without a prototype cannot be overloaded");
6816   assert(!isa<CXXConstructorDecl>(Method) &&
6817          "Use AddOverloadCandidate for constructors");
6818 
6819   if (!CandidateSet.isNewCandidate(Method, PO))
6820     return;
6821 
6822   // C++11 [class.copy]p23: [DR1402]
6823   //   A defaulted move assignment operator that is defined as deleted is
6824   //   ignored by overload resolution.
6825   if (Method->isDefaulted() && Method->isDeleted() &&
6826       Method->isMoveAssignmentOperator())
6827     return;
6828 
6829   // Overload resolution is always an unevaluated context.
6830   EnterExpressionEvaluationContext Unevaluated(
6831       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6832 
6833   // Add this candidate
6834   OverloadCandidate &Candidate =
6835       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6836   Candidate.FoundDecl = FoundDecl;
6837   Candidate.Function = Method;
6838   Candidate.RewriteKind =
6839       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6840   Candidate.IsSurrogate = false;
6841   Candidate.IgnoreObjectArgument = false;
6842   Candidate.ExplicitCallArguments = Args.size();
6843 
6844   unsigned NumParams = Proto->getNumParams();
6845 
6846   // (C++ 13.3.2p2): A candidate function having fewer than m
6847   // parameters is viable only if it has an ellipsis in its parameter
6848   // list (8.3.5).
6849   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6850       !Proto->isVariadic()) {
6851     Candidate.Viable = false;
6852     Candidate.FailureKind = ovl_fail_too_many_arguments;
6853     return;
6854   }
6855 
6856   // (C++ 13.3.2p2): A candidate function having more than m parameters
6857   // is viable only if the (m+1)st parameter has a default argument
6858   // (8.3.6). For the purposes of overload resolution, the
6859   // parameter list is truncated on the right, so that there are
6860   // exactly m parameters.
6861   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6862   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6863     // Not enough arguments.
6864     Candidate.Viable = false;
6865     Candidate.FailureKind = ovl_fail_too_few_arguments;
6866     return;
6867   }
6868 
6869   Candidate.Viable = true;
6870 
6871   if (Method->isStatic() || ObjectType.isNull())
6872     // The implicit object argument is ignored.
6873     Candidate.IgnoreObjectArgument = true;
6874   else {
6875     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6876     // Determine the implicit conversion sequence for the object
6877     // parameter.
6878     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6879         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6880         Method, ActingContext);
6881     if (Candidate.Conversions[ConvIdx].isBad()) {
6882       Candidate.Viable = false;
6883       Candidate.FailureKind = ovl_fail_bad_conversion;
6884       return;
6885     }
6886   }
6887 
6888   // (CUDA B.1): Check for invalid calls between targets.
6889   if (getLangOpts().CUDA)
6890     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6891       if (!IsAllowedCUDACall(Caller, Method)) {
6892         Candidate.Viable = false;
6893         Candidate.FailureKind = ovl_fail_bad_target;
6894         return;
6895       }
6896 
6897   if (Method->getTrailingRequiresClause()) {
6898     ConstraintSatisfaction Satisfaction;
6899     if (CheckFunctionConstraints(Method, Satisfaction) ||
6900         !Satisfaction.IsSatisfied) {
6901       Candidate.Viable = false;
6902       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6903       return;
6904     }
6905   }
6906 
6907   // Determine the implicit conversion sequences for each of the
6908   // arguments.
6909   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6910     unsigned ConvIdx =
6911         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6912     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6913       // We already formed a conversion sequence for this parameter during
6914       // template argument deduction.
6915     } else if (ArgIdx < NumParams) {
6916       // (C++ 13.3.2p3): for F to be a viable function, there shall
6917       // exist for each argument an implicit conversion sequence
6918       // (13.3.3.1) that converts that argument to the corresponding
6919       // parameter of F.
6920       QualType ParamType = Proto->getParamType(ArgIdx);
6921       Candidate.Conversions[ConvIdx]
6922         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6923                                 SuppressUserConversions,
6924                                 /*InOverloadResolution=*/true,
6925                                 /*AllowObjCWritebackConversion=*/
6926                                   getLangOpts().ObjCAutoRefCount);
6927       if (Candidate.Conversions[ConvIdx].isBad()) {
6928         Candidate.Viable = false;
6929         Candidate.FailureKind = ovl_fail_bad_conversion;
6930         return;
6931       }
6932     } else {
6933       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6934       // argument for which there is no corresponding parameter is
6935       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6936       Candidate.Conversions[ConvIdx].setEllipsis();
6937     }
6938   }
6939 
6940   if (EnableIfAttr *FailedAttr =
6941           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6942     Candidate.Viable = false;
6943     Candidate.FailureKind = ovl_fail_enable_if;
6944     Candidate.DeductionFailure.Data = FailedAttr;
6945     return;
6946   }
6947 
6948   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6949       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6950     Candidate.Viable = false;
6951     Candidate.FailureKind = ovl_non_default_multiversion_function;
6952   }
6953 }
6954 
6955 /// Add a C++ member function template as a candidate to the candidate
6956 /// set, using template argument deduction to produce an appropriate member
6957 /// function template specialization.
6958 void Sema::AddMethodTemplateCandidate(
6959     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6960     CXXRecordDecl *ActingContext,
6961     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6962     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6963     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6964     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6965   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6966     return;
6967 
6968   // C++ [over.match.funcs]p7:
6969   //   In each case where a candidate is a function template, candidate
6970   //   function template specializations are generated using template argument
6971   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6972   //   candidate functions in the usual way.113) A given name can refer to one
6973   //   or more function templates and also to a set of overloaded non-template
6974   //   functions. In such a case, the candidate functions generated from each
6975   //   function template are combined with the set of non-template candidate
6976   //   functions.
6977   TemplateDeductionInfo Info(CandidateSet.getLocation());
6978   FunctionDecl *Specialization = nullptr;
6979   ConversionSequenceList Conversions;
6980   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6981           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6982           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6983             return CheckNonDependentConversions(
6984                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6985                 SuppressUserConversions, ActingContext, ObjectType,
6986                 ObjectClassification, PO);
6987           })) {
6988     OverloadCandidate &Candidate =
6989         CandidateSet.addCandidate(Conversions.size(), Conversions);
6990     Candidate.FoundDecl = FoundDecl;
6991     Candidate.Function = MethodTmpl->getTemplatedDecl();
6992     Candidate.Viable = false;
6993     Candidate.RewriteKind =
6994       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6995     Candidate.IsSurrogate = false;
6996     Candidate.IgnoreObjectArgument =
6997         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6998         ObjectType.isNull();
6999     Candidate.ExplicitCallArguments = Args.size();
7000     if (Result == TDK_NonDependentConversionFailure)
7001       Candidate.FailureKind = ovl_fail_bad_conversion;
7002     else {
7003       Candidate.FailureKind = ovl_fail_bad_deduction;
7004       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7005                                                             Info);
7006     }
7007     return;
7008   }
7009 
7010   // Add the function template specialization produced by template argument
7011   // deduction as a candidate.
7012   assert(Specialization && "Missing member function template specialization?");
7013   assert(isa<CXXMethodDecl>(Specialization) &&
7014          "Specialization is not a member function?");
7015   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7016                      ActingContext, ObjectType, ObjectClassification, Args,
7017                      CandidateSet, SuppressUserConversions, PartialOverloading,
7018                      Conversions, PO);
7019 }
7020 
7021 /// Determine whether a given function template has a simple explicit specifier
7022 /// or a non-value-dependent explicit-specification that evaluates to true.
7023 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7024   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7025 }
7026 
7027 /// Add a C++ function template specialization as a candidate
7028 /// in the candidate set, using template argument deduction to produce
7029 /// an appropriate function template specialization.
7030 void Sema::AddTemplateOverloadCandidate(
7031     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7032     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7033     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7034     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7035     OverloadCandidateParamOrder PO) {
7036   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7037     return;
7038 
7039   // If the function template has a non-dependent explicit specification,
7040   // exclude it now if appropriate; we are not permitted to perform deduction
7041   // and substitution in this case.
7042   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7043     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7044     Candidate.FoundDecl = FoundDecl;
7045     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7046     Candidate.Viable = false;
7047     Candidate.FailureKind = ovl_fail_explicit;
7048     return;
7049   }
7050 
7051   // C++ [over.match.funcs]p7:
7052   //   In each case where a candidate is a function template, candidate
7053   //   function template specializations are generated using template argument
7054   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7055   //   candidate functions in the usual way.113) A given name can refer to one
7056   //   or more function templates and also to a set of overloaded non-template
7057   //   functions. In such a case, the candidate functions generated from each
7058   //   function template are combined with the set of non-template candidate
7059   //   functions.
7060   TemplateDeductionInfo Info(CandidateSet.getLocation());
7061   FunctionDecl *Specialization = nullptr;
7062   ConversionSequenceList Conversions;
7063   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7064           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7065           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7066             return CheckNonDependentConversions(
7067                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7068                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7069           })) {
7070     OverloadCandidate &Candidate =
7071         CandidateSet.addCandidate(Conversions.size(), Conversions);
7072     Candidate.FoundDecl = FoundDecl;
7073     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7074     Candidate.Viable = false;
7075     Candidate.RewriteKind =
7076       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7077     Candidate.IsSurrogate = false;
7078     Candidate.IsADLCandidate = IsADLCandidate;
7079     // Ignore the object argument if there is one, since we don't have an object
7080     // type.
7081     Candidate.IgnoreObjectArgument =
7082         isa<CXXMethodDecl>(Candidate.Function) &&
7083         !isa<CXXConstructorDecl>(Candidate.Function);
7084     Candidate.ExplicitCallArguments = Args.size();
7085     if (Result == TDK_NonDependentConversionFailure)
7086       Candidate.FailureKind = ovl_fail_bad_conversion;
7087     else {
7088       Candidate.FailureKind = ovl_fail_bad_deduction;
7089       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7090                                                             Info);
7091     }
7092     return;
7093   }
7094 
7095   // Add the function template specialization produced by template argument
7096   // deduction as a candidate.
7097   assert(Specialization && "Missing function template specialization?");
7098   AddOverloadCandidate(
7099       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7100       PartialOverloading, AllowExplicit,
7101       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7102 }
7103 
7104 /// Check that implicit conversion sequences can be formed for each argument
7105 /// whose corresponding parameter has a non-dependent type, per DR1391's
7106 /// [temp.deduct.call]p10.
7107 bool Sema::CheckNonDependentConversions(
7108     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7109     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7110     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7111     CXXRecordDecl *ActingContext, QualType ObjectType,
7112     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7113   // FIXME: The cases in which we allow explicit conversions for constructor
7114   // arguments never consider calling a constructor template. It's not clear
7115   // that is correct.
7116   const bool AllowExplicit = false;
7117 
7118   auto *FD = FunctionTemplate->getTemplatedDecl();
7119   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7120   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7121   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7122 
7123   Conversions =
7124       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7125 
7126   // Overload resolution is always an unevaluated context.
7127   EnterExpressionEvaluationContext Unevaluated(
7128       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7129 
7130   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7131   // require that, but this check should never result in a hard error, and
7132   // overload resolution is permitted to sidestep instantiations.
7133   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7134       !ObjectType.isNull()) {
7135     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7136     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7137         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7138         Method, ActingContext);
7139     if (Conversions[ConvIdx].isBad())
7140       return true;
7141   }
7142 
7143   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7144        ++I) {
7145     QualType ParamType = ParamTypes[I];
7146     if (!ParamType->isDependentType()) {
7147       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7148                              ? 0
7149                              : (ThisConversions + I);
7150       Conversions[ConvIdx]
7151         = TryCopyInitialization(*this, Args[I], ParamType,
7152                                 SuppressUserConversions,
7153                                 /*InOverloadResolution=*/true,
7154                                 /*AllowObjCWritebackConversion=*/
7155                                   getLangOpts().ObjCAutoRefCount,
7156                                 AllowExplicit);
7157       if (Conversions[ConvIdx].isBad())
7158         return true;
7159     }
7160   }
7161 
7162   return false;
7163 }
7164 
7165 /// Determine whether this is an allowable conversion from the result
7166 /// of an explicit conversion operator to the expected type, per C++
7167 /// [over.match.conv]p1 and [over.match.ref]p1.
7168 ///
7169 /// \param ConvType The return type of the conversion function.
7170 ///
7171 /// \param ToType The type we are converting to.
7172 ///
7173 /// \param AllowObjCPointerConversion Allow a conversion from one
7174 /// Objective-C pointer to another.
7175 ///
7176 /// \returns true if the conversion is allowable, false otherwise.
7177 static bool isAllowableExplicitConversion(Sema &S,
7178                                           QualType ConvType, QualType ToType,
7179                                           bool AllowObjCPointerConversion) {
7180   QualType ToNonRefType = ToType.getNonReferenceType();
7181 
7182   // Easy case: the types are the same.
7183   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7184     return true;
7185 
7186   // Allow qualification conversions.
7187   bool ObjCLifetimeConversion;
7188   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7189                                   ObjCLifetimeConversion))
7190     return true;
7191 
7192   // If we're not allowed to consider Objective-C pointer conversions,
7193   // we're done.
7194   if (!AllowObjCPointerConversion)
7195     return false;
7196 
7197   // Is this an Objective-C pointer conversion?
7198   bool IncompatibleObjC = false;
7199   QualType ConvertedType;
7200   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7201                                    IncompatibleObjC);
7202 }
7203 
7204 /// AddConversionCandidate - Add a C++ conversion function as a
7205 /// candidate in the candidate set (C++ [over.match.conv],
7206 /// C++ [over.match.copy]). From is the expression we're converting from,
7207 /// and ToType is the type that we're eventually trying to convert to
7208 /// (which may or may not be the same type as the type that the
7209 /// conversion function produces).
7210 void Sema::AddConversionCandidate(
7211     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7212     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7213     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7214     bool AllowExplicit, bool AllowResultConversion) {
7215   assert(!Conversion->getDescribedFunctionTemplate() &&
7216          "Conversion function templates use AddTemplateConversionCandidate");
7217   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7218   if (!CandidateSet.isNewCandidate(Conversion))
7219     return;
7220 
7221   // If the conversion function has an undeduced return type, trigger its
7222   // deduction now.
7223   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7224     if (DeduceReturnType(Conversion, From->getExprLoc()))
7225       return;
7226     ConvType = Conversion->getConversionType().getNonReferenceType();
7227   }
7228 
7229   // If we don't allow any conversion of the result type, ignore conversion
7230   // functions that don't convert to exactly (possibly cv-qualified) T.
7231   if (!AllowResultConversion &&
7232       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7233     return;
7234 
7235   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7236   // operator is only a candidate if its return type is the target type or
7237   // can be converted to the target type with a qualification conversion.
7238   //
7239   // FIXME: Include such functions in the candidate list and explain why we
7240   // can't select them.
7241   if (Conversion->isExplicit() &&
7242       !isAllowableExplicitConversion(*this, ConvType, ToType,
7243                                      AllowObjCConversionOnExplicit))
7244     return;
7245 
7246   // Overload resolution is always an unevaluated context.
7247   EnterExpressionEvaluationContext Unevaluated(
7248       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7249 
7250   // Add this candidate
7251   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7252   Candidate.FoundDecl = FoundDecl;
7253   Candidate.Function = Conversion;
7254   Candidate.IsSurrogate = false;
7255   Candidate.IgnoreObjectArgument = false;
7256   Candidate.FinalConversion.setAsIdentityConversion();
7257   Candidate.FinalConversion.setFromType(ConvType);
7258   Candidate.FinalConversion.setAllToTypes(ToType);
7259   Candidate.Viable = true;
7260   Candidate.ExplicitCallArguments = 1;
7261 
7262   // Explicit functions are not actually candidates at all if we're not
7263   // allowing them in this context, but keep them around so we can point
7264   // to them in diagnostics.
7265   if (!AllowExplicit && Conversion->isExplicit()) {
7266     Candidate.Viable = false;
7267     Candidate.FailureKind = ovl_fail_explicit;
7268     return;
7269   }
7270 
7271   // C++ [over.match.funcs]p4:
7272   //   For conversion functions, the function is considered to be a member of
7273   //   the class of the implicit implied object argument for the purpose of
7274   //   defining the type of the implicit object parameter.
7275   //
7276   // Determine the implicit conversion sequence for the implicit
7277   // object parameter.
7278   QualType ImplicitParamType = From->getType();
7279   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7280     ImplicitParamType = FromPtrType->getPointeeType();
7281   CXXRecordDecl *ConversionContext
7282     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7283 
7284   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7285       *this, CandidateSet.getLocation(), From->getType(),
7286       From->Classify(Context), Conversion, ConversionContext);
7287 
7288   if (Candidate.Conversions[0].isBad()) {
7289     Candidate.Viable = false;
7290     Candidate.FailureKind = ovl_fail_bad_conversion;
7291     return;
7292   }
7293 
7294   if (Conversion->getTrailingRequiresClause()) {
7295     ConstraintSatisfaction Satisfaction;
7296     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7297         !Satisfaction.IsSatisfied) {
7298       Candidate.Viable = false;
7299       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7300       return;
7301     }
7302   }
7303 
7304   // We won't go through a user-defined type conversion function to convert a
7305   // derived to base as such conversions are given Conversion Rank. They only
7306   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7307   QualType FromCanon
7308     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7309   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7310   if (FromCanon == ToCanon ||
7311       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7312     Candidate.Viable = false;
7313     Candidate.FailureKind = ovl_fail_trivial_conversion;
7314     return;
7315   }
7316 
7317   // To determine what the conversion from the result of calling the
7318   // conversion function to the type we're eventually trying to
7319   // convert to (ToType), we need to synthesize a call to the
7320   // conversion function and attempt copy initialization from it. This
7321   // makes sure that we get the right semantics with respect to
7322   // lvalues/rvalues and the type. Fortunately, we can allocate this
7323   // call on the stack and we don't need its arguments to be
7324   // well-formed.
7325   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7326                             VK_LValue, From->getBeginLoc());
7327   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7328                                 Context.getPointerType(Conversion->getType()),
7329                                 CK_FunctionToPointerDecay, &ConversionRef,
7330                                 VK_RValue, FPOptionsOverride());
7331 
7332   QualType ConversionType = Conversion->getConversionType();
7333   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7334     Candidate.Viable = false;
7335     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7336     return;
7337   }
7338 
7339   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7340 
7341   // Note that it is safe to allocate CallExpr on the stack here because
7342   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7343   // allocator).
7344   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7345 
7346   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7347   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7348       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7349 
7350   ImplicitConversionSequence ICS =
7351       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7352                             /*SuppressUserConversions=*/true,
7353                             /*InOverloadResolution=*/false,
7354                             /*AllowObjCWritebackConversion=*/false);
7355 
7356   switch (ICS.getKind()) {
7357   case ImplicitConversionSequence::StandardConversion:
7358     Candidate.FinalConversion = ICS.Standard;
7359 
7360     // C++ [over.ics.user]p3:
7361     //   If the user-defined conversion is specified by a specialization of a
7362     //   conversion function template, the second standard conversion sequence
7363     //   shall have exact match rank.
7364     if (Conversion->getPrimaryTemplate() &&
7365         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7366       Candidate.Viable = false;
7367       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7368       return;
7369     }
7370 
7371     // C++0x [dcl.init.ref]p5:
7372     //    In the second case, if the reference is an rvalue reference and
7373     //    the second standard conversion sequence of the user-defined
7374     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7375     //    program is ill-formed.
7376     if (ToType->isRValueReferenceType() &&
7377         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7378       Candidate.Viable = false;
7379       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7380       return;
7381     }
7382     break;
7383 
7384   case ImplicitConversionSequence::BadConversion:
7385     Candidate.Viable = false;
7386     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7387     return;
7388 
7389   default:
7390     llvm_unreachable(
7391            "Can only end up with a standard conversion sequence or failure");
7392   }
7393 
7394   if (EnableIfAttr *FailedAttr =
7395           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7396     Candidate.Viable = false;
7397     Candidate.FailureKind = ovl_fail_enable_if;
7398     Candidate.DeductionFailure.Data = FailedAttr;
7399     return;
7400   }
7401 
7402   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7403       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7404     Candidate.Viable = false;
7405     Candidate.FailureKind = ovl_non_default_multiversion_function;
7406   }
7407 }
7408 
7409 /// Adds a conversion function template specialization
7410 /// candidate to the overload set, using template argument deduction
7411 /// to deduce the template arguments of the conversion function
7412 /// template from the type that we are converting to (C++
7413 /// [temp.deduct.conv]).
7414 void Sema::AddTemplateConversionCandidate(
7415     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7416     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7417     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7418     bool AllowExplicit, bool AllowResultConversion) {
7419   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7420          "Only conversion function templates permitted here");
7421 
7422   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7423     return;
7424 
7425   // If the function template has a non-dependent explicit specification,
7426   // exclude it now if appropriate; we are not permitted to perform deduction
7427   // and substitution in this case.
7428   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7429     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7430     Candidate.FoundDecl = FoundDecl;
7431     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7432     Candidate.Viable = false;
7433     Candidate.FailureKind = ovl_fail_explicit;
7434     return;
7435   }
7436 
7437   TemplateDeductionInfo Info(CandidateSet.getLocation());
7438   CXXConversionDecl *Specialization = nullptr;
7439   if (TemplateDeductionResult Result
7440         = DeduceTemplateArguments(FunctionTemplate, ToType,
7441                                   Specialization, Info)) {
7442     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7443     Candidate.FoundDecl = FoundDecl;
7444     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7445     Candidate.Viable = false;
7446     Candidate.FailureKind = ovl_fail_bad_deduction;
7447     Candidate.IsSurrogate = false;
7448     Candidate.IgnoreObjectArgument = false;
7449     Candidate.ExplicitCallArguments = 1;
7450     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7451                                                           Info);
7452     return;
7453   }
7454 
7455   // Add the conversion function template specialization produced by
7456   // template argument deduction as a candidate.
7457   assert(Specialization && "Missing function template specialization?");
7458   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7459                          CandidateSet, AllowObjCConversionOnExplicit,
7460                          AllowExplicit, AllowResultConversion);
7461 }
7462 
7463 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7464 /// converts the given @c Object to a function pointer via the
7465 /// conversion function @c Conversion, and then attempts to call it
7466 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7467 /// the type of function that we'll eventually be calling.
7468 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7469                                  DeclAccessPair FoundDecl,
7470                                  CXXRecordDecl *ActingContext,
7471                                  const FunctionProtoType *Proto,
7472                                  Expr *Object,
7473                                  ArrayRef<Expr *> Args,
7474                                  OverloadCandidateSet& CandidateSet) {
7475   if (!CandidateSet.isNewCandidate(Conversion))
7476     return;
7477 
7478   // Overload resolution is always an unevaluated context.
7479   EnterExpressionEvaluationContext Unevaluated(
7480       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7481 
7482   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7483   Candidate.FoundDecl = FoundDecl;
7484   Candidate.Function = nullptr;
7485   Candidate.Surrogate = Conversion;
7486   Candidate.Viable = true;
7487   Candidate.IsSurrogate = true;
7488   Candidate.IgnoreObjectArgument = false;
7489   Candidate.ExplicitCallArguments = Args.size();
7490 
7491   // Determine the implicit conversion sequence for the implicit
7492   // object parameter.
7493   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7494       *this, CandidateSet.getLocation(), Object->getType(),
7495       Object->Classify(Context), Conversion, ActingContext);
7496   if (ObjectInit.isBad()) {
7497     Candidate.Viable = false;
7498     Candidate.FailureKind = ovl_fail_bad_conversion;
7499     Candidate.Conversions[0] = ObjectInit;
7500     return;
7501   }
7502 
7503   // The first conversion is actually a user-defined conversion whose
7504   // first conversion is ObjectInit's standard conversion (which is
7505   // effectively a reference binding). Record it as such.
7506   Candidate.Conversions[0].setUserDefined();
7507   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7508   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7509   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7510   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7511   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7512   Candidate.Conversions[0].UserDefined.After
7513     = Candidate.Conversions[0].UserDefined.Before;
7514   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7515 
7516   // Find the
7517   unsigned NumParams = Proto->getNumParams();
7518 
7519   // (C++ 13.3.2p2): A candidate function having fewer than m
7520   // parameters is viable only if it has an ellipsis in its parameter
7521   // list (8.3.5).
7522   if (Args.size() > NumParams && !Proto->isVariadic()) {
7523     Candidate.Viable = false;
7524     Candidate.FailureKind = ovl_fail_too_many_arguments;
7525     return;
7526   }
7527 
7528   // Function types don't have any default arguments, so just check if
7529   // we have enough arguments.
7530   if (Args.size() < NumParams) {
7531     // Not enough arguments.
7532     Candidate.Viable = false;
7533     Candidate.FailureKind = ovl_fail_too_few_arguments;
7534     return;
7535   }
7536 
7537   // Determine the implicit conversion sequences for each of the
7538   // arguments.
7539   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7540     if (ArgIdx < NumParams) {
7541       // (C++ 13.3.2p3): for F to be a viable function, there shall
7542       // exist for each argument an implicit conversion sequence
7543       // (13.3.3.1) that converts that argument to the corresponding
7544       // parameter of F.
7545       QualType ParamType = Proto->getParamType(ArgIdx);
7546       Candidate.Conversions[ArgIdx + 1]
7547         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7548                                 /*SuppressUserConversions=*/false,
7549                                 /*InOverloadResolution=*/false,
7550                                 /*AllowObjCWritebackConversion=*/
7551                                   getLangOpts().ObjCAutoRefCount);
7552       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7553         Candidate.Viable = false;
7554         Candidate.FailureKind = ovl_fail_bad_conversion;
7555         return;
7556       }
7557     } else {
7558       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7559       // argument for which there is no corresponding parameter is
7560       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7561       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7562     }
7563   }
7564 
7565   if (EnableIfAttr *FailedAttr =
7566           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7567     Candidate.Viable = false;
7568     Candidate.FailureKind = ovl_fail_enable_if;
7569     Candidate.DeductionFailure.Data = FailedAttr;
7570     return;
7571   }
7572 }
7573 
7574 /// Add all of the non-member operator function declarations in the given
7575 /// function set to the overload candidate set.
7576 void Sema::AddNonMemberOperatorCandidates(
7577     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7578     OverloadCandidateSet &CandidateSet,
7579     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7580   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7581     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7582     ArrayRef<Expr *> FunctionArgs = Args;
7583 
7584     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7585     FunctionDecl *FD =
7586         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7587 
7588     // Don't consider rewritten functions if we're not rewriting.
7589     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7590       continue;
7591 
7592     assert(!isa<CXXMethodDecl>(FD) &&
7593            "unqualified operator lookup found a member function");
7594 
7595     if (FunTmpl) {
7596       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7597                                    FunctionArgs, CandidateSet);
7598       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7599         AddTemplateOverloadCandidate(
7600             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7601             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7602             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7603     } else {
7604       if (ExplicitTemplateArgs)
7605         continue;
7606       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7607       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7608         AddOverloadCandidate(FD, F.getPair(),
7609                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7610                              false, false, true, false, ADLCallKind::NotADL,
7611                              None, OverloadCandidateParamOrder::Reversed);
7612     }
7613   }
7614 }
7615 
7616 /// Add overload candidates for overloaded operators that are
7617 /// member functions.
7618 ///
7619 /// Add the overloaded operator candidates that are member functions
7620 /// for the operator Op that was used in an operator expression such
7621 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7622 /// CandidateSet will store the added overload candidates. (C++
7623 /// [over.match.oper]).
7624 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7625                                        SourceLocation OpLoc,
7626                                        ArrayRef<Expr *> Args,
7627                                        OverloadCandidateSet &CandidateSet,
7628                                        OverloadCandidateParamOrder PO) {
7629   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7630 
7631   // C++ [over.match.oper]p3:
7632   //   For a unary operator @ with an operand of a type whose
7633   //   cv-unqualified version is T1, and for a binary operator @ with
7634   //   a left operand of a type whose cv-unqualified version is T1 and
7635   //   a right operand of a type whose cv-unqualified version is T2,
7636   //   three sets of candidate functions, designated member
7637   //   candidates, non-member candidates and built-in candidates, are
7638   //   constructed as follows:
7639   QualType T1 = Args[0]->getType();
7640 
7641   //     -- If T1 is a complete class type or a class currently being
7642   //        defined, the set of member candidates is the result of the
7643   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7644   //        the set of member candidates is empty.
7645   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7646     // Complete the type if it can be completed.
7647     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7648       return;
7649     // If the type is neither complete nor being defined, bail out now.
7650     if (!T1Rec->getDecl()->getDefinition())
7651       return;
7652 
7653     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7654     LookupQualifiedName(Operators, T1Rec->getDecl());
7655     Operators.suppressDiagnostics();
7656 
7657     for (LookupResult::iterator Oper = Operators.begin(),
7658                              OperEnd = Operators.end();
7659          Oper != OperEnd;
7660          ++Oper)
7661       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7662                          Args[0]->Classify(Context), Args.slice(1),
7663                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7664   }
7665 }
7666 
7667 /// AddBuiltinCandidate - Add a candidate for a built-in
7668 /// operator. ResultTy and ParamTys are the result and parameter types
7669 /// of the built-in candidate, respectively. Args and NumArgs are the
7670 /// arguments being passed to the candidate. IsAssignmentOperator
7671 /// should be true when this built-in candidate is an assignment
7672 /// operator. NumContextualBoolArguments is the number of arguments
7673 /// (at the beginning of the argument list) that will be contextually
7674 /// converted to bool.
7675 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7676                                OverloadCandidateSet& CandidateSet,
7677                                bool IsAssignmentOperator,
7678                                unsigned NumContextualBoolArguments) {
7679   // Overload resolution is always an unevaluated context.
7680   EnterExpressionEvaluationContext Unevaluated(
7681       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7682 
7683   // Add this candidate
7684   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7685   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7686   Candidate.Function = nullptr;
7687   Candidate.IsSurrogate = false;
7688   Candidate.IgnoreObjectArgument = false;
7689   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7690 
7691   // Determine the implicit conversion sequences for each of the
7692   // arguments.
7693   Candidate.Viable = true;
7694   Candidate.ExplicitCallArguments = Args.size();
7695   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7696     // C++ [over.match.oper]p4:
7697     //   For the built-in assignment operators, conversions of the
7698     //   left operand are restricted as follows:
7699     //     -- no temporaries are introduced to hold the left operand, and
7700     //     -- no user-defined conversions are applied to the left
7701     //        operand to achieve a type match with the left-most
7702     //        parameter of a built-in candidate.
7703     //
7704     // We block these conversions by turning off user-defined
7705     // conversions, since that is the only way that initialization of
7706     // a reference to a non-class type can occur from something that
7707     // is not of the same type.
7708     if (ArgIdx < NumContextualBoolArguments) {
7709       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7710              "Contextual conversion to bool requires bool type");
7711       Candidate.Conversions[ArgIdx]
7712         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7713     } else {
7714       Candidate.Conversions[ArgIdx]
7715         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7716                                 ArgIdx == 0 && IsAssignmentOperator,
7717                                 /*InOverloadResolution=*/false,
7718                                 /*AllowObjCWritebackConversion=*/
7719                                   getLangOpts().ObjCAutoRefCount);
7720     }
7721     if (Candidate.Conversions[ArgIdx].isBad()) {
7722       Candidate.Viable = false;
7723       Candidate.FailureKind = ovl_fail_bad_conversion;
7724       break;
7725     }
7726   }
7727 }
7728 
7729 namespace {
7730 
7731 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7732 /// candidate operator functions for built-in operators (C++
7733 /// [over.built]). The types are separated into pointer types and
7734 /// enumeration types.
7735 class BuiltinCandidateTypeSet  {
7736   /// TypeSet - A set of types.
7737   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7738                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7739 
7740   /// PointerTypes - The set of pointer types that will be used in the
7741   /// built-in candidates.
7742   TypeSet PointerTypes;
7743 
7744   /// MemberPointerTypes - The set of member pointer types that will be
7745   /// used in the built-in candidates.
7746   TypeSet MemberPointerTypes;
7747 
7748   /// EnumerationTypes - The set of enumeration types that will be
7749   /// used in the built-in candidates.
7750   TypeSet EnumerationTypes;
7751 
7752   /// The set of vector types that will be used in the built-in
7753   /// candidates.
7754   TypeSet VectorTypes;
7755 
7756   /// The set of matrix types that will be used in the built-in
7757   /// candidates.
7758   TypeSet MatrixTypes;
7759 
7760   /// A flag indicating non-record types are viable candidates
7761   bool HasNonRecordTypes;
7762 
7763   /// A flag indicating whether either arithmetic or enumeration types
7764   /// were present in the candidate set.
7765   bool HasArithmeticOrEnumeralTypes;
7766 
7767   /// A flag indicating whether the nullptr type was present in the
7768   /// candidate set.
7769   bool HasNullPtrType;
7770 
7771   /// Sema - The semantic analysis instance where we are building the
7772   /// candidate type set.
7773   Sema &SemaRef;
7774 
7775   /// Context - The AST context in which we will build the type sets.
7776   ASTContext &Context;
7777 
7778   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7779                                                const Qualifiers &VisibleQuals);
7780   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7781 
7782 public:
7783   /// iterator - Iterates through the types that are part of the set.
7784   typedef TypeSet::iterator iterator;
7785 
7786   BuiltinCandidateTypeSet(Sema &SemaRef)
7787     : HasNonRecordTypes(false),
7788       HasArithmeticOrEnumeralTypes(false),
7789       HasNullPtrType(false),
7790       SemaRef(SemaRef),
7791       Context(SemaRef.Context) { }
7792 
7793   void AddTypesConvertedFrom(QualType Ty,
7794                              SourceLocation Loc,
7795                              bool AllowUserConversions,
7796                              bool AllowExplicitConversions,
7797                              const Qualifiers &VisibleTypeConversionsQuals);
7798 
7799   /// pointer_begin - First pointer type found;
7800   iterator pointer_begin() { return PointerTypes.begin(); }
7801 
7802   /// pointer_end - Past the last pointer type found;
7803   iterator pointer_end() { return PointerTypes.end(); }
7804 
7805   /// member_pointer_begin - First member pointer type found;
7806   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7807 
7808   /// member_pointer_end - Past the last member pointer type found;
7809   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7810 
7811   /// enumeration_begin - First enumeration type found;
7812   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7813 
7814   /// enumeration_end - Past the last enumeration type found;
7815   iterator enumeration_end() { return EnumerationTypes.end(); }
7816 
7817   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7818 
7819   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7820 
7821   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7822   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7823   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7824   bool hasNullPtrType() const { return HasNullPtrType; }
7825 };
7826 
7827 } // end anonymous namespace
7828 
7829 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7830 /// the set of pointer types along with any more-qualified variants of
7831 /// that type. For example, if @p Ty is "int const *", this routine
7832 /// will add "int const *", "int const volatile *", "int const
7833 /// restrict *", and "int const volatile restrict *" to the set of
7834 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7835 /// false otherwise.
7836 ///
7837 /// FIXME: what to do about extended qualifiers?
7838 bool
7839 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7840                                              const Qualifiers &VisibleQuals) {
7841 
7842   // Insert this type.
7843   if (!PointerTypes.insert(Ty))
7844     return false;
7845 
7846   QualType PointeeTy;
7847   const PointerType *PointerTy = Ty->getAs<PointerType>();
7848   bool buildObjCPtr = false;
7849   if (!PointerTy) {
7850     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7851     PointeeTy = PTy->getPointeeType();
7852     buildObjCPtr = true;
7853   } else {
7854     PointeeTy = PointerTy->getPointeeType();
7855   }
7856 
7857   // Don't add qualified variants of arrays. For one, they're not allowed
7858   // (the qualifier would sink to the element type), and for another, the
7859   // only overload situation where it matters is subscript or pointer +- int,
7860   // and those shouldn't have qualifier variants anyway.
7861   if (PointeeTy->isArrayType())
7862     return true;
7863 
7864   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7865   bool hasVolatile = VisibleQuals.hasVolatile();
7866   bool hasRestrict = VisibleQuals.hasRestrict();
7867 
7868   // Iterate through all strict supersets of BaseCVR.
7869   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7870     if ((CVR | BaseCVR) != CVR) continue;
7871     // Skip over volatile if no volatile found anywhere in the types.
7872     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7873 
7874     // Skip over restrict if no restrict found anywhere in the types, or if
7875     // the type cannot be restrict-qualified.
7876     if ((CVR & Qualifiers::Restrict) &&
7877         (!hasRestrict ||
7878          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7879       continue;
7880 
7881     // Build qualified pointee type.
7882     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7883 
7884     // Build qualified pointer type.
7885     QualType QPointerTy;
7886     if (!buildObjCPtr)
7887       QPointerTy = Context.getPointerType(QPointeeTy);
7888     else
7889       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7890 
7891     // Insert qualified pointer type.
7892     PointerTypes.insert(QPointerTy);
7893   }
7894 
7895   return true;
7896 }
7897 
7898 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7899 /// to the set of pointer types along with any more-qualified variants of
7900 /// that type. For example, if @p Ty is "int const *", this routine
7901 /// will add "int const *", "int const volatile *", "int const
7902 /// restrict *", and "int const volatile restrict *" to the set of
7903 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7904 /// false otherwise.
7905 ///
7906 /// FIXME: what to do about extended qualifiers?
7907 bool
7908 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7909     QualType Ty) {
7910   // Insert this type.
7911   if (!MemberPointerTypes.insert(Ty))
7912     return false;
7913 
7914   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7915   assert(PointerTy && "type was not a member pointer type!");
7916 
7917   QualType PointeeTy = PointerTy->getPointeeType();
7918   // Don't add qualified variants of arrays. For one, they're not allowed
7919   // (the qualifier would sink to the element type), and for another, the
7920   // only overload situation where it matters is subscript or pointer +- int,
7921   // and those shouldn't have qualifier variants anyway.
7922   if (PointeeTy->isArrayType())
7923     return true;
7924   const Type *ClassTy = PointerTy->getClass();
7925 
7926   // Iterate through all strict supersets of the pointee type's CVR
7927   // qualifiers.
7928   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7929   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7930     if ((CVR | BaseCVR) != CVR) continue;
7931 
7932     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7933     MemberPointerTypes.insert(
7934       Context.getMemberPointerType(QPointeeTy, ClassTy));
7935   }
7936 
7937   return true;
7938 }
7939 
7940 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7941 /// Ty can be implicit converted to the given set of @p Types. We're
7942 /// primarily interested in pointer types and enumeration types. We also
7943 /// take member pointer types, for the conditional operator.
7944 /// AllowUserConversions is true if we should look at the conversion
7945 /// functions of a class type, and AllowExplicitConversions if we
7946 /// should also include the explicit conversion functions of a class
7947 /// type.
7948 void
7949 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7950                                                SourceLocation Loc,
7951                                                bool AllowUserConversions,
7952                                                bool AllowExplicitConversions,
7953                                                const Qualifiers &VisibleQuals) {
7954   // Only deal with canonical types.
7955   Ty = Context.getCanonicalType(Ty);
7956 
7957   // Look through reference types; they aren't part of the type of an
7958   // expression for the purposes of conversions.
7959   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7960     Ty = RefTy->getPointeeType();
7961 
7962   // If we're dealing with an array type, decay to the pointer.
7963   if (Ty->isArrayType())
7964     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7965 
7966   // Otherwise, we don't care about qualifiers on the type.
7967   Ty = Ty.getLocalUnqualifiedType();
7968 
7969   // Flag if we ever add a non-record type.
7970   const RecordType *TyRec = Ty->getAs<RecordType>();
7971   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7972 
7973   // Flag if we encounter an arithmetic type.
7974   HasArithmeticOrEnumeralTypes =
7975     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7976 
7977   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7978     PointerTypes.insert(Ty);
7979   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7980     // Insert our type, and its more-qualified variants, into the set
7981     // of types.
7982     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7983       return;
7984   } else if (Ty->isMemberPointerType()) {
7985     // Member pointers are far easier, since the pointee can't be converted.
7986     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7987       return;
7988   } else if (Ty->isEnumeralType()) {
7989     HasArithmeticOrEnumeralTypes = true;
7990     EnumerationTypes.insert(Ty);
7991   } else if (Ty->isVectorType()) {
7992     // We treat vector types as arithmetic types in many contexts as an
7993     // extension.
7994     HasArithmeticOrEnumeralTypes = true;
7995     VectorTypes.insert(Ty);
7996   } else if (Ty->isMatrixType()) {
7997     // Similar to vector types, we treat vector types as arithmetic types in
7998     // many contexts as an extension.
7999     HasArithmeticOrEnumeralTypes = true;
8000     MatrixTypes.insert(Ty);
8001   } else if (Ty->isNullPtrType()) {
8002     HasNullPtrType = true;
8003   } else if (AllowUserConversions && TyRec) {
8004     // No conversion functions in incomplete types.
8005     if (!SemaRef.isCompleteType(Loc, Ty))
8006       return;
8007 
8008     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8009     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8010       if (isa<UsingShadowDecl>(D))
8011         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8012 
8013       // Skip conversion function templates; they don't tell us anything
8014       // about which builtin types we can convert to.
8015       if (isa<FunctionTemplateDecl>(D))
8016         continue;
8017 
8018       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8019       if (AllowExplicitConversions || !Conv->isExplicit()) {
8020         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8021                               VisibleQuals);
8022       }
8023     }
8024   }
8025 }
8026 /// Helper function for adjusting address spaces for the pointer or reference
8027 /// operands of builtin operators depending on the argument.
8028 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8029                                                         Expr *Arg) {
8030   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8031 }
8032 
8033 /// Helper function for AddBuiltinOperatorCandidates() that adds
8034 /// the volatile- and non-volatile-qualified assignment operators for the
8035 /// given type to the candidate set.
8036 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8037                                                    QualType T,
8038                                                    ArrayRef<Expr *> Args,
8039                                     OverloadCandidateSet &CandidateSet) {
8040   QualType ParamTypes[2];
8041 
8042   // T& operator=(T&, T)
8043   ParamTypes[0] = S.Context.getLValueReferenceType(
8044       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8045   ParamTypes[1] = T;
8046   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8047                         /*IsAssignmentOperator=*/true);
8048 
8049   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8050     // volatile T& operator=(volatile T&, T)
8051     ParamTypes[0] = S.Context.getLValueReferenceType(
8052         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8053                                                 Args[0]));
8054     ParamTypes[1] = T;
8055     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8056                           /*IsAssignmentOperator=*/true);
8057   }
8058 }
8059 
8060 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8061 /// if any, found in visible type conversion functions found in ArgExpr's type.
8062 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8063     Qualifiers VRQuals;
8064     const RecordType *TyRec;
8065     if (const MemberPointerType *RHSMPType =
8066         ArgExpr->getType()->getAs<MemberPointerType>())
8067       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8068     else
8069       TyRec = ArgExpr->getType()->getAs<RecordType>();
8070     if (!TyRec) {
8071       // Just to be safe, assume the worst case.
8072       VRQuals.addVolatile();
8073       VRQuals.addRestrict();
8074       return VRQuals;
8075     }
8076 
8077     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8078     if (!ClassDecl->hasDefinition())
8079       return VRQuals;
8080 
8081     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8082       if (isa<UsingShadowDecl>(D))
8083         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8084       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8085         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8086         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8087           CanTy = ResTypeRef->getPointeeType();
8088         // Need to go down the pointer/mempointer chain and add qualifiers
8089         // as see them.
8090         bool done = false;
8091         while (!done) {
8092           if (CanTy.isRestrictQualified())
8093             VRQuals.addRestrict();
8094           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8095             CanTy = ResTypePtr->getPointeeType();
8096           else if (const MemberPointerType *ResTypeMPtr =
8097                 CanTy->getAs<MemberPointerType>())
8098             CanTy = ResTypeMPtr->getPointeeType();
8099           else
8100             done = true;
8101           if (CanTy.isVolatileQualified())
8102             VRQuals.addVolatile();
8103           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8104             return VRQuals;
8105         }
8106       }
8107     }
8108     return VRQuals;
8109 }
8110 
8111 namespace {
8112 
8113 /// Helper class to manage the addition of builtin operator overload
8114 /// candidates. It provides shared state and utility methods used throughout
8115 /// the process, as well as a helper method to add each group of builtin
8116 /// operator overloads from the standard to a candidate set.
8117 class BuiltinOperatorOverloadBuilder {
8118   // Common instance state available to all overload candidate addition methods.
8119   Sema &S;
8120   ArrayRef<Expr *> Args;
8121   Qualifiers VisibleTypeConversionsQuals;
8122   bool HasArithmeticOrEnumeralCandidateType;
8123   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8124   OverloadCandidateSet &CandidateSet;
8125 
8126   static constexpr int ArithmeticTypesCap = 24;
8127   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8128 
8129   // Define some indices used to iterate over the arithmetic types in
8130   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8131   // types are that preserved by promotion (C++ [over.built]p2).
8132   unsigned FirstIntegralType,
8133            LastIntegralType;
8134   unsigned FirstPromotedIntegralType,
8135            LastPromotedIntegralType;
8136   unsigned FirstPromotedArithmeticType,
8137            LastPromotedArithmeticType;
8138   unsigned NumArithmeticTypes;
8139 
8140   void InitArithmeticTypes() {
8141     // Start of promoted types.
8142     FirstPromotedArithmeticType = 0;
8143     ArithmeticTypes.push_back(S.Context.FloatTy);
8144     ArithmeticTypes.push_back(S.Context.DoubleTy);
8145     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8146     if (S.Context.getTargetInfo().hasFloat128Type())
8147       ArithmeticTypes.push_back(S.Context.Float128Ty);
8148 
8149     // Start of integral types.
8150     FirstIntegralType = ArithmeticTypes.size();
8151     FirstPromotedIntegralType = ArithmeticTypes.size();
8152     ArithmeticTypes.push_back(S.Context.IntTy);
8153     ArithmeticTypes.push_back(S.Context.LongTy);
8154     ArithmeticTypes.push_back(S.Context.LongLongTy);
8155     if (S.Context.getTargetInfo().hasInt128Type())
8156       ArithmeticTypes.push_back(S.Context.Int128Ty);
8157     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8158     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8159     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8160     if (S.Context.getTargetInfo().hasInt128Type())
8161       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8162     LastPromotedIntegralType = ArithmeticTypes.size();
8163     LastPromotedArithmeticType = ArithmeticTypes.size();
8164     // End of promoted types.
8165 
8166     ArithmeticTypes.push_back(S.Context.BoolTy);
8167     ArithmeticTypes.push_back(S.Context.CharTy);
8168     ArithmeticTypes.push_back(S.Context.WCharTy);
8169     if (S.Context.getLangOpts().Char8)
8170       ArithmeticTypes.push_back(S.Context.Char8Ty);
8171     ArithmeticTypes.push_back(S.Context.Char16Ty);
8172     ArithmeticTypes.push_back(S.Context.Char32Ty);
8173     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8174     ArithmeticTypes.push_back(S.Context.ShortTy);
8175     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8176     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8177     LastIntegralType = ArithmeticTypes.size();
8178     NumArithmeticTypes = ArithmeticTypes.size();
8179     // End of integral types.
8180     // FIXME: What about complex? What about half?
8181 
8182     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8183            "Enough inline storage for all arithmetic types.");
8184   }
8185 
8186   /// Helper method to factor out the common pattern of adding overloads
8187   /// for '++' and '--' builtin operators.
8188   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8189                                            bool HasVolatile,
8190                                            bool HasRestrict) {
8191     QualType ParamTypes[2] = {
8192       S.Context.getLValueReferenceType(CandidateTy),
8193       S.Context.IntTy
8194     };
8195 
8196     // Non-volatile version.
8197     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8198 
8199     // Use a heuristic to reduce number of builtin candidates in the set:
8200     // add volatile version only if there are conversions to a volatile type.
8201     if (HasVolatile) {
8202       ParamTypes[0] =
8203         S.Context.getLValueReferenceType(
8204           S.Context.getVolatileType(CandidateTy));
8205       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8206     }
8207 
8208     // Add restrict version only if there are conversions to a restrict type
8209     // and our candidate type is a non-restrict-qualified pointer.
8210     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8211         !CandidateTy.isRestrictQualified()) {
8212       ParamTypes[0]
8213         = S.Context.getLValueReferenceType(
8214             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8215       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8216 
8217       if (HasVolatile) {
8218         ParamTypes[0]
8219           = S.Context.getLValueReferenceType(
8220               S.Context.getCVRQualifiedType(CandidateTy,
8221                                             (Qualifiers::Volatile |
8222                                              Qualifiers::Restrict)));
8223         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8224       }
8225     }
8226 
8227   }
8228 
8229   /// Helper to add an overload candidate for a binary builtin with types \p L
8230   /// and \p R.
8231   void AddCandidate(QualType L, QualType R) {
8232     QualType LandR[2] = {L, R};
8233     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8234   }
8235 
8236 public:
8237   BuiltinOperatorOverloadBuilder(
8238     Sema &S, ArrayRef<Expr *> Args,
8239     Qualifiers VisibleTypeConversionsQuals,
8240     bool HasArithmeticOrEnumeralCandidateType,
8241     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8242     OverloadCandidateSet &CandidateSet)
8243     : S(S), Args(Args),
8244       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8245       HasArithmeticOrEnumeralCandidateType(
8246         HasArithmeticOrEnumeralCandidateType),
8247       CandidateTypes(CandidateTypes),
8248       CandidateSet(CandidateSet) {
8249 
8250     InitArithmeticTypes();
8251   }
8252 
8253   // Increment is deprecated for bool since C++17.
8254   //
8255   // C++ [over.built]p3:
8256   //
8257   //   For every pair (T, VQ), where T is an arithmetic type other
8258   //   than bool, and VQ is either volatile or empty, there exist
8259   //   candidate operator functions of the form
8260   //
8261   //       VQ T&      operator++(VQ T&);
8262   //       T          operator++(VQ T&, int);
8263   //
8264   // C++ [over.built]p4:
8265   //
8266   //   For every pair (T, VQ), where T is an arithmetic type other
8267   //   than bool, and VQ is either volatile or empty, there exist
8268   //   candidate operator functions of the form
8269   //
8270   //       VQ T&      operator--(VQ T&);
8271   //       T          operator--(VQ T&, int);
8272   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8273     if (!HasArithmeticOrEnumeralCandidateType)
8274       return;
8275 
8276     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8277       const auto TypeOfT = ArithmeticTypes[Arith];
8278       if (TypeOfT == S.Context.BoolTy) {
8279         if (Op == OO_MinusMinus)
8280           continue;
8281         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8282           continue;
8283       }
8284       addPlusPlusMinusMinusStyleOverloads(
8285         TypeOfT,
8286         VisibleTypeConversionsQuals.hasVolatile(),
8287         VisibleTypeConversionsQuals.hasRestrict());
8288     }
8289   }
8290 
8291   // C++ [over.built]p5:
8292   //
8293   //   For every pair (T, VQ), where T is a cv-qualified or
8294   //   cv-unqualified object type, and VQ is either volatile or
8295   //   empty, there exist candidate operator functions of the form
8296   //
8297   //       T*VQ&      operator++(T*VQ&);
8298   //       T*VQ&      operator--(T*VQ&);
8299   //       T*         operator++(T*VQ&, int);
8300   //       T*         operator--(T*VQ&, int);
8301   void addPlusPlusMinusMinusPointerOverloads() {
8302     for (BuiltinCandidateTypeSet::iterator
8303               Ptr = CandidateTypes[0].pointer_begin(),
8304            PtrEnd = CandidateTypes[0].pointer_end();
8305          Ptr != PtrEnd; ++Ptr) {
8306       // Skip pointer types that aren't pointers to object types.
8307       if (!(*Ptr)->getPointeeType()->isObjectType())
8308         continue;
8309 
8310       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8311         (!(*Ptr).isVolatileQualified() &&
8312          VisibleTypeConversionsQuals.hasVolatile()),
8313         (!(*Ptr).isRestrictQualified() &&
8314          VisibleTypeConversionsQuals.hasRestrict()));
8315     }
8316   }
8317 
8318   // C++ [over.built]p6:
8319   //   For every cv-qualified or cv-unqualified object type T, there
8320   //   exist candidate operator functions of the form
8321   //
8322   //       T&         operator*(T*);
8323   //
8324   // C++ [over.built]p7:
8325   //   For every function type T that does not have cv-qualifiers or a
8326   //   ref-qualifier, there exist candidate operator functions of the form
8327   //       T&         operator*(T*);
8328   void addUnaryStarPointerOverloads() {
8329     for (BuiltinCandidateTypeSet::iterator
8330               Ptr = CandidateTypes[0].pointer_begin(),
8331            PtrEnd = CandidateTypes[0].pointer_end();
8332          Ptr != PtrEnd; ++Ptr) {
8333       QualType ParamTy = *Ptr;
8334       QualType PointeeTy = ParamTy->getPointeeType();
8335       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8336         continue;
8337 
8338       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8339         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8340           continue;
8341 
8342       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8343     }
8344   }
8345 
8346   // C++ [over.built]p9:
8347   //  For every promoted arithmetic type T, there exist candidate
8348   //  operator functions of the form
8349   //
8350   //       T         operator+(T);
8351   //       T         operator-(T);
8352   void addUnaryPlusOrMinusArithmeticOverloads() {
8353     if (!HasArithmeticOrEnumeralCandidateType)
8354       return;
8355 
8356     for (unsigned Arith = FirstPromotedArithmeticType;
8357          Arith < LastPromotedArithmeticType; ++Arith) {
8358       QualType ArithTy = ArithmeticTypes[Arith];
8359       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8360     }
8361 
8362     // Extension: We also add these operators for vector types.
8363     for (QualType VecTy : CandidateTypes[0].vector_types())
8364       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8365   }
8366 
8367   // C++ [over.built]p8:
8368   //   For every type T, there exist candidate operator functions of
8369   //   the form
8370   //
8371   //       T*         operator+(T*);
8372   void addUnaryPlusPointerOverloads() {
8373     for (BuiltinCandidateTypeSet::iterator
8374               Ptr = CandidateTypes[0].pointer_begin(),
8375            PtrEnd = CandidateTypes[0].pointer_end();
8376          Ptr != PtrEnd; ++Ptr) {
8377       QualType ParamTy = *Ptr;
8378       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8379     }
8380   }
8381 
8382   // C++ [over.built]p10:
8383   //   For every promoted integral type T, there exist candidate
8384   //   operator functions of the form
8385   //
8386   //        T         operator~(T);
8387   void addUnaryTildePromotedIntegralOverloads() {
8388     if (!HasArithmeticOrEnumeralCandidateType)
8389       return;
8390 
8391     for (unsigned Int = FirstPromotedIntegralType;
8392          Int < LastPromotedIntegralType; ++Int) {
8393       QualType IntTy = ArithmeticTypes[Int];
8394       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8395     }
8396 
8397     // Extension: We also add this operator for vector types.
8398     for (QualType VecTy : CandidateTypes[0].vector_types())
8399       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8400   }
8401 
8402   // C++ [over.match.oper]p16:
8403   //   For every pointer to member type T or type std::nullptr_t, there
8404   //   exist candidate operator functions of the form
8405   //
8406   //        bool operator==(T,T);
8407   //        bool operator!=(T,T);
8408   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8409     /// Set of (canonical) types that we've already handled.
8410     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8411 
8412     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8413       for (BuiltinCandidateTypeSet::iterator
8414                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8415              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8416            MemPtr != MemPtrEnd;
8417            ++MemPtr) {
8418         // Don't add the same builtin candidate twice.
8419         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8420           continue;
8421 
8422         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8423         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8424       }
8425 
8426       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8427         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8428         if (AddedTypes.insert(NullPtrTy).second) {
8429           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8430           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8431         }
8432       }
8433     }
8434   }
8435 
8436   // C++ [over.built]p15:
8437   //
8438   //   For every T, where T is an enumeration type or a pointer type,
8439   //   there exist candidate operator functions of the form
8440   //
8441   //        bool       operator<(T, T);
8442   //        bool       operator>(T, T);
8443   //        bool       operator<=(T, T);
8444   //        bool       operator>=(T, T);
8445   //        bool       operator==(T, T);
8446   //        bool       operator!=(T, T);
8447   //           R       operator<=>(T, T)
8448   void addGenericBinaryPointerOrEnumeralOverloads() {
8449     // C++ [over.match.oper]p3:
8450     //   [...]the built-in candidates include all of the candidate operator
8451     //   functions defined in 13.6 that, compared to the given operator, [...]
8452     //   do not have the same parameter-type-list as any non-template non-member
8453     //   candidate.
8454     //
8455     // Note that in practice, this only affects enumeration types because there
8456     // aren't any built-in candidates of record type, and a user-defined operator
8457     // must have an operand of record or enumeration type. Also, the only other
8458     // overloaded operator with enumeration arguments, operator=,
8459     // cannot be overloaded for enumeration types, so this is the only place
8460     // where we must suppress candidates like this.
8461     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8462       UserDefinedBinaryOperators;
8463 
8464     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8465       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8466           CandidateTypes[ArgIdx].enumeration_end()) {
8467         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8468                                          CEnd = CandidateSet.end();
8469              C != CEnd; ++C) {
8470           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8471             continue;
8472 
8473           if (C->Function->isFunctionTemplateSpecialization())
8474             continue;
8475 
8476           // We interpret "same parameter-type-list" as applying to the
8477           // "synthesized candidate, with the order of the two parameters
8478           // reversed", not to the original function.
8479           bool Reversed = C->isReversed();
8480           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8481                                         ->getType()
8482                                         .getUnqualifiedType();
8483           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8484                                          ->getType()
8485                                          .getUnqualifiedType();
8486 
8487           // Skip if either parameter isn't of enumeral type.
8488           if (!FirstParamType->isEnumeralType() ||
8489               !SecondParamType->isEnumeralType())
8490             continue;
8491 
8492           // Add this operator to the set of known user-defined operators.
8493           UserDefinedBinaryOperators.insert(
8494             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8495                            S.Context.getCanonicalType(SecondParamType)));
8496         }
8497       }
8498     }
8499 
8500     /// Set of (canonical) types that we've already handled.
8501     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8502 
8503     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8504       for (BuiltinCandidateTypeSet::iterator
8505                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8506              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8507            Ptr != PtrEnd; ++Ptr) {
8508         // Don't add the same builtin candidate twice.
8509         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8510           continue;
8511 
8512         QualType ParamTypes[2] = { *Ptr, *Ptr };
8513         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8514       }
8515       for (BuiltinCandidateTypeSet::iterator
8516                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8517              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8518            Enum != EnumEnd; ++Enum) {
8519         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8520 
8521         // Don't add the same builtin candidate twice, or if a user defined
8522         // candidate exists.
8523         if (!AddedTypes.insert(CanonType).second ||
8524             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8525                                                             CanonType)))
8526           continue;
8527         QualType ParamTypes[2] = { *Enum, *Enum };
8528         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8529       }
8530     }
8531   }
8532 
8533   // C++ [over.built]p13:
8534   //
8535   //   For every cv-qualified or cv-unqualified object type T
8536   //   there exist candidate operator functions of the form
8537   //
8538   //      T*         operator+(T*, ptrdiff_t);
8539   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8540   //      T*         operator-(T*, ptrdiff_t);
8541   //      T*         operator+(ptrdiff_t, T*);
8542   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8543   //
8544   // C++ [over.built]p14:
8545   //
8546   //   For every T, where T is a pointer to object type, there
8547   //   exist candidate operator functions of the form
8548   //
8549   //      ptrdiff_t  operator-(T, T);
8550   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8551     /// Set of (canonical) types that we've already handled.
8552     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8553 
8554     for (int Arg = 0; Arg < 2; ++Arg) {
8555       QualType AsymmetricParamTypes[2] = {
8556         S.Context.getPointerDiffType(),
8557         S.Context.getPointerDiffType(),
8558       };
8559       for (BuiltinCandidateTypeSet::iterator
8560                 Ptr = CandidateTypes[Arg].pointer_begin(),
8561              PtrEnd = CandidateTypes[Arg].pointer_end();
8562            Ptr != PtrEnd; ++Ptr) {
8563         QualType PointeeTy = (*Ptr)->getPointeeType();
8564         if (!PointeeTy->isObjectType())
8565           continue;
8566 
8567         AsymmetricParamTypes[Arg] = *Ptr;
8568         if (Arg == 0 || Op == OO_Plus) {
8569           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8570           // T* operator+(ptrdiff_t, T*);
8571           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8572         }
8573         if (Op == OO_Minus) {
8574           // ptrdiff_t operator-(T, T);
8575           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8576             continue;
8577 
8578           QualType ParamTypes[2] = { *Ptr, *Ptr };
8579           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8580         }
8581       }
8582     }
8583   }
8584 
8585   // C++ [over.built]p12:
8586   //
8587   //   For every pair of promoted arithmetic types L and R, there
8588   //   exist candidate operator functions of the form
8589   //
8590   //        LR         operator*(L, R);
8591   //        LR         operator/(L, R);
8592   //        LR         operator+(L, R);
8593   //        LR         operator-(L, R);
8594   //        bool       operator<(L, R);
8595   //        bool       operator>(L, R);
8596   //        bool       operator<=(L, R);
8597   //        bool       operator>=(L, R);
8598   //        bool       operator==(L, R);
8599   //        bool       operator!=(L, R);
8600   //
8601   //   where LR is the result of the usual arithmetic conversions
8602   //   between types L and R.
8603   //
8604   // C++ [over.built]p24:
8605   //
8606   //   For every pair of promoted arithmetic types L and R, there exist
8607   //   candidate operator functions of the form
8608   //
8609   //        LR       operator?(bool, L, R);
8610   //
8611   //   where LR is the result of the usual arithmetic conversions
8612   //   between types L and R.
8613   // Our candidates ignore the first parameter.
8614   void addGenericBinaryArithmeticOverloads() {
8615     if (!HasArithmeticOrEnumeralCandidateType)
8616       return;
8617 
8618     for (unsigned Left = FirstPromotedArithmeticType;
8619          Left < LastPromotedArithmeticType; ++Left) {
8620       for (unsigned Right = FirstPromotedArithmeticType;
8621            Right < LastPromotedArithmeticType; ++Right) {
8622         QualType LandR[2] = { ArithmeticTypes[Left],
8623                               ArithmeticTypes[Right] };
8624         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8625       }
8626     }
8627 
8628     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8629     // conditional operator for vector types.
8630     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8631       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8632         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8633         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8634       }
8635   }
8636 
8637   /// Add binary operator overloads for each candidate matrix type M1, M2:
8638   ///  * (M1, M1) -> M1
8639   ///  * (M1, M1.getElementType()) -> M1
8640   ///  * (M2.getElementType(), M2) -> M2
8641   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8642   void addMatrixBinaryArithmeticOverloads() {
8643     if (!HasArithmeticOrEnumeralCandidateType)
8644       return;
8645 
8646     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8647       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8648       AddCandidate(M1, M1);
8649     }
8650 
8651     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8652       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8653       if (!CandidateTypes[0].containsMatrixType(M2))
8654         AddCandidate(M2, M2);
8655     }
8656   }
8657 
8658   // C++2a [over.built]p14:
8659   //
8660   //   For every integral type T there exists a candidate operator function
8661   //   of the form
8662   //
8663   //        std::strong_ordering operator<=>(T, T)
8664   //
8665   // C++2a [over.built]p15:
8666   //
8667   //   For every pair of floating-point types L and R, there exists a candidate
8668   //   operator function of the form
8669   //
8670   //       std::partial_ordering operator<=>(L, R);
8671   //
8672   // FIXME: The current specification for integral types doesn't play nice with
8673   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8674   // comparisons. Under the current spec this can lead to ambiguity during
8675   // overload resolution. For example:
8676   //
8677   //   enum A : int {a};
8678   //   auto x = (a <=> (long)42);
8679   //
8680   //   error: call is ambiguous for arguments 'A' and 'long'.
8681   //   note: candidate operator<=>(int, int)
8682   //   note: candidate operator<=>(long, long)
8683   //
8684   // To avoid this error, this function deviates from the specification and adds
8685   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8686   // arithmetic types (the same as the generic relational overloads).
8687   //
8688   // For now this function acts as a placeholder.
8689   void addThreeWayArithmeticOverloads() {
8690     addGenericBinaryArithmeticOverloads();
8691   }
8692 
8693   // C++ [over.built]p17:
8694   //
8695   //   For every pair of promoted integral types L and R, there
8696   //   exist candidate operator functions of the form
8697   //
8698   //      LR         operator%(L, R);
8699   //      LR         operator&(L, R);
8700   //      LR         operator^(L, R);
8701   //      LR         operator|(L, R);
8702   //      L          operator<<(L, R);
8703   //      L          operator>>(L, R);
8704   //
8705   //   where LR is the result of the usual arithmetic conversions
8706   //   between types L and R.
8707   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8708     if (!HasArithmeticOrEnumeralCandidateType)
8709       return;
8710 
8711     for (unsigned Left = FirstPromotedIntegralType;
8712          Left < LastPromotedIntegralType; ++Left) {
8713       for (unsigned Right = FirstPromotedIntegralType;
8714            Right < LastPromotedIntegralType; ++Right) {
8715         QualType LandR[2] = { ArithmeticTypes[Left],
8716                               ArithmeticTypes[Right] };
8717         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8718       }
8719     }
8720   }
8721 
8722   // C++ [over.built]p20:
8723   //
8724   //   For every pair (T, VQ), where T is an enumeration or
8725   //   pointer to member type and VQ is either volatile or
8726   //   empty, there exist candidate operator functions of the form
8727   //
8728   //        VQ T&      operator=(VQ T&, T);
8729   void addAssignmentMemberPointerOrEnumeralOverloads() {
8730     /// Set of (canonical) types that we've already handled.
8731     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8732 
8733     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8734       for (BuiltinCandidateTypeSet::iterator
8735                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8736              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8737            Enum != EnumEnd; ++Enum) {
8738         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8739           continue;
8740 
8741         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8742       }
8743 
8744       for (BuiltinCandidateTypeSet::iterator
8745                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8746              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8747            MemPtr != MemPtrEnd; ++MemPtr) {
8748         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8749           continue;
8750 
8751         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8752       }
8753     }
8754   }
8755 
8756   // C++ [over.built]p19:
8757   //
8758   //   For every pair (T, VQ), where T is any type and VQ is either
8759   //   volatile or empty, there exist candidate operator functions
8760   //   of the form
8761   //
8762   //        T*VQ&      operator=(T*VQ&, T*);
8763   //
8764   // C++ [over.built]p21:
8765   //
8766   //   For every pair (T, VQ), where T is a cv-qualified or
8767   //   cv-unqualified object type and VQ is either volatile or
8768   //   empty, there exist candidate operator functions of the form
8769   //
8770   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8771   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8772   void addAssignmentPointerOverloads(bool isEqualOp) {
8773     /// Set of (canonical) types that we've already handled.
8774     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8775 
8776     for (BuiltinCandidateTypeSet::iterator
8777               Ptr = CandidateTypes[0].pointer_begin(),
8778            PtrEnd = CandidateTypes[0].pointer_end();
8779          Ptr != PtrEnd; ++Ptr) {
8780       // If this is operator=, keep track of the builtin candidates we added.
8781       if (isEqualOp)
8782         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8783       else if (!(*Ptr)->getPointeeType()->isObjectType())
8784         continue;
8785 
8786       // non-volatile version
8787       QualType ParamTypes[2] = {
8788         S.Context.getLValueReferenceType(*Ptr),
8789         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8790       };
8791       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8792                             /*IsAssignmentOperator=*/ isEqualOp);
8793 
8794       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8795                           VisibleTypeConversionsQuals.hasVolatile();
8796       if (NeedVolatile) {
8797         // volatile version
8798         ParamTypes[0] =
8799           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8800         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8801                               /*IsAssignmentOperator=*/isEqualOp);
8802       }
8803 
8804       if (!(*Ptr).isRestrictQualified() &&
8805           VisibleTypeConversionsQuals.hasRestrict()) {
8806         // restrict version
8807         ParamTypes[0]
8808           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8809         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8810                               /*IsAssignmentOperator=*/isEqualOp);
8811 
8812         if (NeedVolatile) {
8813           // volatile restrict version
8814           ParamTypes[0]
8815             = S.Context.getLValueReferenceType(
8816                 S.Context.getCVRQualifiedType(*Ptr,
8817                                               (Qualifiers::Volatile |
8818                                                Qualifiers::Restrict)));
8819           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8820                                 /*IsAssignmentOperator=*/isEqualOp);
8821         }
8822       }
8823     }
8824 
8825     if (isEqualOp) {
8826       for (BuiltinCandidateTypeSet::iterator
8827                 Ptr = CandidateTypes[1].pointer_begin(),
8828              PtrEnd = CandidateTypes[1].pointer_end();
8829            Ptr != PtrEnd; ++Ptr) {
8830         // Make sure we don't add the same candidate twice.
8831         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8832           continue;
8833 
8834         QualType ParamTypes[2] = {
8835           S.Context.getLValueReferenceType(*Ptr),
8836           *Ptr,
8837         };
8838 
8839         // non-volatile version
8840         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8841                               /*IsAssignmentOperator=*/true);
8842 
8843         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8844                            VisibleTypeConversionsQuals.hasVolatile();
8845         if (NeedVolatile) {
8846           // volatile version
8847           ParamTypes[0] =
8848             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8849           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8850                                 /*IsAssignmentOperator=*/true);
8851         }
8852 
8853         if (!(*Ptr).isRestrictQualified() &&
8854             VisibleTypeConversionsQuals.hasRestrict()) {
8855           // restrict version
8856           ParamTypes[0]
8857             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8858           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8859                                 /*IsAssignmentOperator=*/true);
8860 
8861           if (NeedVolatile) {
8862             // volatile restrict version
8863             ParamTypes[0]
8864               = S.Context.getLValueReferenceType(
8865                   S.Context.getCVRQualifiedType(*Ptr,
8866                                                 (Qualifiers::Volatile |
8867                                                  Qualifiers::Restrict)));
8868             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8869                                   /*IsAssignmentOperator=*/true);
8870           }
8871         }
8872       }
8873     }
8874   }
8875 
8876   // C++ [over.built]p18:
8877   //
8878   //   For every triple (L, VQ, R), where L is an arithmetic type,
8879   //   VQ is either volatile or empty, and R is a promoted
8880   //   arithmetic type, there exist candidate operator functions of
8881   //   the form
8882   //
8883   //        VQ L&      operator=(VQ L&, R);
8884   //        VQ L&      operator*=(VQ L&, R);
8885   //        VQ L&      operator/=(VQ L&, R);
8886   //        VQ L&      operator+=(VQ L&, R);
8887   //        VQ L&      operator-=(VQ L&, R);
8888   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8889     if (!HasArithmeticOrEnumeralCandidateType)
8890       return;
8891 
8892     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8893       for (unsigned Right = FirstPromotedArithmeticType;
8894            Right < LastPromotedArithmeticType; ++Right) {
8895         QualType ParamTypes[2];
8896         ParamTypes[1] = ArithmeticTypes[Right];
8897         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8898             S, ArithmeticTypes[Left], Args[0]);
8899         // Add this built-in operator as a candidate (VQ is empty).
8900         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8901         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8902                               /*IsAssignmentOperator=*/isEqualOp);
8903 
8904         // Add this built-in operator as a candidate (VQ is 'volatile').
8905         if (VisibleTypeConversionsQuals.hasVolatile()) {
8906           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8907           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8908           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8909                                 /*IsAssignmentOperator=*/isEqualOp);
8910         }
8911       }
8912     }
8913 
8914     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8915     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8916       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8917         QualType ParamTypes[2];
8918         ParamTypes[1] = Vec2Ty;
8919         // Add this built-in operator as a candidate (VQ is empty).
8920         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8921         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8922                               /*IsAssignmentOperator=*/isEqualOp);
8923 
8924         // Add this built-in operator as a candidate (VQ is 'volatile').
8925         if (VisibleTypeConversionsQuals.hasVolatile()) {
8926           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8927           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8928           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8929                                 /*IsAssignmentOperator=*/isEqualOp);
8930         }
8931       }
8932   }
8933 
8934   // C++ [over.built]p22:
8935   //
8936   //   For every triple (L, VQ, R), where L is an integral type, VQ
8937   //   is either volatile or empty, and R is a promoted integral
8938   //   type, there exist candidate operator functions of the form
8939   //
8940   //        VQ L&       operator%=(VQ L&, R);
8941   //        VQ L&       operator<<=(VQ L&, R);
8942   //        VQ L&       operator>>=(VQ L&, R);
8943   //        VQ L&       operator&=(VQ L&, R);
8944   //        VQ L&       operator^=(VQ L&, R);
8945   //        VQ L&       operator|=(VQ L&, R);
8946   void addAssignmentIntegralOverloads() {
8947     if (!HasArithmeticOrEnumeralCandidateType)
8948       return;
8949 
8950     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8951       for (unsigned Right = FirstPromotedIntegralType;
8952            Right < LastPromotedIntegralType; ++Right) {
8953         QualType ParamTypes[2];
8954         ParamTypes[1] = ArithmeticTypes[Right];
8955         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8956             S, ArithmeticTypes[Left], Args[0]);
8957         // Add this built-in operator as a candidate (VQ is empty).
8958         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8959         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8960         if (VisibleTypeConversionsQuals.hasVolatile()) {
8961           // Add this built-in operator as a candidate (VQ is 'volatile').
8962           ParamTypes[0] = LeftBaseTy;
8963           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8964           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8965           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8966         }
8967       }
8968     }
8969   }
8970 
8971   // C++ [over.operator]p23:
8972   //
8973   //   There also exist candidate operator functions of the form
8974   //
8975   //        bool        operator!(bool);
8976   //        bool        operator&&(bool, bool);
8977   //        bool        operator||(bool, bool);
8978   void addExclaimOverload() {
8979     QualType ParamTy = S.Context.BoolTy;
8980     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8981                           /*IsAssignmentOperator=*/false,
8982                           /*NumContextualBoolArguments=*/1);
8983   }
8984   void addAmpAmpOrPipePipeOverload() {
8985     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8986     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8987                           /*IsAssignmentOperator=*/false,
8988                           /*NumContextualBoolArguments=*/2);
8989   }
8990 
8991   // C++ [over.built]p13:
8992   //
8993   //   For every cv-qualified or cv-unqualified object type T there
8994   //   exist candidate operator functions of the form
8995   //
8996   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8997   //        T&         operator[](T*, ptrdiff_t);
8998   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8999   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9000   //        T&         operator[](ptrdiff_t, T*);
9001   void addSubscriptOverloads() {
9002     for (BuiltinCandidateTypeSet::iterator
9003               Ptr = CandidateTypes[0].pointer_begin(),
9004            PtrEnd = CandidateTypes[0].pointer_end();
9005          Ptr != PtrEnd; ++Ptr) {
9006       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
9007       QualType PointeeType = (*Ptr)->getPointeeType();
9008       if (!PointeeType->isObjectType())
9009         continue;
9010 
9011       // T& operator[](T*, ptrdiff_t)
9012       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9013     }
9014 
9015     for (BuiltinCandidateTypeSet::iterator
9016               Ptr = CandidateTypes[1].pointer_begin(),
9017            PtrEnd = CandidateTypes[1].pointer_end();
9018          Ptr != PtrEnd; ++Ptr) {
9019       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
9020       QualType PointeeType = (*Ptr)->getPointeeType();
9021       if (!PointeeType->isObjectType())
9022         continue;
9023 
9024       // T& operator[](ptrdiff_t, T*)
9025       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9026     }
9027   }
9028 
9029   // C++ [over.built]p11:
9030   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9031   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9032   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9033   //    there exist candidate operator functions of the form
9034   //
9035   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9036   //
9037   //    where CV12 is the union of CV1 and CV2.
9038   void addArrowStarOverloads() {
9039     for (BuiltinCandidateTypeSet::iterator
9040              Ptr = CandidateTypes[0].pointer_begin(),
9041            PtrEnd = CandidateTypes[0].pointer_end();
9042          Ptr != PtrEnd; ++Ptr) {
9043       QualType C1Ty = (*Ptr);
9044       QualType C1;
9045       QualifierCollector Q1;
9046       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9047       if (!isa<RecordType>(C1))
9048         continue;
9049       // heuristic to reduce number of builtin candidates in the set.
9050       // Add volatile/restrict version only if there are conversions to a
9051       // volatile/restrict type.
9052       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9053         continue;
9054       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9055         continue;
9056       for (BuiltinCandidateTypeSet::iterator
9057                 MemPtr = CandidateTypes[1].member_pointer_begin(),
9058              MemPtrEnd = CandidateTypes[1].member_pointer_end();
9059            MemPtr != MemPtrEnd; ++MemPtr) {
9060         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9061         QualType C2 = QualType(mptr->getClass(), 0);
9062         C2 = C2.getUnqualifiedType();
9063         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9064           break;
9065         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9066         // build CV12 T&
9067         QualType T = mptr->getPointeeType();
9068         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9069             T.isVolatileQualified())
9070           continue;
9071         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9072             T.isRestrictQualified())
9073           continue;
9074         T = Q1.apply(S.Context, T);
9075         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9076       }
9077     }
9078   }
9079 
9080   // Note that we don't consider the first argument, since it has been
9081   // contextually converted to bool long ago. The candidates below are
9082   // therefore added as binary.
9083   //
9084   // C++ [over.built]p25:
9085   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9086   //   enumeration type, there exist candidate operator functions of the form
9087   //
9088   //        T        operator?(bool, T, T);
9089   //
9090   void addConditionalOperatorOverloads() {
9091     /// Set of (canonical) types that we've already handled.
9092     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9093 
9094     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9095       for (BuiltinCandidateTypeSet::iterator
9096                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9097              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9098            Ptr != PtrEnd; ++Ptr) {
9099         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9100           continue;
9101 
9102         QualType ParamTypes[2] = { *Ptr, *Ptr };
9103         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9104       }
9105 
9106       for (BuiltinCandidateTypeSet::iterator
9107                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9108              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9109            MemPtr != MemPtrEnd; ++MemPtr) {
9110         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9111           continue;
9112 
9113         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9114         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9115       }
9116 
9117       if (S.getLangOpts().CPlusPlus11) {
9118         for (BuiltinCandidateTypeSet::iterator
9119                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9120                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9121              Enum != EnumEnd; ++Enum) {
9122           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9123             continue;
9124 
9125           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9126             continue;
9127 
9128           QualType ParamTypes[2] = { *Enum, *Enum };
9129           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9130         }
9131       }
9132     }
9133   }
9134 };
9135 
9136 } // end anonymous namespace
9137 
9138 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9139 /// operator overloads to the candidate set (C++ [over.built]), based
9140 /// on the operator @p Op and the arguments given. For example, if the
9141 /// operator is a binary '+', this routine might add "int
9142 /// operator+(int, int)" to cover integer addition.
9143 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9144                                         SourceLocation OpLoc,
9145                                         ArrayRef<Expr *> Args,
9146                                         OverloadCandidateSet &CandidateSet) {
9147   // Find all of the types that the arguments can convert to, but only
9148   // if the operator we're looking at has built-in operator candidates
9149   // that make use of these types. Also record whether we encounter non-record
9150   // candidate types or either arithmetic or enumeral candidate types.
9151   Qualifiers VisibleTypeConversionsQuals;
9152   VisibleTypeConversionsQuals.addConst();
9153   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9154     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9155 
9156   bool HasNonRecordCandidateType = false;
9157   bool HasArithmeticOrEnumeralCandidateType = false;
9158   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9159   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9160     CandidateTypes.emplace_back(*this);
9161     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9162                                                  OpLoc,
9163                                                  true,
9164                                                  (Op == OO_Exclaim ||
9165                                                   Op == OO_AmpAmp ||
9166                                                   Op == OO_PipePipe),
9167                                                  VisibleTypeConversionsQuals);
9168     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9169         CandidateTypes[ArgIdx].hasNonRecordTypes();
9170     HasArithmeticOrEnumeralCandidateType =
9171         HasArithmeticOrEnumeralCandidateType ||
9172         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9173   }
9174 
9175   // Exit early when no non-record types have been added to the candidate set
9176   // for any of the arguments to the operator.
9177   //
9178   // We can't exit early for !, ||, or &&, since there we have always have
9179   // 'bool' overloads.
9180   if (!HasNonRecordCandidateType &&
9181       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9182     return;
9183 
9184   // Setup an object to manage the common state for building overloads.
9185   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9186                                            VisibleTypeConversionsQuals,
9187                                            HasArithmeticOrEnumeralCandidateType,
9188                                            CandidateTypes, CandidateSet);
9189 
9190   // Dispatch over the operation to add in only those overloads which apply.
9191   switch (Op) {
9192   case OO_None:
9193   case NUM_OVERLOADED_OPERATORS:
9194     llvm_unreachable("Expected an overloaded operator");
9195 
9196   case OO_New:
9197   case OO_Delete:
9198   case OO_Array_New:
9199   case OO_Array_Delete:
9200   case OO_Call:
9201     llvm_unreachable(
9202                     "Special operators don't use AddBuiltinOperatorCandidates");
9203 
9204   case OO_Comma:
9205   case OO_Arrow:
9206   case OO_Coawait:
9207     // C++ [over.match.oper]p3:
9208     //   -- For the operator ',', the unary operator '&', the
9209     //      operator '->', or the operator 'co_await', the
9210     //      built-in candidates set is empty.
9211     break;
9212 
9213   case OO_Plus: // '+' is either unary or binary
9214     if (Args.size() == 1)
9215       OpBuilder.addUnaryPlusPointerOverloads();
9216     LLVM_FALLTHROUGH;
9217 
9218   case OO_Minus: // '-' is either unary or binary
9219     if (Args.size() == 1) {
9220       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9221     } else {
9222       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9223       OpBuilder.addGenericBinaryArithmeticOverloads();
9224       OpBuilder.addMatrixBinaryArithmeticOverloads();
9225     }
9226     break;
9227 
9228   case OO_Star: // '*' is either unary or binary
9229     if (Args.size() == 1)
9230       OpBuilder.addUnaryStarPointerOverloads();
9231     else {
9232       OpBuilder.addGenericBinaryArithmeticOverloads();
9233       OpBuilder.addMatrixBinaryArithmeticOverloads();
9234     }
9235     break;
9236 
9237   case OO_Slash:
9238     OpBuilder.addGenericBinaryArithmeticOverloads();
9239     break;
9240 
9241   case OO_PlusPlus:
9242   case OO_MinusMinus:
9243     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9244     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9245     break;
9246 
9247   case OO_EqualEqual:
9248   case OO_ExclaimEqual:
9249     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9250     LLVM_FALLTHROUGH;
9251 
9252   case OO_Less:
9253   case OO_Greater:
9254   case OO_LessEqual:
9255   case OO_GreaterEqual:
9256     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9257     OpBuilder.addGenericBinaryArithmeticOverloads();
9258     break;
9259 
9260   case OO_Spaceship:
9261     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9262     OpBuilder.addThreeWayArithmeticOverloads();
9263     break;
9264 
9265   case OO_Percent:
9266   case OO_Caret:
9267   case OO_Pipe:
9268   case OO_LessLess:
9269   case OO_GreaterGreater:
9270     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9271     break;
9272 
9273   case OO_Amp: // '&' is either unary or binary
9274     if (Args.size() == 1)
9275       // C++ [over.match.oper]p3:
9276       //   -- For the operator ',', the unary operator '&', or the
9277       //      operator '->', the built-in candidates set is empty.
9278       break;
9279 
9280     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9281     break;
9282 
9283   case OO_Tilde:
9284     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9285     break;
9286 
9287   case OO_Equal:
9288     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9289     LLVM_FALLTHROUGH;
9290 
9291   case OO_PlusEqual:
9292   case OO_MinusEqual:
9293     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9294     LLVM_FALLTHROUGH;
9295 
9296   case OO_StarEqual:
9297   case OO_SlashEqual:
9298     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9299     break;
9300 
9301   case OO_PercentEqual:
9302   case OO_LessLessEqual:
9303   case OO_GreaterGreaterEqual:
9304   case OO_AmpEqual:
9305   case OO_CaretEqual:
9306   case OO_PipeEqual:
9307     OpBuilder.addAssignmentIntegralOverloads();
9308     break;
9309 
9310   case OO_Exclaim:
9311     OpBuilder.addExclaimOverload();
9312     break;
9313 
9314   case OO_AmpAmp:
9315   case OO_PipePipe:
9316     OpBuilder.addAmpAmpOrPipePipeOverload();
9317     break;
9318 
9319   case OO_Subscript:
9320     OpBuilder.addSubscriptOverloads();
9321     break;
9322 
9323   case OO_ArrowStar:
9324     OpBuilder.addArrowStarOverloads();
9325     break;
9326 
9327   case OO_Conditional:
9328     OpBuilder.addConditionalOperatorOverloads();
9329     OpBuilder.addGenericBinaryArithmeticOverloads();
9330     break;
9331   }
9332 }
9333 
9334 /// Add function candidates found via argument-dependent lookup
9335 /// to the set of overloading candidates.
9336 ///
9337 /// This routine performs argument-dependent name lookup based on the
9338 /// given function name (which may also be an operator name) and adds
9339 /// all of the overload candidates found by ADL to the overload
9340 /// candidate set (C++ [basic.lookup.argdep]).
9341 void
9342 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9343                                            SourceLocation Loc,
9344                                            ArrayRef<Expr *> Args,
9345                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9346                                            OverloadCandidateSet& CandidateSet,
9347                                            bool PartialOverloading) {
9348   ADLResult Fns;
9349 
9350   // FIXME: This approach for uniquing ADL results (and removing
9351   // redundant candidates from the set) relies on pointer-equality,
9352   // which means we need to key off the canonical decl.  However,
9353   // always going back to the canonical decl might not get us the
9354   // right set of default arguments.  What default arguments are
9355   // we supposed to consider on ADL candidates, anyway?
9356 
9357   // FIXME: Pass in the explicit template arguments?
9358   ArgumentDependentLookup(Name, Loc, Args, Fns);
9359 
9360   // Erase all of the candidates we already knew about.
9361   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9362                                    CandEnd = CandidateSet.end();
9363        Cand != CandEnd; ++Cand)
9364     if (Cand->Function) {
9365       Fns.erase(Cand->Function);
9366       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9367         Fns.erase(FunTmpl);
9368     }
9369 
9370   // For each of the ADL candidates we found, add it to the overload
9371   // set.
9372   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9373     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9374 
9375     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9376       if (ExplicitTemplateArgs)
9377         continue;
9378 
9379       AddOverloadCandidate(
9380           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9381           PartialOverloading, /*AllowExplicit=*/true,
9382           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9383       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9384         AddOverloadCandidate(
9385             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9386             /*SuppressUserConversions=*/false, PartialOverloading,
9387             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9388             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9389       }
9390     } else {
9391       auto *FTD = cast<FunctionTemplateDecl>(*I);
9392       AddTemplateOverloadCandidate(
9393           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9394           /*SuppressUserConversions=*/false, PartialOverloading,
9395           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9396       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9397               Context, FTD->getTemplatedDecl())) {
9398         AddTemplateOverloadCandidate(
9399             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9400             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9401             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9402             OverloadCandidateParamOrder::Reversed);
9403       }
9404     }
9405   }
9406 }
9407 
9408 namespace {
9409 enum class Comparison { Equal, Better, Worse };
9410 }
9411 
9412 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9413 /// overload resolution.
9414 ///
9415 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9416 /// Cand1's first N enable_if attributes have precisely the same conditions as
9417 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9418 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9419 ///
9420 /// Note that you can have a pair of candidates such that Cand1's enable_if
9421 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9422 /// worse than Cand1's.
9423 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9424                                        const FunctionDecl *Cand2) {
9425   // Common case: One (or both) decls don't have enable_if attrs.
9426   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9427   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9428   if (!Cand1Attr || !Cand2Attr) {
9429     if (Cand1Attr == Cand2Attr)
9430       return Comparison::Equal;
9431     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9432   }
9433 
9434   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9435   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9436 
9437   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9438   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9439     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9440     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9441 
9442     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9443     // has fewer enable_if attributes than Cand2, and vice versa.
9444     if (!Cand1A)
9445       return Comparison::Worse;
9446     if (!Cand2A)
9447       return Comparison::Better;
9448 
9449     Cand1ID.clear();
9450     Cand2ID.clear();
9451 
9452     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9453     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9454     if (Cand1ID != Cand2ID)
9455       return Comparison::Worse;
9456   }
9457 
9458   return Comparison::Equal;
9459 }
9460 
9461 static Comparison
9462 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9463                               const OverloadCandidate &Cand2) {
9464   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9465       !Cand2.Function->isMultiVersion())
9466     return Comparison::Equal;
9467 
9468   // If both are invalid, they are equal. If one of them is invalid, the other
9469   // is better.
9470   if (Cand1.Function->isInvalidDecl()) {
9471     if (Cand2.Function->isInvalidDecl())
9472       return Comparison::Equal;
9473     return Comparison::Worse;
9474   }
9475   if (Cand2.Function->isInvalidDecl())
9476     return Comparison::Better;
9477 
9478   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9479   // cpu_dispatch, else arbitrarily based on the identifiers.
9480   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9481   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9482   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9483   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9484 
9485   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9486     return Comparison::Equal;
9487 
9488   if (Cand1CPUDisp && !Cand2CPUDisp)
9489     return Comparison::Better;
9490   if (Cand2CPUDisp && !Cand1CPUDisp)
9491     return Comparison::Worse;
9492 
9493   if (Cand1CPUSpec && Cand2CPUSpec) {
9494     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9495       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9496                  ? Comparison::Better
9497                  : Comparison::Worse;
9498 
9499     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9500         FirstDiff = std::mismatch(
9501             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9502             Cand2CPUSpec->cpus_begin(),
9503             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9504               return LHS->getName() == RHS->getName();
9505             });
9506 
9507     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9508            "Two different cpu-specific versions should not have the same "
9509            "identifier list, otherwise they'd be the same decl!");
9510     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9511                ? Comparison::Better
9512                : Comparison::Worse;
9513   }
9514   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9515 }
9516 
9517 /// Compute the type of the implicit object parameter for the given function,
9518 /// if any. Returns None if there is no implicit object parameter, and a null
9519 /// QualType if there is a 'matches anything' implicit object parameter.
9520 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9521                                                      const FunctionDecl *F) {
9522   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9523     return llvm::None;
9524 
9525   auto *M = cast<CXXMethodDecl>(F);
9526   // Static member functions' object parameters match all types.
9527   if (M->isStatic())
9528     return QualType();
9529 
9530   QualType T = M->getThisObjectType();
9531   if (M->getRefQualifier() == RQ_RValue)
9532     return Context.getRValueReferenceType(T);
9533   return Context.getLValueReferenceType(T);
9534 }
9535 
9536 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9537                                    const FunctionDecl *F2, unsigned NumParams) {
9538   if (declaresSameEntity(F1, F2))
9539     return true;
9540 
9541   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9542     if (First) {
9543       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9544         return *T;
9545     }
9546     assert(I < F->getNumParams());
9547     return F->getParamDecl(I++)->getType();
9548   };
9549 
9550   unsigned I1 = 0, I2 = 0;
9551   for (unsigned I = 0; I != NumParams; ++I) {
9552     QualType T1 = NextParam(F1, I1, I == 0);
9553     QualType T2 = NextParam(F2, I2, I == 0);
9554     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9555       return false;
9556   }
9557   return true;
9558 }
9559 
9560 /// isBetterOverloadCandidate - Determines whether the first overload
9561 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9562 bool clang::isBetterOverloadCandidate(
9563     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9564     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9565   // Define viable functions to be better candidates than non-viable
9566   // functions.
9567   if (!Cand2.Viable)
9568     return Cand1.Viable;
9569   else if (!Cand1.Viable)
9570     return false;
9571 
9572   // C++ [over.match.best]p1:
9573   //
9574   //   -- if F is a static member function, ICS1(F) is defined such
9575   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9576   //      any function G, and, symmetrically, ICS1(G) is neither
9577   //      better nor worse than ICS1(F).
9578   unsigned StartArg = 0;
9579   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9580     StartArg = 1;
9581 
9582   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9583     // We don't allow incompatible pointer conversions in C++.
9584     if (!S.getLangOpts().CPlusPlus)
9585       return ICS.isStandard() &&
9586              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9587 
9588     // The only ill-formed conversion we allow in C++ is the string literal to
9589     // char* conversion, which is only considered ill-formed after C++11.
9590     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9591            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9592   };
9593 
9594   // Define functions that don't require ill-formed conversions for a given
9595   // argument to be better candidates than functions that do.
9596   unsigned NumArgs = Cand1.Conversions.size();
9597   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9598   bool HasBetterConversion = false;
9599   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9600     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9601     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9602     if (Cand1Bad != Cand2Bad) {
9603       if (Cand1Bad)
9604         return false;
9605       HasBetterConversion = true;
9606     }
9607   }
9608 
9609   if (HasBetterConversion)
9610     return true;
9611 
9612   // C++ [over.match.best]p1:
9613   //   A viable function F1 is defined to be a better function than another
9614   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9615   //   conversion sequence than ICSi(F2), and then...
9616   bool HasWorseConversion = false;
9617   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9618     switch (CompareImplicitConversionSequences(S, Loc,
9619                                                Cand1.Conversions[ArgIdx],
9620                                                Cand2.Conversions[ArgIdx])) {
9621     case ImplicitConversionSequence::Better:
9622       // Cand1 has a better conversion sequence.
9623       HasBetterConversion = true;
9624       break;
9625 
9626     case ImplicitConversionSequence::Worse:
9627       if (Cand1.Function && Cand2.Function &&
9628           Cand1.isReversed() != Cand2.isReversed() &&
9629           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9630                                  NumArgs)) {
9631         // Work around large-scale breakage caused by considering reversed
9632         // forms of operator== in C++20:
9633         //
9634         // When comparing a function against a reversed function with the same
9635         // parameter types, if we have a better conversion for one argument and
9636         // a worse conversion for the other, the implicit conversion sequences
9637         // are treated as being equally good.
9638         //
9639         // This prevents a comparison function from being considered ambiguous
9640         // with a reversed form that is written in the same way.
9641         //
9642         // We diagnose this as an extension from CreateOverloadedBinOp.
9643         HasWorseConversion = true;
9644         break;
9645       }
9646 
9647       // Cand1 can't be better than Cand2.
9648       return false;
9649 
9650     case ImplicitConversionSequence::Indistinguishable:
9651       // Do nothing.
9652       break;
9653     }
9654   }
9655 
9656   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9657   //       ICSj(F2), or, if not that,
9658   if (HasBetterConversion && !HasWorseConversion)
9659     return true;
9660 
9661   //   -- the context is an initialization by user-defined conversion
9662   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9663   //      from the return type of F1 to the destination type (i.e.,
9664   //      the type of the entity being initialized) is a better
9665   //      conversion sequence than the standard conversion sequence
9666   //      from the return type of F2 to the destination type.
9667   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9668       Cand1.Function && Cand2.Function &&
9669       isa<CXXConversionDecl>(Cand1.Function) &&
9670       isa<CXXConversionDecl>(Cand2.Function)) {
9671     // First check whether we prefer one of the conversion functions over the
9672     // other. This only distinguishes the results in non-standard, extension
9673     // cases such as the conversion from a lambda closure type to a function
9674     // pointer or block.
9675     ImplicitConversionSequence::CompareKind Result =
9676         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9677     if (Result == ImplicitConversionSequence::Indistinguishable)
9678       Result = CompareStandardConversionSequences(S, Loc,
9679                                                   Cand1.FinalConversion,
9680                                                   Cand2.FinalConversion);
9681 
9682     if (Result != ImplicitConversionSequence::Indistinguishable)
9683       return Result == ImplicitConversionSequence::Better;
9684 
9685     // FIXME: Compare kind of reference binding if conversion functions
9686     // convert to a reference type used in direct reference binding, per
9687     // C++14 [over.match.best]p1 section 2 bullet 3.
9688   }
9689 
9690   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9691   // as combined with the resolution to CWG issue 243.
9692   //
9693   // When the context is initialization by constructor ([over.match.ctor] or
9694   // either phase of [over.match.list]), a constructor is preferred over
9695   // a conversion function.
9696   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9697       Cand1.Function && Cand2.Function &&
9698       isa<CXXConstructorDecl>(Cand1.Function) !=
9699           isa<CXXConstructorDecl>(Cand2.Function))
9700     return isa<CXXConstructorDecl>(Cand1.Function);
9701 
9702   //    -- F1 is a non-template function and F2 is a function template
9703   //       specialization, or, if not that,
9704   bool Cand1IsSpecialization = Cand1.Function &&
9705                                Cand1.Function->getPrimaryTemplate();
9706   bool Cand2IsSpecialization = Cand2.Function &&
9707                                Cand2.Function->getPrimaryTemplate();
9708   if (Cand1IsSpecialization != Cand2IsSpecialization)
9709     return Cand2IsSpecialization;
9710 
9711   //   -- F1 and F2 are function template specializations, and the function
9712   //      template for F1 is more specialized than the template for F2
9713   //      according to the partial ordering rules described in 14.5.5.2, or,
9714   //      if not that,
9715   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9716     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9717             Cand1.Function->getPrimaryTemplate(),
9718             Cand2.Function->getPrimaryTemplate(), Loc,
9719             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9720                                                    : TPOC_Call,
9721             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9722             Cand1.isReversed() ^ Cand2.isReversed()))
9723       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9724   }
9725 
9726   //   -— F1 and F2 are non-template functions with the same
9727   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9728   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9729       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9730       Cand2.Function->hasPrototype()) {
9731     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9732     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9733     if (PT1->getNumParams() == PT2->getNumParams() &&
9734         PT1->isVariadic() == PT2->isVariadic() &&
9735         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9736       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9737       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9738       if (RC1 && RC2) {
9739         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9740         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9741                                      {RC2}, AtLeastAsConstrained1) ||
9742             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9743                                      {RC1}, AtLeastAsConstrained2))
9744           return false;
9745         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9746           return AtLeastAsConstrained1;
9747       } else if (RC1 || RC2) {
9748         return RC1 != nullptr;
9749       }
9750     }
9751   }
9752 
9753   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9754   //      class B of D, and for all arguments the corresponding parameters of
9755   //      F1 and F2 have the same type.
9756   // FIXME: Implement the "all parameters have the same type" check.
9757   bool Cand1IsInherited =
9758       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9759   bool Cand2IsInherited =
9760       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9761   if (Cand1IsInherited != Cand2IsInherited)
9762     return Cand2IsInherited;
9763   else if (Cand1IsInherited) {
9764     assert(Cand2IsInherited);
9765     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9766     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9767     if (Cand1Class->isDerivedFrom(Cand2Class))
9768       return true;
9769     if (Cand2Class->isDerivedFrom(Cand1Class))
9770       return false;
9771     // Inherited from sibling base classes: still ambiguous.
9772   }
9773 
9774   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9775   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9776   //      with reversed order of parameters and F1 is not
9777   //
9778   // We rank reversed + different operator as worse than just reversed, but
9779   // that comparison can never happen, because we only consider reversing for
9780   // the maximally-rewritten operator (== or <=>).
9781   if (Cand1.RewriteKind != Cand2.RewriteKind)
9782     return Cand1.RewriteKind < Cand2.RewriteKind;
9783 
9784   // Check C++17 tie-breakers for deduction guides.
9785   {
9786     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9787     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9788     if (Guide1 && Guide2) {
9789       //  -- F1 is generated from a deduction-guide and F2 is not
9790       if (Guide1->isImplicit() != Guide2->isImplicit())
9791         return Guide2->isImplicit();
9792 
9793       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9794       if (Guide1->isCopyDeductionCandidate())
9795         return true;
9796     }
9797   }
9798 
9799   // Check for enable_if value-based overload resolution.
9800   if (Cand1.Function && Cand2.Function) {
9801     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9802     if (Cmp != Comparison::Equal)
9803       return Cmp == Comparison::Better;
9804   }
9805 
9806   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9807     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9808     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9809            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9810   }
9811 
9812   bool HasPS1 = Cand1.Function != nullptr &&
9813                 functionHasPassObjectSizeParams(Cand1.Function);
9814   bool HasPS2 = Cand2.Function != nullptr &&
9815                 functionHasPassObjectSizeParams(Cand2.Function);
9816   if (HasPS1 != HasPS2 && HasPS1)
9817     return true;
9818 
9819   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9820   return MV == Comparison::Better;
9821 }
9822 
9823 /// Determine whether two declarations are "equivalent" for the purposes of
9824 /// name lookup and overload resolution. This applies when the same internal/no
9825 /// linkage entity is defined by two modules (probably by textually including
9826 /// the same header). In such a case, we don't consider the declarations to
9827 /// declare the same entity, but we also don't want lookups with both
9828 /// declarations visible to be ambiguous in some cases (this happens when using
9829 /// a modularized libstdc++).
9830 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9831                                                   const NamedDecl *B) {
9832   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9833   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9834   if (!VA || !VB)
9835     return false;
9836 
9837   // The declarations must be declaring the same name as an internal linkage
9838   // entity in different modules.
9839   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9840           VB->getDeclContext()->getRedeclContext()) ||
9841       getOwningModule(VA) == getOwningModule(VB) ||
9842       VA->isExternallyVisible() || VB->isExternallyVisible())
9843     return false;
9844 
9845   // Check that the declarations appear to be equivalent.
9846   //
9847   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9848   // For constants and functions, we should check the initializer or body is
9849   // the same. For non-constant variables, we shouldn't allow it at all.
9850   if (Context.hasSameType(VA->getType(), VB->getType()))
9851     return true;
9852 
9853   // Enum constants within unnamed enumerations will have different types, but
9854   // may still be similar enough to be interchangeable for our purposes.
9855   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9856     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9857       // Only handle anonymous enums. If the enumerations were named and
9858       // equivalent, they would have been merged to the same type.
9859       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9860       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9861       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9862           !Context.hasSameType(EnumA->getIntegerType(),
9863                                EnumB->getIntegerType()))
9864         return false;
9865       // Allow this only if the value is the same for both enumerators.
9866       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9867     }
9868   }
9869 
9870   // Nothing else is sufficiently similar.
9871   return false;
9872 }
9873 
9874 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9875     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9876   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9877 
9878   Module *M = getOwningModule(D);
9879   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9880       << !M << (M ? M->getFullModuleName() : "");
9881 
9882   for (auto *E : Equiv) {
9883     Module *M = getOwningModule(E);
9884     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9885         << !M << (M ? M->getFullModuleName() : "");
9886   }
9887 }
9888 
9889 /// Computes the best viable function (C++ 13.3.3)
9890 /// within an overload candidate set.
9891 ///
9892 /// \param Loc The location of the function name (or operator symbol) for
9893 /// which overload resolution occurs.
9894 ///
9895 /// \param Best If overload resolution was successful or found a deleted
9896 /// function, \p Best points to the candidate function found.
9897 ///
9898 /// \returns The result of overload resolution.
9899 OverloadingResult
9900 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9901                                          iterator &Best) {
9902   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9903   std::transform(begin(), end(), std::back_inserter(Candidates),
9904                  [](OverloadCandidate &Cand) { return &Cand; });
9905 
9906   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9907   // are accepted by both clang and NVCC. However, during a particular
9908   // compilation mode only one call variant is viable. We need to
9909   // exclude non-viable overload candidates from consideration based
9910   // only on their host/device attributes. Specifically, if one
9911   // candidate call is WrongSide and the other is SameSide, we ignore
9912   // the WrongSide candidate.
9913   if (S.getLangOpts().CUDA) {
9914     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9915     bool ContainsSameSideCandidate =
9916         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9917           // Check viable function only.
9918           return Cand->Viable && Cand->Function &&
9919                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9920                      Sema::CFP_SameSide;
9921         });
9922     if (ContainsSameSideCandidate) {
9923       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9924         // Check viable function only to avoid unnecessary data copying/moving.
9925         return Cand->Viable && Cand->Function &&
9926                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9927                    Sema::CFP_WrongSide;
9928       };
9929       llvm::erase_if(Candidates, IsWrongSideCandidate);
9930     }
9931   }
9932 
9933   // Find the best viable function.
9934   Best = end();
9935   for (auto *Cand : Candidates) {
9936     Cand->Best = false;
9937     if (Cand->Viable)
9938       if (Best == end() ||
9939           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9940         Best = Cand;
9941   }
9942 
9943   // If we didn't find any viable functions, abort.
9944   if (Best == end())
9945     return OR_No_Viable_Function;
9946 
9947   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9948 
9949   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9950   PendingBest.push_back(&*Best);
9951   Best->Best = true;
9952 
9953   // Make sure that this function is better than every other viable
9954   // function. If not, we have an ambiguity.
9955   while (!PendingBest.empty()) {
9956     auto *Curr = PendingBest.pop_back_val();
9957     for (auto *Cand : Candidates) {
9958       if (Cand->Viable && !Cand->Best &&
9959           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9960         PendingBest.push_back(Cand);
9961         Cand->Best = true;
9962 
9963         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9964                                                      Curr->Function))
9965           EquivalentCands.push_back(Cand->Function);
9966         else
9967           Best = end();
9968       }
9969     }
9970   }
9971 
9972   // If we found more than one best candidate, this is ambiguous.
9973   if (Best == end())
9974     return OR_Ambiguous;
9975 
9976   // Best is the best viable function.
9977   if (Best->Function && Best->Function->isDeleted())
9978     return OR_Deleted;
9979 
9980   if (!EquivalentCands.empty())
9981     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9982                                                     EquivalentCands);
9983 
9984   return OR_Success;
9985 }
9986 
9987 namespace {
9988 
9989 enum OverloadCandidateKind {
9990   oc_function,
9991   oc_method,
9992   oc_reversed_binary_operator,
9993   oc_constructor,
9994   oc_implicit_default_constructor,
9995   oc_implicit_copy_constructor,
9996   oc_implicit_move_constructor,
9997   oc_implicit_copy_assignment,
9998   oc_implicit_move_assignment,
9999   oc_implicit_equality_comparison,
10000   oc_inherited_constructor
10001 };
10002 
10003 enum OverloadCandidateSelect {
10004   ocs_non_template,
10005   ocs_template,
10006   ocs_described_template,
10007 };
10008 
10009 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10010 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10011                           OverloadCandidateRewriteKind CRK,
10012                           std::string &Description) {
10013 
10014   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10015   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10016     isTemplate = true;
10017     Description = S.getTemplateArgumentBindingsText(
10018         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10019   }
10020 
10021   OverloadCandidateSelect Select = [&]() {
10022     if (!Description.empty())
10023       return ocs_described_template;
10024     return isTemplate ? ocs_template : ocs_non_template;
10025   }();
10026 
10027   OverloadCandidateKind Kind = [&]() {
10028     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10029       return oc_implicit_equality_comparison;
10030 
10031     if (CRK & CRK_Reversed)
10032       return oc_reversed_binary_operator;
10033 
10034     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10035       if (!Ctor->isImplicit()) {
10036         if (isa<ConstructorUsingShadowDecl>(Found))
10037           return oc_inherited_constructor;
10038         else
10039           return oc_constructor;
10040       }
10041 
10042       if (Ctor->isDefaultConstructor())
10043         return oc_implicit_default_constructor;
10044 
10045       if (Ctor->isMoveConstructor())
10046         return oc_implicit_move_constructor;
10047 
10048       assert(Ctor->isCopyConstructor() &&
10049              "unexpected sort of implicit constructor");
10050       return oc_implicit_copy_constructor;
10051     }
10052 
10053     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10054       // This actually gets spelled 'candidate function' for now, but
10055       // it doesn't hurt to split it out.
10056       if (!Meth->isImplicit())
10057         return oc_method;
10058 
10059       if (Meth->isMoveAssignmentOperator())
10060         return oc_implicit_move_assignment;
10061 
10062       if (Meth->isCopyAssignmentOperator())
10063         return oc_implicit_copy_assignment;
10064 
10065       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10066       return oc_method;
10067     }
10068 
10069     return oc_function;
10070   }();
10071 
10072   return std::make_pair(Kind, Select);
10073 }
10074 
10075 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10076   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10077   // set.
10078   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10079     S.Diag(FoundDecl->getLocation(),
10080            diag::note_ovl_candidate_inherited_constructor)
10081       << Shadow->getNominatedBaseClass();
10082 }
10083 
10084 } // end anonymous namespace
10085 
10086 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10087                                     const FunctionDecl *FD) {
10088   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10089     bool AlwaysTrue;
10090     if (EnableIf->getCond()->isValueDependent() ||
10091         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10092       return false;
10093     if (!AlwaysTrue)
10094       return false;
10095   }
10096   return true;
10097 }
10098 
10099 /// Returns true if we can take the address of the function.
10100 ///
10101 /// \param Complain - If true, we'll emit a diagnostic
10102 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10103 ///   we in overload resolution?
10104 /// \param Loc - The location of the statement we're complaining about. Ignored
10105 ///   if we're not complaining, or if we're in overload resolution.
10106 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10107                                               bool Complain,
10108                                               bool InOverloadResolution,
10109                                               SourceLocation Loc) {
10110   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10111     if (Complain) {
10112       if (InOverloadResolution)
10113         S.Diag(FD->getBeginLoc(),
10114                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10115       else
10116         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10117     }
10118     return false;
10119   }
10120 
10121   if (FD->getTrailingRequiresClause()) {
10122     ConstraintSatisfaction Satisfaction;
10123     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10124       return false;
10125     if (!Satisfaction.IsSatisfied) {
10126       if (Complain) {
10127         if (InOverloadResolution)
10128           S.Diag(FD->getBeginLoc(),
10129                  diag::note_ovl_candidate_unsatisfied_constraints);
10130         else
10131           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10132               << FD;
10133         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10134       }
10135       return false;
10136     }
10137   }
10138 
10139   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10140     return P->hasAttr<PassObjectSizeAttr>();
10141   });
10142   if (I == FD->param_end())
10143     return true;
10144 
10145   if (Complain) {
10146     // Add one to ParamNo because it's user-facing
10147     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10148     if (InOverloadResolution)
10149       S.Diag(FD->getLocation(),
10150              diag::note_ovl_candidate_has_pass_object_size_params)
10151           << ParamNo;
10152     else
10153       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10154           << FD << ParamNo;
10155   }
10156   return false;
10157 }
10158 
10159 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10160                                                const FunctionDecl *FD) {
10161   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10162                                            /*InOverloadResolution=*/true,
10163                                            /*Loc=*/SourceLocation());
10164 }
10165 
10166 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10167                                              bool Complain,
10168                                              SourceLocation Loc) {
10169   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10170                                              /*InOverloadResolution=*/false,
10171                                              Loc);
10172 }
10173 
10174 // Notes the location of an overload candidate.
10175 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10176                                  OverloadCandidateRewriteKind RewriteKind,
10177                                  QualType DestType, bool TakingAddress) {
10178   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10179     return;
10180   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10181       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10182     return;
10183 
10184   std::string FnDesc;
10185   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10186       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10187   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10188                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10189                          << Fn << FnDesc;
10190 
10191   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10192   Diag(Fn->getLocation(), PD);
10193   MaybeEmitInheritedConstructorNote(*this, Found);
10194 }
10195 
10196 static void
10197 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10198   // Perhaps the ambiguity was caused by two atomic constraints that are
10199   // 'identical' but not equivalent:
10200   //
10201   // void foo() requires (sizeof(T) > 4) { } // #1
10202   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10203   //
10204   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10205   // #2 to subsume #1, but these constraint are not considered equivalent
10206   // according to the subsumption rules because they are not the same
10207   // source-level construct. This behavior is quite confusing and we should try
10208   // to help the user figure out what happened.
10209 
10210   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10211   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10212   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10213     if (!I->Function)
10214       continue;
10215     SmallVector<const Expr *, 3> AC;
10216     if (auto *Template = I->Function->getPrimaryTemplate())
10217       Template->getAssociatedConstraints(AC);
10218     else
10219       I->Function->getAssociatedConstraints(AC);
10220     if (AC.empty())
10221       continue;
10222     if (FirstCand == nullptr) {
10223       FirstCand = I->Function;
10224       FirstAC = AC;
10225     } else if (SecondCand == nullptr) {
10226       SecondCand = I->Function;
10227       SecondAC = AC;
10228     } else {
10229       // We have more than one pair of constrained functions - this check is
10230       // expensive and we'd rather not try to diagnose it.
10231       return;
10232     }
10233   }
10234   if (!SecondCand)
10235     return;
10236   // The diagnostic can only happen if there are associated constraints on
10237   // both sides (there needs to be some identical atomic constraint).
10238   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10239                                                       SecondCand, SecondAC))
10240     // Just show the user one diagnostic, they'll probably figure it out
10241     // from here.
10242     return;
10243 }
10244 
10245 // Notes the location of all overload candidates designated through
10246 // OverloadedExpr
10247 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10248                                      bool TakingAddress) {
10249   assert(OverloadedExpr->getType() == Context.OverloadTy);
10250 
10251   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10252   OverloadExpr *OvlExpr = Ovl.Expression;
10253 
10254   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10255                             IEnd = OvlExpr->decls_end();
10256        I != IEnd; ++I) {
10257     if (FunctionTemplateDecl *FunTmpl =
10258                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10259       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10260                             TakingAddress);
10261     } else if (FunctionDecl *Fun
10262                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10263       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10264     }
10265   }
10266 }
10267 
10268 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10269 /// "lead" diagnostic; it will be given two arguments, the source and
10270 /// target types of the conversion.
10271 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10272                                  Sema &S,
10273                                  SourceLocation CaretLoc,
10274                                  const PartialDiagnostic &PDiag) const {
10275   S.Diag(CaretLoc, PDiag)
10276     << Ambiguous.getFromType() << Ambiguous.getToType();
10277   // FIXME: The note limiting machinery is borrowed from
10278   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10279   // refactoring here.
10280   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10281   unsigned CandsShown = 0;
10282   AmbiguousConversionSequence::const_iterator I, E;
10283   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10284     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10285       break;
10286     ++CandsShown;
10287     S.NoteOverloadCandidate(I->first, I->second);
10288   }
10289   if (I != E)
10290     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10291 }
10292 
10293 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10294                                   unsigned I, bool TakingCandidateAddress) {
10295   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10296   assert(Conv.isBad());
10297   assert(Cand->Function && "for now, candidate must be a function");
10298   FunctionDecl *Fn = Cand->Function;
10299 
10300   // There's a conversion slot for the object argument if this is a
10301   // non-constructor method.  Note that 'I' corresponds the
10302   // conversion-slot index.
10303   bool isObjectArgument = false;
10304   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10305     if (I == 0)
10306       isObjectArgument = true;
10307     else
10308       I--;
10309   }
10310 
10311   std::string FnDesc;
10312   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10313       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10314                                 FnDesc);
10315 
10316   Expr *FromExpr = Conv.Bad.FromExpr;
10317   QualType FromTy = Conv.Bad.getFromType();
10318   QualType ToTy = Conv.Bad.getToType();
10319 
10320   if (FromTy == S.Context.OverloadTy) {
10321     assert(FromExpr && "overload set argument came from implicit argument?");
10322     Expr *E = FromExpr->IgnoreParens();
10323     if (isa<UnaryOperator>(E))
10324       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10325     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10326 
10327     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10328         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10329         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10330         << Name << I + 1;
10331     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10332     return;
10333   }
10334 
10335   // Do some hand-waving analysis to see if the non-viability is due
10336   // to a qualifier mismatch.
10337   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10338   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10339   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10340     CToTy = RT->getPointeeType();
10341   else {
10342     // TODO: detect and diagnose the full richness of const mismatches.
10343     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10344       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10345         CFromTy = FromPT->getPointeeType();
10346         CToTy = ToPT->getPointeeType();
10347       }
10348   }
10349 
10350   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10351       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10352     Qualifiers FromQs = CFromTy.getQualifiers();
10353     Qualifiers ToQs = CToTy.getQualifiers();
10354 
10355     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10356       if (isObjectArgument)
10357         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10358             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10359             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10360             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10361       else
10362         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10363             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10364             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10365             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10366             << ToTy->isReferenceType() << I + 1;
10367       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10368       return;
10369     }
10370 
10371     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10372       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10373           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10374           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10375           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10376           << (unsigned)isObjectArgument << I + 1;
10377       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10378       return;
10379     }
10380 
10381     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10382       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10383           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10384           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10385           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10386           << (unsigned)isObjectArgument << I + 1;
10387       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10388       return;
10389     }
10390 
10391     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10392       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10393           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10394           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10395           << FromQs.hasUnaligned() << I + 1;
10396       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10397       return;
10398     }
10399 
10400     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10401     assert(CVR && "unexpected qualifiers mismatch");
10402 
10403     if (isObjectArgument) {
10404       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10405           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10406           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10407           << (CVR - 1);
10408     } else {
10409       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10410           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10411           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10412           << (CVR - 1) << I + 1;
10413     }
10414     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10415     return;
10416   }
10417 
10418   // Special diagnostic for failure to convert an initializer list, since
10419   // telling the user that it has type void is not useful.
10420   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10421     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10422         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10423         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10424         << ToTy << (unsigned)isObjectArgument << I + 1;
10425     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10426     return;
10427   }
10428 
10429   // Diagnose references or pointers to incomplete types differently,
10430   // since it's far from impossible that the incompleteness triggered
10431   // the failure.
10432   QualType TempFromTy = FromTy.getNonReferenceType();
10433   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10434     TempFromTy = PTy->getPointeeType();
10435   if (TempFromTy->isIncompleteType()) {
10436     // Emit the generic diagnostic and, optionally, add the hints to it.
10437     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10438         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10439         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10440         << ToTy << (unsigned)isObjectArgument << I + 1
10441         << (unsigned)(Cand->Fix.Kind);
10442 
10443     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10444     return;
10445   }
10446 
10447   // Diagnose base -> derived pointer conversions.
10448   unsigned BaseToDerivedConversion = 0;
10449   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10450     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10451       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10452                                                FromPtrTy->getPointeeType()) &&
10453           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10454           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10455           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10456                           FromPtrTy->getPointeeType()))
10457         BaseToDerivedConversion = 1;
10458     }
10459   } else if (const ObjCObjectPointerType *FromPtrTy
10460                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10461     if (const ObjCObjectPointerType *ToPtrTy
10462                                         = ToTy->getAs<ObjCObjectPointerType>())
10463       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10464         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10465           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10466                                                 FromPtrTy->getPointeeType()) &&
10467               FromIface->isSuperClassOf(ToIface))
10468             BaseToDerivedConversion = 2;
10469   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10470     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10471         !FromTy->isIncompleteType() &&
10472         !ToRefTy->getPointeeType()->isIncompleteType() &&
10473         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10474       BaseToDerivedConversion = 3;
10475     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10476                ToTy.getNonReferenceType().getCanonicalType() ==
10477                FromTy.getNonReferenceType().getCanonicalType()) {
10478       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10479           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10480           << (unsigned)isObjectArgument << I + 1
10481           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10482       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10483       return;
10484     }
10485   }
10486 
10487   if (BaseToDerivedConversion) {
10488     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10489         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10490         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10491         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10492     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10493     return;
10494   }
10495 
10496   if (isa<ObjCObjectPointerType>(CFromTy) &&
10497       isa<PointerType>(CToTy)) {
10498       Qualifiers FromQs = CFromTy.getQualifiers();
10499       Qualifiers ToQs = CToTy.getQualifiers();
10500       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10501         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10502             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10503             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10504             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10505         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10506         return;
10507       }
10508   }
10509 
10510   if (TakingCandidateAddress &&
10511       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10512     return;
10513 
10514   // Emit the generic diagnostic and, optionally, add the hints to it.
10515   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10516   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10517         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10518         << ToTy << (unsigned)isObjectArgument << I + 1
10519         << (unsigned)(Cand->Fix.Kind);
10520 
10521   // If we can fix the conversion, suggest the FixIts.
10522   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10523        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10524     FDiag << *HI;
10525   S.Diag(Fn->getLocation(), FDiag);
10526 
10527   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10528 }
10529 
10530 /// Additional arity mismatch diagnosis specific to a function overload
10531 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10532 /// over a candidate in any candidate set.
10533 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10534                                unsigned NumArgs) {
10535   FunctionDecl *Fn = Cand->Function;
10536   unsigned MinParams = Fn->getMinRequiredArguments();
10537 
10538   // With invalid overloaded operators, it's possible that we think we
10539   // have an arity mismatch when in fact it looks like we have the
10540   // right number of arguments, because only overloaded operators have
10541   // the weird behavior of overloading member and non-member functions.
10542   // Just don't report anything.
10543   if (Fn->isInvalidDecl() &&
10544       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10545     return true;
10546 
10547   if (NumArgs < MinParams) {
10548     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10549            (Cand->FailureKind == ovl_fail_bad_deduction &&
10550             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10551   } else {
10552     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10553            (Cand->FailureKind == ovl_fail_bad_deduction &&
10554             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10555   }
10556 
10557   return false;
10558 }
10559 
10560 /// General arity mismatch diagnosis over a candidate in a candidate set.
10561 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10562                                   unsigned NumFormalArgs) {
10563   assert(isa<FunctionDecl>(D) &&
10564       "The templated declaration should at least be a function"
10565       " when diagnosing bad template argument deduction due to too many"
10566       " or too few arguments");
10567 
10568   FunctionDecl *Fn = cast<FunctionDecl>(D);
10569 
10570   // TODO: treat calls to a missing default constructor as a special case
10571   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10572   unsigned MinParams = Fn->getMinRequiredArguments();
10573 
10574   // at least / at most / exactly
10575   unsigned mode, modeCount;
10576   if (NumFormalArgs < MinParams) {
10577     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10578         FnTy->isTemplateVariadic())
10579       mode = 0; // "at least"
10580     else
10581       mode = 2; // "exactly"
10582     modeCount = MinParams;
10583   } else {
10584     if (MinParams != FnTy->getNumParams())
10585       mode = 1; // "at most"
10586     else
10587       mode = 2; // "exactly"
10588     modeCount = FnTy->getNumParams();
10589   }
10590 
10591   std::string Description;
10592   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10593       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10594 
10595   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10596     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10597         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10598         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10599   else
10600     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10601         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10602         << Description << mode << modeCount << NumFormalArgs;
10603 
10604   MaybeEmitInheritedConstructorNote(S, Found);
10605 }
10606 
10607 /// Arity mismatch diagnosis specific to a function overload candidate.
10608 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10609                                   unsigned NumFormalArgs) {
10610   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10611     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10612 }
10613 
10614 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10615   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10616     return TD;
10617   llvm_unreachable("Unsupported: Getting the described template declaration"
10618                    " for bad deduction diagnosis");
10619 }
10620 
10621 /// Diagnose a failed template-argument deduction.
10622 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10623                                  DeductionFailureInfo &DeductionFailure,
10624                                  unsigned NumArgs,
10625                                  bool TakingCandidateAddress) {
10626   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10627   NamedDecl *ParamD;
10628   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10629   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10630   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10631   switch (DeductionFailure.Result) {
10632   case Sema::TDK_Success:
10633     llvm_unreachable("TDK_success while diagnosing bad deduction");
10634 
10635   case Sema::TDK_Incomplete: {
10636     assert(ParamD && "no parameter found for incomplete deduction result");
10637     S.Diag(Templated->getLocation(),
10638            diag::note_ovl_candidate_incomplete_deduction)
10639         << ParamD->getDeclName();
10640     MaybeEmitInheritedConstructorNote(S, Found);
10641     return;
10642   }
10643 
10644   case Sema::TDK_IncompletePack: {
10645     assert(ParamD && "no parameter found for incomplete deduction result");
10646     S.Diag(Templated->getLocation(),
10647            diag::note_ovl_candidate_incomplete_deduction_pack)
10648         << ParamD->getDeclName()
10649         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10650         << *DeductionFailure.getFirstArg();
10651     MaybeEmitInheritedConstructorNote(S, Found);
10652     return;
10653   }
10654 
10655   case Sema::TDK_Underqualified: {
10656     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10657     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10658 
10659     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10660 
10661     // Param will have been canonicalized, but it should just be a
10662     // qualified version of ParamD, so move the qualifiers to that.
10663     QualifierCollector Qs;
10664     Qs.strip(Param);
10665     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10666     assert(S.Context.hasSameType(Param, NonCanonParam));
10667 
10668     // Arg has also been canonicalized, but there's nothing we can do
10669     // about that.  It also doesn't matter as much, because it won't
10670     // have any template parameters in it (because deduction isn't
10671     // done on dependent types).
10672     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10673 
10674     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10675         << ParamD->getDeclName() << Arg << NonCanonParam;
10676     MaybeEmitInheritedConstructorNote(S, Found);
10677     return;
10678   }
10679 
10680   case Sema::TDK_Inconsistent: {
10681     assert(ParamD && "no parameter found for inconsistent deduction result");
10682     int which = 0;
10683     if (isa<TemplateTypeParmDecl>(ParamD))
10684       which = 0;
10685     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10686       // Deduction might have failed because we deduced arguments of two
10687       // different types for a non-type template parameter.
10688       // FIXME: Use a different TDK value for this.
10689       QualType T1 =
10690           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10691       QualType T2 =
10692           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10693       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10694         S.Diag(Templated->getLocation(),
10695                diag::note_ovl_candidate_inconsistent_deduction_types)
10696           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10697           << *DeductionFailure.getSecondArg() << T2;
10698         MaybeEmitInheritedConstructorNote(S, Found);
10699         return;
10700       }
10701 
10702       which = 1;
10703     } else {
10704       which = 2;
10705     }
10706 
10707     // Tweak the diagnostic if the problem is that we deduced packs of
10708     // different arities. We'll print the actual packs anyway in case that
10709     // includes additional useful information.
10710     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10711         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10712         DeductionFailure.getFirstArg()->pack_size() !=
10713             DeductionFailure.getSecondArg()->pack_size()) {
10714       which = 3;
10715     }
10716 
10717     S.Diag(Templated->getLocation(),
10718            diag::note_ovl_candidate_inconsistent_deduction)
10719         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10720         << *DeductionFailure.getSecondArg();
10721     MaybeEmitInheritedConstructorNote(S, Found);
10722     return;
10723   }
10724 
10725   case Sema::TDK_InvalidExplicitArguments:
10726     assert(ParamD && "no parameter found for invalid explicit arguments");
10727     if (ParamD->getDeclName())
10728       S.Diag(Templated->getLocation(),
10729              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10730           << ParamD->getDeclName();
10731     else {
10732       int index = 0;
10733       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10734         index = TTP->getIndex();
10735       else if (NonTypeTemplateParmDecl *NTTP
10736                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10737         index = NTTP->getIndex();
10738       else
10739         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10740       S.Diag(Templated->getLocation(),
10741              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10742           << (index + 1);
10743     }
10744     MaybeEmitInheritedConstructorNote(S, Found);
10745     return;
10746 
10747   case Sema::TDK_ConstraintsNotSatisfied: {
10748     // Format the template argument list into the argument string.
10749     SmallString<128> TemplateArgString;
10750     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10751     TemplateArgString = " ";
10752     TemplateArgString += S.getTemplateArgumentBindingsText(
10753         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10754     if (TemplateArgString.size() == 1)
10755       TemplateArgString.clear();
10756     S.Diag(Templated->getLocation(),
10757            diag::note_ovl_candidate_unsatisfied_constraints)
10758         << TemplateArgString;
10759 
10760     S.DiagnoseUnsatisfiedConstraint(
10761         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10762     return;
10763   }
10764   case Sema::TDK_TooManyArguments:
10765   case Sema::TDK_TooFewArguments:
10766     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10767     return;
10768 
10769   case Sema::TDK_InstantiationDepth:
10770     S.Diag(Templated->getLocation(),
10771            diag::note_ovl_candidate_instantiation_depth);
10772     MaybeEmitInheritedConstructorNote(S, Found);
10773     return;
10774 
10775   case Sema::TDK_SubstitutionFailure: {
10776     // Format the template argument list into the argument string.
10777     SmallString<128> TemplateArgString;
10778     if (TemplateArgumentList *Args =
10779             DeductionFailure.getTemplateArgumentList()) {
10780       TemplateArgString = " ";
10781       TemplateArgString += S.getTemplateArgumentBindingsText(
10782           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10783       if (TemplateArgString.size() == 1)
10784         TemplateArgString.clear();
10785     }
10786 
10787     // If this candidate was disabled by enable_if, say so.
10788     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10789     if (PDiag && PDiag->second.getDiagID() ==
10790           diag::err_typename_nested_not_found_enable_if) {
10791       // FIXME: Use the source range of the condition, and the fully-qualified
10792       //        name of the enable_if template. These are both present in PDiag.
10793       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10794         << "'enable_if'" << TemplateArgString;
10795       return;
10796     }
10797 
10798     // We found a specific requirement that disabled the enable_if.
10799     if (PDiag && PDiag->second.getDiagID() ==
10800         diag::err_typename_nested_not_found_requirement) {
10801       S.Diag(Templated->getLocation(),
10802              diag::note_ovl_candidate_disabled_by_requirement)
10803         << PDiag->second.getStringArg(0) << TemplateArgString;
10804       return;
10805     }
10806 
10807     // Format the SFINAE diagnostic into the argument string.
10808     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10809     //        formatted message in another diagnostic.
10810     SmallString<128> SFINAEArgString;
10811     SourceRange R;
10812     if (PDiag) {
10813       SFINAEArgString = ": ";
10814       R = SourceRange(PDiag->first, PDiag->first);
10815       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10816     }
10817 
10818     S.Diag(Templated->getLocation(),
10819            diag::note_ovl_candidate_substitution_failure)
10820         << TemplateArgString << SFINAEArgString << R;
10821     MaybeEmitInheritedConstructorNote(S, Found);
10822     return;
10823   }
10824 
10825   case Sema::TDK_DeducedMismatch:
10826   case Sema::TDK_DeducedMismatchNested: {
10827     // Format the template argument list into the argument string.
10828     SmallString<128> TemplateArgString;
10829     if (TemplateArgumentList *Args =
10830             DeductionFailure.getTemplateArgumentList()) {
10831       TemplateArgString = " ";
10832       TemplateArgString += S.getTemplateArgumentBindingsText(
10833           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10834       if (TemplateArgString.size() == 1)
10835         TemplateArgString.clear();
10836     }
10837 
10838     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10839         << (*DeductionFailure.getCallArgIndex() + 1)
10840         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10841         << TemplateArgString
10842         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10843     break;
10844   }
10845 
10846   case Sema::TDK_NonDeducedMismatch: {
10847     // FIXME: Provide a source location to indicate what we couldn't match.
10848     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10849     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10850     if (FirstTA.getKind() == TemplateArgument::Template &&
10851         SecondTA.getKind() == TemplateArgument::Template) {
10852       TemplateName FirstTN = FirstTA.getAsTemplate();
10853       TemplateName SecondTN = SecondTA.getAsTemplate();
10854       if (FirstTN.getKind() == TemplateName::Template &&
10855           SecondTN.getKind() == TemplateName::Template) {
10856         if (FirstTN.getAsTemplateDecl()->getName() ==
10857             SecondTN.getAsTemplateDecl()->getName()) {
10858           // FIXME: This fixes a bad diagnostic where both templates are named
10859           // the same.  This particular case is a bit difficult since:
10860           // 1) It is passed as a string to the diagnostic printer.
10861           // 2) The diagnostic printer only attempts to find a better
10862           //    name for types, not decls.
10863           // Ideally, this should folded into the diagnostic printer.
10864           S.Diag(Templated->getLocation(),
10865                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10866               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10867           return;
10868         }
10869       }
10870     }
10871 
10872     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10873         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10874       return;
10875 
10876     // FIXME: For generic lambda parameters, check if the function is a lambda
10877     // call operator, and if so, emit a prettier and more informative
10878     // diagnostic that mentions 'auto' and lambda in addition to
10879     // (or instead of?) the canonical template type parameters.
10880     S.Diag(Templated->getLocation(),
10881            diag::note_ovl_candidate_non_deduced_mismatch)
10882         << FirstTA << SecondTA;
10883     return;
10884   }
10885   // TODO: diagnose these individually, then kill off
10886   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10887   case Sema::TDK_MiscellaneousDeductionFailure:
10888     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10889     MaybeEmitInheritedConstructorNote(S, Found);
10890     return;
10891   case Sema::TDK_CUDATargetMismatch:
10892     S.Diag(Templated->getLocation(),
10893            diag::note_cuda_ovl_candidate_target_mismatch);
10894     return;
10895   }
10896 }
10897 
10898 /// Diagnose a failed template-argument deduction, for function calls.
10899 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10900                                  unsigned NumArgs,
10901                                  bool TakingCandidateAddress) {
10902   unsigned TDK = Cand->DeductionFailure.Result;
10903   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10904     if (CheckArityMismatch(S, Cand, NumArgs))
10905       return;
10906   }
10907   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10908                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10909 }
10910 
10911 /// CUDA: diagnose an invalid call across targets.
10912 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10913   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10914   FunctionDecl *Callee = Cand->Function;
10915 
10916   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10917                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10918 
10919   std::string FnDesc;
10920   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10921       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10922                                 Cand->getRewriteKind(), FnDesc);
10923 
10924   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10925       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10926       << FnDesc /* Ignored */
10927       << CalleeTarget << CallerTarget;
10928 
10929   // This could be an implicit constructor for which we could not infer the
10930   // target due to a collsion. Diagnose that case.
10931   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10932   if (Meth != nullptr && Meth->isImplicit()) {
10933     CXXRecordDecl *ParentClass = Meth->getParent();
10934     Sema::CXXSpecialMember CSM;
10935 
10936     switch (FnKindPair.first) {
10937     default:
10938       return;
10939     case oc_implicit_default_constructor:
10940       CSM = Sema::CXXDefaultConstructor;
10941       break;
10942     case oc_implicit_copy_constructor:
10943       CSM = Sema::CXXCopyConstructor;
10944       break;
10945     case oc_implicit_move_constructor:
10946       CSM = Sema::CXXMoveConstructor;
10947       break;
10948     case oc_implicit_copy_assignment:
10949       CSM = Sema::CXXCopyAssignment;
10950       break;
10951     case oc_implicit_move_assignment:
10952       CSM = Sema::CXXMoveAssignment;
10953       break;
10954     };
10955 
10956     bool ConstRHS = false;
10957     if (Meth->getNumParams()) {
10958       if (const ReferenceType *RT =
10959               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10960         ConstRHS = RT->getPointeeType().isConstQualified();
10961       }
10962     }
10963 
10964     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10965                                               /* ConstRHS */ ConstRHS,
10966                                               /* Diagnose */ true);
10967   }
10968 }
10969 
10970 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10971   FunctionDecl *Callee = Cand->Function;
10972   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10973 
10974   S.Diag(Callee->getLocation(),
10975          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10976       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10977 }
10978 
10979 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10980   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10981   assert(ES.isExplicit() && "not an explicit candidate");
10982 
10983   unsigned Kind;
10984   switch (Cand->Function->getDeclKind()) {
10985   case Decl::Kind::CXXConstructor:
10986     Kind = 0;
10987     break;
10988   case Decl::Kind::CXXConversion:
10989     Kind = 1;
10990     break;
10991   case Decl::Kind::CXXDeductionGuide:
10992     Kind = Cand->Function->isImplicit() ? 0 : 2;
10993     break;
10994   default:
10995     llvm_unreachable("invalid Decl");
10996   }
10997 
10998   // Note the location of the first (in-class) declaration; a redeclaration
10999   // (particularly an out-of-class definition) will typically lack the
11000   // 'explicit' specifier.
11001   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11002   FunctionDecl *First = Cand->Function->getFirstDecl();
11003   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11004     First = Pattern->getFirstDecl();
11005 
11006   S.Diag(First->getLocation(),
11007          diag::note_ovl_candidate_explicit)
11008       << Kind << (ES.getExpr() ? 1 : 0)
11009       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11010 }
11011 
11012 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
11013   FunctionDecl *Callee = Cand->Function;
11014 
11015   S.Diag(Callee->getLocation(),
11016          diag::note_ovl_candidate_disabled_by_extension)
11017     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
11018 }
11019 
11020 /// Generates a 'note' diagnostic for an overload candidate.  We've
11021 /// already generated a primary error at the call site.
11022 ///
11023 /// It really does need to be a single diagnostic with its caret
11024 /// pointed at the candidate declaration.  Yes, this creates some
11025 /// major challenges of technical writing.  Yes, this makes pointing
11026 /// out problems with specific arguments quite awkward.  It's still
11027 /// better than generating twenty screens of text for every failed
11028 /// overload.
11029 ///
11030 /// It would be great to be able to express per-candidate problems
11031 /// more richly for those diagnostic clients that cared, but we'd
11032 /// still have to be just as careful with the default diagnostics.
11033 /// \param CtorDestAS Addr space of object being constructed (for ctor
11034 /// candidates only).
11035 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11036                                   unsigned NumArgs,
11037                                   bool TakingCandidateAddress,
11038                                   LangAS CtorDestAS = LangAS::Default) {
11039   FunctionDecl *Fn = Cand->Function;
11040 
11041   // Note deleted candidates, but only if they're viable.
11042   if (Cand->Viable) {
11043     if (Fn->isDeleted()) {
11044       std::string FnDesc;
11045       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11046           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11047                                     Cand->getRewriteKind(), FnDesc);
11048 
11049       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11050           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11051           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11052       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11053       return;
11054     }
11055 
11056     // We don't really have anything else to say about viable candidates.
11057     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11058     return;
11059   }
11060 
11061   switch (Cand->FailureKind) {
11062   case ovl_fail_too_many_arguments:
11063   case ovl_fail_too_few_arguments:
11064     return DiagnoseArityMismatch(S, Cand, NumArgs);
11065 
11066   case ovl_fail_bad_deduction:
11067     return DiagnoseBadDeduction(S, Cand, NumArgs,
11068                                 TakingCandidateAddress);
11069 
11070   case ovl_fail_illegal_constructor: {
11071     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11072       << (Fn->getPrimaryTemplate() ? 1 : 0);
11073     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11074     return;
11075   }
11076 
11077   case ovl_fail_object_addrspace_mismatch: {
11078     Qualifiers QualsForPrinting;
11079     QualsForPrinting.setAddressSpace(CtorDestAS);
11080     S.Diag(Fn->getLocation(),
11081            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11082         << QualsForPrinting;
11083     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11084     return;
11085   }
11086 
11087   case ovl_fail_trivial_conversion:
11088   case ovl_fail_bad_final_conversion:
11089   case ovl_fail_final_conversion_not_exact:
11090     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11091 
11092   case ovl_fail_bad_conversion: {
11093     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11094     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11095       if (Cand->Conversions[I].isBad())
11096         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11097 
11098     // FIXME: this currently happens when we're called from SemaInit
11099     // when user-conversion overload fails.  Figure out how to handle
11100     // those conditions and diagnose them well.
11101     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11102   }
11103 
11104   case ovl_fail_bad_target:
11105     return DiagnoseBadTarget(S, Cand);
11106 
11107   case ovl_fail_enable_if:
11108     return DiagnoseFailedEnableIfAttr(S, Cand);
11109 
11110   case ovl_fail_explicit:
11111     return DiagnoseFailedExplicitSpec(S, Cand);
11112 
11113   case ovl_fail_ext_disabled:
11114     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11115 
11116   case ovl_fail_inhctor_slice:
11117     // It's generally not interesting to note copy/move constructors here.
11118     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11119       return;
11120     S.Diag(Fn->getLocation(),
11121            diag::note_ovl_candidate_inherited_constructor_slice)
11122       << (Fn->getPrimaryTemplate() ? 1 : 0)
11123       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11124     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11125     return;
11126 
11127   case ovl_fail_addr_not_available: {
11128     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11129     (void)Available;
11130     assert(!Available);
11131     break;
11132   }
11133   case ovl_non_default_multiversion_function:
11134     // Do nothing, these should simply be ignored.
11135     break;
11136 
11137   case ovl_fail_constraints_not_satisfied: {
11138     std::string FnDesc;
11139     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11140         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11141                                   Cand->getRewriteKind(), FnDesc);
11142 
11143     S.Diag(Fn->getLocation(),
11144            diag::note_ovl_candidate_constraints_not_satisfied)
11145         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11146         << FnDesc /* Ignored */;
11147     ConstraintSatisfaction Satisfaction;
11148     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11149       break;
11150     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11151   }
11152   }
11153 }
11154 
11155 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11156   // Desugar the type of the surrogate down to a function type,
11157   // retaining as many typedefs as possible while still showing
11158   // the function type (and, therefore, its parameter types).
11159   QualType FnType = Cand->Surrogate->getConversionType();
11160   bool isLValueReference = false;
11161   bool isRValueReference = false;
11162   bool isPointer = false;
11163   if (const LValueReferenceType *FnTypeRef =
11164         FnType->getAs<LValueReferenceType>()) {
11165     FnType = FnTypeRef->getPointeeType();
11166     isLValueReference = true;
11167   } else if (const RValueReferenceType *FnTypeRef =
11168                FnType->getAs<RValueReferenceType>()) {
11169     FnType = FnTypeRef->getPointeeType();
11170     isRValueReference = true;
11171   }
11172   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11173     FnType = FnTypePtr->getPointeeType();
11174     isPointer = true;
11175   }
11176   // Desugar down to a function type.
11177   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11178   // Reconstruct the pointer/reference as appropriate.
11179   if (isPointer) FnType = S.Context.getPointerType(FnType);
11180   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11181   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11182 
11183   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11184     << FnType;
11185 }
11186 
11187 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11188                                          SourceLocation OpLoc,
11189                                          OverloadCandidate *Cand) {
11190   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11191   std::string TypeStr("operator");
11192   TypeStr += Opc;
11193   TypeStr += "(";
11194   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11195   if (Cand->Conversions.size() == 1) {
11196     TypeStr += ")";
11197     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11198   } else {
11199     TypeStr += ", ";
11200     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11201     TypeStr += ")";
11202     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11203   }
11204 }
11205 
11206 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11207                                          OverloadCandidate *Cand) {
11208   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11209     if (ICS.isBad()) break; // all meaningless after first invalid
11210     if (!ICS.isAmbiguous()) continue;
11211 
11212     ICS.DiagnoseAmbiguousConversion(
11213         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11214   }
11215 }
11216 
11217 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11218   if (Cand->Function)
11219     return Cand->Function->getLocation();
11220   if (Cand->IsSurrogate)
11221     return Cand->Surrogate->getLocation();
11222   return SourceLocation();
11223 }
11224 
11225 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11226   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11227   case Sema::TDK_Success:
11228   case Sema::TDK_NonDependentConversionFailure:
11229     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11230 
11231   case Sema::TDK_Invalid:
11232   case Sema::TDK_Incomplete:
11233   case Sema::TDK_IncompletePack:
11234     return 1;
11235 
11236   case Sema::TDK_Underqualified:
11237   case Sema::TDK_Inconsistent:
11238     return 2;
11239 
11240   case Sema::TDK_SubstitutionFailure:
11241   case Sema::TDK_DeducedMismatch:
11242   case Sema::TDK_ConstraintsNotSatisfied:
11243   case Sema::TDK_DeducedMismatchNested:
11244   case Sema::TDK_NonDeducedMismatch:
11245   case Sema::TDK_MiscellaneousDeductionFailure:
11246   case Sema::TDK_CUDATargetMismatch:
11247     return 3;
11248 
11249   case Sema::TDK_InstantiationDepth:
11250     return 4;
11251 
11252   case Sema::TDK_InvalidExplicitArguments:
11253     return 5;
11254 
11255   case Sema::TDK_TooManyArguments:
11256   case Sema::TDK_TooFewArguments:
11257     return 6;
11258   }
11259   llvm_unreachable("Unhandled deduction result");
11260 }
11261 
11262 namespace {
11263 struct CompareOverloadCandidatesForDisplay {
11264   Sema &S;
11265   SourceLocation Loc;
11266   size_t NumArgs;
11267   OverloadCandidateSet::CandidateSetKind CSK;
11268 
11269   CompareOverloadCandidatesForDisplay(
11270       Sema &S, SourceLocation Loc, size_t NArgs,
11271       OverloadCandidateSet::CandidateSetKind CSK)
11272       : S(S), NumArgs(NArgs), CSK(CSK) {}
11273 
11274   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11275     // If there are too many or too few arguments, that's the high-order bit we
11276     // want to sort by, even if the immediate failure kind was something else.
11277     if (C->FailureKind == ovl_fail_too_many_arguments ||
11278         C->FailureKind == ovl_fail_too_few_arguments)
11279       return static_cast<OverloadFailureKind>(C->FailureKind);
11280 
11281     if (C->Function) {
11282       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11283         return ovl_fail_too_many_arguments;
11284       if (NumArgs < C->Function->getMinRequiredArguments())
11285         return ovl_fail_too_few_arguments;
11286     }
11287 
11288     return static_cast<OverloadFailureKind>(C->FailureKind);
11289   }
11290 
11291   bool operator()(const OverloadCandidate *L,
11292                   const OverloadCandidate *R) {
11293     // Fast-path this check.
11294     if (L == R) return false;
11295 
11296     // Order first by viability.
11297     if (L->Viable) {
11298       if (!R->Viable) return true;
11299 
11300       // TODO: introduce a tri-valued comparison for overload
11301       // candidates.  Would be more worthwhile if we had a sort
11302       // that could exploit it.
11303       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11304         return true;
11305       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11306         return false;
11307     } else if (R->Viable)
11308       return false;
11309 
11310     assert(L->Viable == R->Viable);
11311 
11312     // Criteria by which we can sort non-viable candidates:
11313     if (!L->Viable) {
11314       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11315       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11316 
11317       // 1. Arity mismatches come after other candidates.
11318       if (LFailureKind == ovl_fail_too_many_arguments ||
11319           LFailureKind == ovl_fail_too_few_arguments) {
11320         if (RFailureKind == ovl_fail_too_many_arguments ||
11321             RFailureKind == ovl_fail_too_few_arguments) {
11322           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11323           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11324           if (LDist == RDist) {
11325             if (LFailureKind == RFailureKind)
11326               // Sort non-surrogates before surrogates.
11327               return !L->IsSurrogate && R->IsSurrogate;
11328             // Sort candidates requiring fewer parameters than there were
11329             // arguments given after candidates requiring more parameters
11330             // than there were arguments given.
11331             return LFailureKind == ovl_fail_too_many_arguments;
11332           }
11333           return LDist < RDist;
11334         }
11335         return false;
11336       }
11337       if (RFailureKind == ovl_fail_too_many_arguments ||
11338           RFailureKind == ovl_fail_too_few_arguments)
11339         return true;
11340 
11341       // 2. Bad conversions come first and are ordered by the number
11342       // of bad conversions and quality of good conversions.
11343       if (LFailureKind == ovl_fail_bad_conversion) {
11344         if (RFailureKind != ovl_fail_bad_conversion)
11345           return true;
11346 
11347         // The conversion that can be fixed with a smaller number of changes,
11348         // comes first.
11349         unsigned numLFixes = L->Fix.NumConversionsFixed;
11350         unsigned numRFixes = R->Fix.NumConversionsFixed;
11351         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11352         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11353         if (numLFixes != numRFixes) {
11354           return numLFixes < numRFixes;
11355         }
11356 
11357         // If there's any ordering between the defined conversions...
11358         // FIXME: this might not be transitive.
11359         assert(L->Conversions.size() == R->Conversions.size());
11360 
11361         int leftBetter = 0;
11362         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11363         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11364           switch (CompareImplicitConversionSequences(S, Loc,
11365                                                      L->Conversions[I],
11366                                                      R->Conversions[I])) {
11367           case ImplicitConversionSequence::Better:
11368             leftBetter++;
11369             break;
11370 
11371           case ImplicitConversionSequence::Worse:
11372             leftBetter--;
11373             break;
11374 
11375           case ImplicitConversionSequence::Indistinguishable:
11376             break;
11377           }
11378         }
11379         if (leftBetter > 0) return true;
11380         if (leftBetter < 0) return false;
11381 
11382       } else if (RFailureKind == ovl_fail_bad_conversion)
11383         return false;
11384 
11385       if (LFailureKind == ovl_fail_bad_deduction) {
11386         if (RFailureKind != ovl_fail_bad_deduction)
11387           return true;
11388 
11389         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11390           return RankDeductionFailure(L->DeductionFailure)
11391                < RankDeductionFailure(R->DeductionFailure);
11392       } else if (RFailureKind == ovl_fail_bad_deduction)
11393         return false;
11394 
11395       // TODO: others?
11396     }
11397 
11398     // Sort everything else by location.
11399     SourceLocation LLoc = GetLocationForCandidate(L);
11400     SourceLocation RLoc = GetLocationForCandidate(R);
11401 
11402     // Put candidates without locations (e.g. builtins) at the end.
11403     if (LLoc.isInvalid()) return false;
11404     if (RLoc.isInvalid()) return true;
11405 
11406     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11407   }
11408 };
11409 }
11410 
11411 /// CompleteNonViableCandidate - Normally, overload resolution only
11412 /// computes up to the first bad conversion. Produces the FixIt set if
11413 /// possible.
11414 static void
11415 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11416                            ArrayRef<Expr *> Args,
11417                            OverloadCandidateSet::CandidateSetKind CSK) {
11418   assert(!Cand->Viable);
11419 
11420   // Don't do anything on failures other than bad conversion.
11421   if (Cand->FailureKind != ovl_fail_bad_conversion)
11422     return;
11423 
11424   // We only want the FixIts if all the arguments can be corrected.
11425   bool Unfixable = false;
11426   // Use a implicit copy initialization to check conversion fixes.
11427   Cand->Fix.setConversionChecker(TryCopyInitialization);
11428 
11429   // Attempt to fix the bad conversion.
11430   unsigned ConvCount = Cand->Conversions.size();
11431   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11432        ++ConvIdx) {
11433     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11434     if (Cand->Conversions[ConvIdx].isInitialized() &&
11435         Cand->Conversions[ConvIdx].isBad()) {
11436       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11437       break;
11438     }
11439   }
11440 
11441   // FIXME: this should probably be preserved from the overload
11442   // operation somehow.
11443   bool SuppressUserConversions = false;
11444 
11445   unsigned ConvIdx = 0;
11446   unsigned ArgIdx = 0;
11447   ArrayRef<QualType> ParamTypes;
11448   bool Reversed = Cand->isReversed();
11449 
11450   if (Cand->IsSurrogate) {
11451     QualType ConvType
11452       = Cand->Surrogate->getConversionType().getNonReferenceType();
11453     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11454       ConvType = ConvPtrType->getPointeeType();
11455     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11456     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11457     ConvIdx = 1;
11458   } else if (Cand->Function) {
11459     ParamTypes =
11460         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11461     if (isa<CXXMethodDecl>(Cand->Function) &&
11462         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11463       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11464       ConvIdx = 1;
11465       if (CSK == OverloadCandidateSet::CSK_Operator &&
11466           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11467         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11468         ArgIdx = 1;
11469     }
11470   } else {
11471     // Builtin operator.
11472     assert(ConvCount <= 3);
11473     ParamTypes = Cand->BuiltinParamTypes;
11474   }
11475 
11476   // Fill in the rest of the conversions.
11477   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11478        ConvIdx != ConvCount;
11479        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11480     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11481     if (Cand->Conversions[ConvIdx].isInitialized()) {
11482       // We've already checked this conversion.
11483     } else if (ParamIdx < ParamTypes.size()) {
11484       if (ParamTypes[ParamIdx]->isDependentType())
11485         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11486             Args[ArgIdx]->getType());
11487       else {
11488         Cand->Conversions[ConvIdx] =
11489             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11490                                   SuppressUserConversions,
11491                                   /*InOverloadResolution=*/true,
11492                                   /*AllowObjCWritebackConversion=*/
11493                                   S.getLangOpts().ObjCAutoRefCount);
11494         // Store the FixIt in the candidate if it exists.
11495         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11496           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11497       }
11498     } else
11499       Cand->Conversions[ConvIdx].setEllipsis();
11500   }
11501 }
11502 
11503 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11504     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11505     SourceLocation OpLoc,
11506     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11507   // Sort the candidates by viability and position.  Sorting directly would
11508   // be prohibitive, so we make a set of pointers and sort those.
11509   SmallVector<OverloadCandidate*, 32> Cands;
11510   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11511   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11512     if (!Filter(*Cand))
11513       continue;
11514     switch (OCD) {
11515     case OCD_AllCandidates:
11516       if (!Cand->Viable) {
11517         if (!Cand->Function && !Cand->IsSurrogate) {
11518           // This a non-viable builtin candidate.  We do not, in general,
11519           // want to list every possible builtin candidate.
11520           continue;
11521         }
11522         CompleteNonViableCandidate(S, Cand, Args, Kind);
11523       }
11524       break;
11525 
11526     case OCD_ViableCandidates:
11527       if (!Cand->Viable)
11528         continue;
11529       break;
11530 
11531     case OCD_AmbiguousCandidates:
11532       if (!Cand->Best)
11533         continue;
11534       break;
11535     }
11536 
11537     Cands.push_back(Cand);
11538   }
11539 
11540   llvm::stable_sort(
11541       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11542 
11543   return Cands;
11544 }
11545 
11546 /// When overload resolution fails, prints diagnostic messages containing the
11547 /// candidates in the candidate set.
11548 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11549     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11550     StringRef Opc, SourceLocation OpLoc,
11551     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11552 
11553   bool DeferHint = false;
11554   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11555     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates.
11556     auto WrongSidedCands =
11557         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11558           return Cand.Viable == false &&
11559                  Cand.FailureKind == ovl_fail_bad_target;
11560         });
11561     DeferHint = WrongSidedCands.size();
11562   }
11563   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11564 
11565   S.Diag(PD.first, PD.second, DeferHint);
11566 
11567   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11568 
11569   if (OCD == OCD_AmbiguousCandidates)
11570     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11571 }
11572 
11573 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11574                                           ArrayRef<OverloadCandidate *> Cands,
11575                                           StringRef Opc, SourceLocation OpLoc) {
11576   bool ReportedAmbiguousConversions = false;
11577 
11578   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11579   unsigned CandsShown = 0;
11580   auto I = Cands.begin(), E = Cands.end();
11581   for (; I != E; ++I) {
11582     OverloadCandidate *Cand = *I;
11583 
11584     // Set an arbitrary limit on the number of candidate functions we'll spam
11585     // the user with.  FIXME: This limit should depend on details of the
11586     // candidate list.
11587     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11588       break;
11589     }
11590     ++CandsShown;
11591 
11592     if (Cand->Function)
11593       NoteFunctionCandidate(S, Cand, Args.size(),
11594                             /*TakingCandidateAddress=*/false, DestAS);
11595     else if (Cand->IsSurrogate)
11596       NoteSurrogateCandidate(S, Cand);
11597     else {
11598       assert(Cand->Viable &&
11599              "Non-viable built-in candidates are not added to Cands.");
11600       // Generally we only see ambiguities including viable builtin
11601       // operators if overload resolution got screwed up by an
11602       // ambiguous user-defined conversion.
11603       //
11604       // FIXME: It's quite possible for different conversions to see
11605       // different ambiguities, though.
11606       if (!ReportedAmbiguousConversions) {
11607         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11608         ReportedAmbiguousConversions = true;
11609       }
11610 
11611       // If this is a viable builtin, print it.
11612       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11613     }
11614   }
11615 
11616   if (I != E)
11617     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11618 }
11619 
11620 static SourceLocation
11621 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11622   return Cand->Specialization ? Cand->Specialization->getLocation()
11623                               : SourceLocation();
11624 }
11625 
11626 namespace {
11627 struct CompareTemplateSpecCandidatesForDisplay {
11628   Sema &S;
11629   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11630 
11631   bool operator()(const TemplateSpecCandidate *L,
11632                   const TemplateSpecCandidate *R) {
11633     // Fast-path this check.
11634     if (L == R)
11635       return false;
11636 
11637     // Assuming that both candidates are not matches...
11638 
11639     // Sort by the ranking of deduction failures.
11640     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11641       return RankDeductionFailure(L->DeductionFailure) <
11642              RankDeductionFailure(R->DeductionFailure);
11643 
11644     // Sort everything else by location.
11645     SourceLocation LLoc = GetLocationForCandidate(L);
11646     SourceLocation RLoc = GetLocationForCandidate(R);
11647 
11648     // Put candidates without locations (e.g. builtins) at the end.
11649     if (LLoc.isInvalid())
11650       return false;
11651     if (RLoc.isInvalid())
11652       return true;
11653 
11654     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11655   }
11656 };
11657 }
11658 
11659 /// Diagnose a template argument deduction failure.
11660 /// We are treating these failures as overload failures due to bad
11661 /// deductions.
11662 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11663                                                  bool ForTakingAddress) {
11664   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11665                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11666 }
11667 
11668 void TemplateSpecCandidateSet::destroyCandidates() {
11669   for (iterator i = begin(), e = end(); i != e; ++i) {
11670     i->DeductionFailure.Destroy();
11671   }
11672 }
11673 
11674 void TemplateSpecCandidateSet::clear() {
11675   destroyCandidates();
11676   Candidates.clear();
11677 }
11678 
11679 /// NoteCandidates - When no template specialization match is found, prints
11680 /// diagnostic messages containing the non-matching specializations that form
11681 /// the candidate set.
11682 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11683 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11684 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11685   // Sort the candidates by position (assuming no candidate is a match).
11686   // Sorting directly would be prohibitive, so we make a set of pointers
11687   // and sort those.
11688   SmallVector<TemplateSpecCandidate *, 32> Cands;
11689   Cands.reserve(size());
11690   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11691     if (Cand->Specialization)
11692       Cands.push_back(Cand);
11693     // Otherwise, this is a non-matching builtin candidate.  We do not,
11694     // in general, want to list every possible builtin candidate.
11695   }
11696 
11697   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11698 
11699   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11700   // for generalization purposes (?).
11701   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11702 
11703   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11704   unsigned CandsShown = 0;
11705   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11706     TemplateSpecCandidate *Cand = *I;
11707 
11708     // Set an arbitrary limit on the number of candidates we'll spam
11709     // the user with.  FIXME: This limit should depend on details of the
11710     // candidate list.
11711     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11712       break;
11713     ++CandsShown;
11714 
11715     assert(Cand->Specialization &&
11716            "Non-matching built-in candidates are not added to Cands.");
11717     Cand->NoteDeductionFailure(S, ForTakingAddress);
11718   }
11719 
11720   if (I != E)
11721     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11722 }
11723 
11724 // [PossiblyAFunctionType]  -->   [Return]
11725 // NonFunctionType --> NonFunctionType
11726 // R (A) --> R(A)
11727 // R (*)(A) --> R (A)
11728 // R (&)(A) --> R (A)
11729 // R (S::*)(A) --> R (A)
11730 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11731   QualType Ret = PossiblyAFunctionType;
11732   if (const PointerType *ToTypePtr =
11733     PossiblyAFunctionType->getAs<PointerType>())
11734     Ret = ToTypePtr->getPointeeType();
11735   else if (const ReferenceType *ToTypeRef =
11736     PossiblyAFunctionType->getAs<ReferenceType>())
11737     Ret = ToTypeRef->getPointeeType();
11738   else if (const MemberPointerType *MemTypePtr =
11739     PossiblyAFunctionType->getAs<MemberPointerType>())
11740     Ret = MemTypePtr->getPointeeType();
11741   Ret =
11742     Context.getCanonicalType(Ret).getUnqualifiedType();
11743   return Ret;
11744 }
11745 
11746 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11747                                  bool Complain = true) {
11748   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11749       S.DeduceReturnType(FD, Loc, Complain))
11750     return true;
11751 
11752   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11753   if (S.getLangOpts().CPlusPlus17 &&
11754       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11755       !S.ResolveExceptionSpec(Loc, FPT))
11756     return true;
11757 
11758   return false;
11759 }
11760 
11761 namespace {
11762 // A helper class to help with address of function resolution
11763 // - allows us to avoid passing around all those ugly parameters
11764 class AddressOfFunctionResolver {
11765   Sema& S;
11766   Expr* SourceExpr;
11767   const QualType& TargetType;
11768   QualType TargetFunctionType; // Extracted function type from target type
11769 
11770   bool Complain;
11771   //DeclAccessPair& ResultFunctionAccessPair;
11772   ASTContext& Context;
11773 
11774   bool TargetTypeIsNonStaticMemberFunction;
11775   bool FoundNonTemplateFunction;
11776   bool StaticMemberFunctionFromBoundPointer;
11777   bool HasComplained;
11778 
11779   OverloadExpr::FindResult OvlExprInfo;
11780   OverloadExpr *OvlExpr;
11781   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11782   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11783   TemplateSpecCandidateSet FailedCandidates;
11784 
11785 public:
11786   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11787                             const QualType &TargetType, bool Complain)
11788       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11789         Complain(Complain), Context(S.getASTContext()),
11790         TargetTypeIsNonStaticMemberFunction(
11791             !!TargetType->getAs<MemberPointerType>()),
11792         FoundNonTemplateFunction(false),
11793         StaticMemberFunctionFromBoundPointer(false),
11794         HasComplained(false),
11795         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11796         OvlExpr(OvlExprInfo.Expression),
11797         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11798     ExtractUnqualifiedFunctionTypeFromTargetType();
11799 
11800     if (TargetFunctionType->isFunctionType()) {
11801       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11802         if (!UME->isImplicitAccess() &&
11803             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11804           StaticMemberFunctionFromBoundPointer = true;
11805     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11806       DeclAccessPair dap;
11807       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11808               OvlExpr, false, &dap)) {
11809         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11810           if (!Method->isStatic()) {
11811             // If the target type is a non-function type and the function found
11812             // is a non-static member function, pretend as if that was the
11813             // target, it's the only possible type to end up with.
11814             TargetTypeIsNonStaticMemberFunction = true;
11815 
11816             // And skip adding the function if its not in the proper form.
11817             // We'll diagnose this due to an empty set of functions.
11818             if (!OvlExprInfo.HasFormOfMemberPointer)
11819               return;
11820           }
11821 
11822         Matches.push_back(std::make_pair(dap, Fn));
11823       }
11824       return;
11825     }
11826 
11827     if (OvlExpr->hasExplicitTemplateArgs())
11828       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11829 
11830     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11831       // C++ [over.over]p4:
11832       //   If more than one function is selected, [...]
11833       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11834         if (FoundNonTemplateFunction)
11835           EliminateAllTemplateMatches();
11836         else
11837           EliminateAllExceptMostSpecializedTemplate();
11838       }
11839     }
11840 
11841     if (S.getLangOpts().CUDA && Matches.size() > 1)
11842       EliminateSuboptimalCudaMatches();
11843   }
11844 
11845   bool hasComplained() const { return HasComplained; }
11846 
11847 private:
11848   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11849     QualType Discard;
11850     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11851            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11852   }
11853 
11854   /// \return true if A is considered a better overload candidate for the
11855   /// desired type than B.
11856   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11857     // If A doesn't have exactly the correct type, we don't want to classify it
11858     // as "better" than anything else. This way, the user is required to
11859     // disambiguate for us if there are multiple candidates and no exact match.
11860     return candidateHasExactlyCorrectType(A) &&
11861            (!candidateHasExactlyCorrectType(B) ||
11862             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11863   }
11864 
11865   /// \return true if we were able to eliminate all but one overload candidate,
11866   /// false otherwise.
11867   bool eliminiateSuboptimalOverloadCandidates() {
11868     // Same algorithm as overload resolution -- one pass to pick the "best",
11869     // another pass to be sure that nothing is better than the best.
11870     auto Best = Matches.begin();
11871     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11872       if (isBetterCandidate(I->second, Best->second))
11873         Best = I;
11874 
11875     const FunctionDecl *BestFn = Best->second;
11876     auto IsBestOrInferiorToBest = [this, BestFn](
11877         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11878       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11879     };
11880 
11881     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11882     // option, so we can potentially give the user a better error
11883     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11884       return false;
11885     Matches[0] = *Best;
11886     Matches.resize(1);
11887     return true;
11888   }
11889 
11890   bool isTargetTypeAFunction() const {
11891     return TargetFunctionType->isFunctionType();
11892   }
11893 
11894   // [ToType]     [Return]
11895 
11896   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11897   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11898   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11899   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11900     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11901   }
11902 
11903   // return true if any matching specializations were found
11904   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11905                                    const DeclAccessPair& CurAccessFunPair) {
11906     if (CXXMethodDecl *Method
11907               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11908       // Skip non-static function templates when converting to pointer, and
11909       // static when converting to member pointer.
11910       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11911         return false;
11912     }
11913     else if (TargetTypeIsNonStaticMemberFunction)
11914       return false;
11915 
11916     // C++ [over.over]p2:
11917     //   If the name is a function template, template argument deduction is
11918     //   done (14.8.2.2), and if the argument deduction succeeds, the
11919     //   resulting template argument list is used to generate a single
11920     //   function template specialization, which is added to the set of
11921     //   overloaded functions considered.
11922     FunctionDecl *Specialization = nullptr;
11923     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11924     if (Sema::TemplateDeductionResult Result
11925           = S.DeduceTemplateArguments(FunctionTemplate,
11926                                       &OvlExplicitTemplateArgs,
11927                                       TargetFunctionType, Specialization,
11928                                       Info, /*IsAddressOfFunction*/true)) {
11929       // Make a note of the failed deduction for diagnostics.
11930       FailedCandidates.addCandidate()
11931           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11932                MakeDeductionFailureInfo(Context, Result, Info));
11933       return false;
11934     }
11935 
11936     // Template argument deduction ensures that we have an exact match or
11937     // compatible pointer-to-function arguments that would be adjusted by ICS.
11938     // This function template specicalization works.
11939     assert(S.isSameOrCompatibleFunctionType(
11940               Context.getCanonicalType(Specialization->getType()),
11941               Context.getCanonicalType(TargetFunctionType)));
11942 
11943     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11944       return false;
11945 
11946     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11947     return true;
11948   }
11949 
11950   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11951                                       const DeclAccessPair& CurAccessFunPair) {
11952     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11953       // Skip non-static functions when converting to pointer, and static
11954       // when converting to member pointer.
11955       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11956         return false;
11957     }
11958     else if (TargetTypeIsNonStaticMemberFunction)
11959       return false;
11960 
11961     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11962       if (S.getLangOpts().CUDA)
11963         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11964           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11965             return false;
11966       if (FunDecl->isMultiVersion()) {
11967         const auto *TA = FunDecl->getAttr<TargetAttr>();
11968         if (TA && !TA->isDefaultVersion())
11969           return false;
11970       }
11971 
11972       // If any candidate has a placeholder return type, trigger its deduction
11973       // now.
11974       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11975                                Complain)) {
11976         HasComplained |= Complain;
11977         return false;
11978       }
11979 
11980       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11981         return false;
11982 
11983       // If we're in C, we need to support types that aren't exactly identical.
11984       if (!S.getLangOpts().CPlusPlus ||
11985           candidateHasExactlyCorrectType(FunDecl)) {
11986         Matches.push_back(std::make_pair(
11987             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11988         FoundNonTemplateFunction = true;
11989         return true;
11990       }
11991     }
11992 
11993     return false;
11994   }
11995 
11996   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11997     bool Ret = false;
11998 
11999     // If the overload expression doesn't have the form of a pointer to
12000     // member, don't try to convert it to a pointer-to-member type.
12001     if (IsInvalidFormOfPointerToMemberFunction())
12002       return false;
12003 
12004     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12005                                E = OvlExpr->decls_end();
12006          I != E; ++I) {
12007       // Look through any using declarations to find the underlying function.
12008       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12009 
12010       // C++ [over.over]p3:
12011       //   Non-member functions and static member functions match
12012       //   targets of type "pointer-to-function" or "reference-to-function."
12013       //   Nonstatic member functions match targets of
12014       //   type "pointer-to-member-function."
12015       // Note that according to DR 247, the containing class does not matter.
12016       if (FunctionTemplateDecl *FunctionTemplate
12017                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12018         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12019           Ret = true;
12020       }
12021       // If we have explicit template arguments supplied, skip non-templates.
12022       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12023                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12024         Ret = true;
12025     }
12026     assert(Ret || Matches.empty());
12027     return Ret;
12028   }
12029 
12030   void EliminateAllExceptMostSpecializedTemplate() {
12031     //   [...] and any given function template specialization F1 is
12032     //   eliminated if the set contains a second function template
12033     //   specialization whose function template is more specialized
12034     //   than the function template of F1 according to the partial
12035     //   ordering rules of 14.5.5.2.
12036 
12037     // The algorithm specified above is quadratic. We instead use a
12038     // two-pass algorithm (similar to the one used to identify the
12039     // best viable function in an overload set) that identifies the
12040     // best function template (if it exists).
12041 
12042     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12043     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12044       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12045 
12046     // TODO: It looks like FailedCandidates does not serve much purpose
12047     // here, since the no_viable diagnostic has index 0.
12048     UnresolvedSetIterator Result = S.getMostSpecialized(
12049         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12050         SourceExpr->getBeginLoc(), S.PDiag(),
12051         S.PDiag(diag::err_addr_ovl_ambiguous)
12052             << Matches[0].second->getDeclName(),
12053         S.PDiag(diag::note_ovl_candidate)
12054             << (unsigned)oc_function << (unsigned)ocs_described_template,
12055         Complain, TargetFunctionType);
12056 
12057     if (Result != MatchesCopy.end()) {
12058       // Make it the first and only element
12059       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12060       Matches[0].second = cast<FunctionDecl>(*Result);
12061       Matches.resize(1);
12062     } else
12063       HasComplained |= Complain;
12064   }
12065 
12066   void EliminateAllTemplateMatches() {
12067     //   [...] any function template specializations in the set are
12068     //   eliminated if the set also contains a non-template function, [...]
12069     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12070       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12071         ++I;
12072       else {
12073         Matches[I] = Matches[--N];
12074         Matches.resize(N);
12075       }
12076     }
12077   }
12078 
12079   void EliminateSuboptimalCudaMatches() {
12080     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12081   }
12082 
12083 public:
12084   void ComplainNoMatchesFound() const {
12085     assert(Matches.empty());
12086     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12087         << OvlExpr->getName() << TargetFunctionType
12088         << OvlExpr->getSourceRange();
12089     if (FailedCandidates.empty())
12090       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12091                                   /*TakingAddress=*/true);
12092     else {
12093       // We have some deduction failure messages. Use them to diagnose
12094       // the function templates, and diagnose the non-template candidates
12095       // normally.
12096       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12097                                  IEnd = OvlExpr->decls_end();
12098            I != IEnd; ++I)
12099         if (FunctionDecl *Fun =
12100                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12101           if (!functionHasPassObjectSizeParams(Fun))
12102             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12103                                     /*TakingAddress=*/true);
12104       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12105     }
12106   }
12107 
12108   bool IsInvalidFormOfPointerToMemberFunction() const {
12109     return TargetTypeIsNonStaticMemberFunction &&
12110       !OvlExprInfo.HasFormOfMemberPointer;
12111   }
12112 
12113   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12114       // TODO: Should we condition this on whether any functions might
12115       // have matched, or is it more appropriate to do that in callers?
12116       // TODO: a fixit wouldn't hurt.
12117       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12118         << TargetType << OvlExpr->getSourceRange();
12119   }
12120 
12121   bool IsStaticMemberFunctionFromBoundPointer() const {
12122     return StaticMemberFunctionFromBoundPointer;
12123   }
12124 
12125   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12126     S.Diag(OvlExpr->getBeginLoc(),
12127            diag::err_invalid_form_pointer_member_function)
12128         << OvlExpr->getSourceRange();
12129   }
12130 
12131   void ComplainOfInvalidConversion() const {
12132     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12133         << OvlExpr->getName() << TargetType;
12134   }
12135 
12136   void ComplainMultipleMatchesFound() const {
12137     assert(Matches.size() > 1);
12138     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12139         << OvlExpr->getName() << OvlExpr->getSourceRange();
12140     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12141                                 /*TakingAddress=*/true);
12142   }
12143 
12144   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12145 
12146   int getNumMatches() const { return Matches.size(); }
12147 
12148   FunctionDecl* getMatchingFunctionDecl() const {
12149     if (Matches.size() != 1) return nullptr;
12150     return Matches[0].second;
12151   }
12152 
12153   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12154     if (Matches.size() != 1) return nullptr;
12155     return &Matches[0].first;
12156   }
12157 };
12158 }
12159 
12160 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12161 /// an overloaded function (C++ [over.over]), where @p From is an
12162 /// expression with overloaded function type and @p ToType is the type
12163 /// we're trying to resolve to. For example:
12164 ///
12165 /// @code
12166 /// int f(double);
12167 /// int f(int);
12168 ///
12169 /// int (*pfd)(double) = f; // selects f(double)
12170 /// @endcode
12171 ///
12172 /// This routine returns the resulting FunctionDecl if it could be
12173 /// resolved, and NULL otherwise. When @p Complain is true, this
12174 /// routine will emit diagnostics if there is an error.
12175 FunctionDecl *
12176 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12177                                          QualType TargetType,
12178                                          bool Complain,
12179                                          DeclAccessPair &FoundResult,
12180                                          bool *pHadMultipleCandidates) {
12181   assert(AddressOfExpr->getType() == Context.OverloadTy);
12182 
12183   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12184                                      Complain);
12185   int NumMatches = Resolver.getNumMatches();
12186   FunctionDecl *Fn = nullptr;
12187   bool ShouldComplain = Complain && !Resolver.hasComplained();
12188   if (NumMatches == 0 && ShouldComplain) {
12189     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12190       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12191     else
12192       Resolver.ComplainNoMatchesFound();
12193   }
12194   else if (NumMatches > 1 && ShouldComplain)
12195     Resolver.ComplainMultipleMatchesFound();
12196   else if (NumMatches == 1) {
12197     Fn = Resolver.getMatchingFunctionDecl();
12198     assert(Fn);
12199     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12200       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12201     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12202     if (Complain) {
12203       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12204         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12205       else
12206         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12207     }
12208   }
12209 
12210   if (pHadMultipleCandidates)
12211     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12212   return Fn;
12213 }
12214 
12215 /// Given an expression that refers to an overloaded function, try to
12216 /// resolve that function to a single function that can have its address taken.
12217 /// This will modify `Pair` iff it returns non-null.
12218 ///
12219 /// This routine can only succeed if from all of the candidates in the overload
12220 /// set for SrcExpr that can have their addresses taken, there is one candidate
12221 /// that is more constrained than the rest.
12222 FunctionDecl *
12223 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12224   OverloadExpr::FindResult R = OverloadExpr::find(E);
12225   OverloadExpr *Ovl = R.Expression;
12226   bool IsResultAmbiguous = false;
12227   FunctionDecl *Result = nullptr;
12228   DeclAccessPair DAP;
12229   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12230 
12231   auto CheckMoreConstrained =
12232       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12233         SmallVector<const Expr *, 1> AC1, AC2;
12234         FD1->getAssociatedConstraints(AC1);
12235         FD2->getAssociatedConstraints(AC2);
12236         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12237         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12238           return None;
12239         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12240           return None;
12241         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12242           return None;
12243         return AtLeastAsConstrained1;
12244       };
12245 
12246   // Don't use the AddressOfResolver because we're specifically looking for
12247   // cases where we have one overload candidate that lacks
12248   // enable_if/pass_object_size/...
12249   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12250     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12251     if (!FD)
12252       return nullptr;
12253 
12254     if (!checkAddressOfFunctionIsAvailable(FD))
12255       continue;
12256 
12257     // We have more than one result - see if it is more constrained than the
12258     // previous one.
12259     if (Result) {
12260       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12261                                                                         Result);
12262       if (!MoreConstrainedThanPrevious) {
12263         IsResultAmbiguous = true;
12264         AmbiguousDecls.push_back(FD);
12265         continue;
12266       }
12267       if (!*MoreConstrainedThanPrevious)
12268         continue;
12269       // FD is more constrained - replace Result with it.
12270     }
12271     IsResultAmbiguous = false;
12272     DAP = I.getPair();
12273     Result = FD;
12274   }
12275 
12276   if (IsResultAmbiguous)
12277     return nullptr;
12278 
12279   if (Result) {
12280     SmallVector<const Expr *, 1> ResultAC;
12281     // We skipped over some ambiguous declarations which might be ambiguous with
12282     // the selected result.
12283     for (FunctionDecl *Skipped : AmbiguousDecls)
12284       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12285         return nullptr;
12286     Pair = DAP;
12287   }
12288   return Result;
12289 }
12290 
12291 /// Given an overloaded function, tries to turn it into a non-overloaded
12292 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12293 /// will perform access checks, diagnose the use of the resultant decl, and, if
12294 /// requested, potentially perform a function-to-pointer decay.
12295 ///
12296 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12297 /// Otherwise, returns true. This may emit diagnostics and return true.
12298 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12299     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12300   Expr *E = SrcExpr.get();
12301   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12302 
12303   DeclAccessPair DAP;
12304   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12305   if (!Found || Found->isCPUDispatchMultiVersion() ||
12306       Found->isCPUSpecificMultiVersion())
12307     return false;
12308 
12309   // Emitting multiple diagnostics for a function that is both inaccessible and
12310   // unavailable is consistent with our behavior elsewhere. So, always check
12311   // for both.
12312   DiagnoseUseOfDecl(Found, E->getExprLoc());
12313   CheckAddressOfMemberAccess(E, DAP);
12314   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12315   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12316     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12317   else
12318     SrcExpr = Fixed;
12319   return true;
12320 }
12321 
12322 /// Given an expression that refers to an overloaded function, try to
12323 /// resolve that overloaded function expression down to a single function.
12324 ///
12325 /// This routine can only resolve template-ids that refer to a single function
12326 /// template, where that template-id refers to a single template whose template
12327 /// arguments are either provided by the template-id or have defaults,
12328 /// as described in C++0x [temp.arg.explicit]p3.
12329 ///
12330 /// If no template-ids are found, no diagnostics are emitted and NULL is
12331 /// returned.
12332 FunctionDecl *
12333 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12334                                                   bool Complain,
12335                                                   DeclAccessPair *FoundResult) {
12336   // C++ [over.over]p1:
12337   //   [...] [Note: any redundant set of parentheses surrounding the
12338   //   overloaded function name is ignored (5.1). ]
12339   // C++ [over.over]p1:
12340   //   [...] The overloaded function name can be preceded by the &
12341   //   operator.
12342 
12343   // If we didn't actually find any template-ids, we're done.
12344   if (!ovl->hasExplicitTemplateArgs())
12345     return nullptr;
12346 
12347   TemplateArgumentListInfo ExplicitTemplateArgs;
12348   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12349   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12350 
12351   // Look through all of the overloaded functions, searching for one
12352   // whose type matches exactly.
12353   FunctionDecl *Matched = nullptr;
12354   for (UnresolvedSetIterator I = ovl->decls_begin(),
12355          E = ovl->decls_end(); I != E; ++I) {
12356     // C++0x [temp.arg.explicit]p3:
12357     //   [...] In contexts where deduction is done and fails, or in contexts
12358     //   where deduction is not done, if a template argument list is
12359     //   specified and it, along with any default template arguments,
12360     //   identifies a single function template specialization, then the
12361     //   template-id is an lvalue for the function template specialization.
12362     FunctionTemplateDecl *FunctionTemplate
12363       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12364 
12365     // C++ [over.over]p2:
12366     //   If the name is a function template, template argument deduction is
12367     //   done (14.8.2.2), and if the argument deduction succeeds, the
12368     //   resulting template argument list is used to generate a single
12369     //   function template specialization, which is added to the set of
12370     //   overloaded functions considered.
12371     FunctionDecl *Specialization = nullptr;
12372     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12373     if (TemplateDeductionResult Result
12374           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12375                                     Specialization, Info,
12376                                     /*IsAddressOfFunction*/true)) {
12377       // Make a note of the failed deduction for diagnostics.
12378       // TODO: Actually use the failed-deduction info?
12379       FailedCandidates.addCandidate()
12380           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12381                MakeDeductionFailureInfo(Context, Result, Info));
12382       continue;
12383     }
12384 
12385     assert(Specialization && "no specialization and no error?");
12386 
12387     // Multiple matches; we can't resolve to a single declaration.
12388     if (Matched) {
12389       if (Complain) {
12390         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12391           << ovl->getName();
12392         NoteAllOverloadCandidates(ovl);
12393       }
12394       return nullptr;
12395     }
12396 
12397     Matched = Specialization;
12398     if (FoundResult) *FoundResult = I.getPair();
12399   }
12400 
12401   if (Matched &&
12402       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12403     return nullptr;
12404 
12405   return Matched;
12406 }
12407 
12408 // Resolve and fix an overloaded expression that can be resolved
12409 // because it identifies a single function template specialization.
12410 //
12411 // Last three arguments should only be supplied if Complain = true
12412 //
12413 // Return true if it was logically possible to so resolve the
12414 // expression, regardless of whether or not it succeeded.  Always
12415 // returns true if 'complain' is set.
12416 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12417                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12418                       bool complain, SourceRange OpRangeForComplaining,
12419                                            QualType DestTypeForComplaining,
12420                                             unsigned DiagIDForComplaining) {
12421   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12422 
12423   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12424 
12425   DeclAccessPair found;
12426   ExprResult SingleFunctionExpression;
12427   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12428                            ovl.Expression, /*complain*/ false, &found)) {
12429     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12430       SrcExpr = ExprError();
12431       return true;
12432     }
12433 
12434     // It is only correct to resolve to an instance method if we're
12435     // resolving a form that's permitted to be a pointer to member.
12436     // Otherwise we'll end up making a bound member expression, which
12437     // is illegal in all the contexts we resolve like this.
12438     if (!ovl.HasFormOfMemberPointer &&
12439         isa<CXXMethodDecl>(fn) &&
12440         cast<CXXMethodDecl>(fn)->isInstance()) {
12441       if (!complain) return false;
12442 
12443       Diag(ovl.Expression->getExprLoc(),
12444            diag::err_bound_member_function)
12445         << 0 << ovl.Expression->getSourceRange();
12446 
12447       // TODO: I believe we only end up here if there's a mix of
12448       // static and non-static candidates (otherwise the expression
12449       // would have 'bound member' type, not 'overload' type).
12450       // Ideally we would note which candidate was chosen and why
12451       // the static candidates were rejected.
12452       SrcExpr = ExprError();
12453       return true;
12454     }
12455 
12456     // Fix the expression to refer to 'fn'.
12457     SingleFunctionExpression =
12458         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12459 
12460     // If desired, do function-to-pointer decay.
12461     if (doFunctionPointerConverion) {
12462       SingleFunctionExpression =
12463         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12464       if (SingleFunctionExpression.isInvalid()) {
12465         SrcExpr = ExprError();
12466         return true;
12467       }
12468     }
12469   }
12470 
12471   if (!SingleFunctionExpression.isUsable()) {
12472     if (complain) {
12473       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12474         << ovl.Expression->getName()
12475         << DestTypeForComplaining
12476         << OpRangeForComplaining
12477         << ovl.Expression->getQualifierLoc().getSourceRange();
12478       NoteAllOverloadCandidates(SrcExpr.get());
12479 
12480       SrcExpr = ExprError();
12481       return true;
12482     }
12483 
12484     return false;
12485   }
12486 
12487   SrcExpr = SingleFunctionExpression;
12488   return true;
12489 }
12490 
12491 /// Add a single candidate to the overload set.
12492 static void AddOverloadedCallCandidate(Sema &S,
12493                                        DeclAccessPair FoundDecl,
12494                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12495                                        ArrayRef<Expr *> Args,
12496                                        OverloadCandidateSet &CandidateSet,
12497                                        bool PartialOverloading,
12498                                        bool KnownValid) {
12499   NamedDecl *Callee = FoundDecl.getDecl();
12500   if (isa<UsingShadowDecl>(Callee))
12501     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12502 
12503   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12504     if (ExplicitTemplateArgs) {
12505       assert(!KnownValid && "Explicit template arguments?");
12506       return;
12507     }
12508     // Prevent ill-formed function decls to be added as overload candidates.
12509     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12510       return;
12511 
12512     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12513                            /*SuppressUserConversions=*/false,
12514                            PartialOverloading);
12515     return;
12516   }
12517 
12518   if (FunctionTemplateDecl *FuncTemplate
12519       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12520     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12521                                    ExplicitTemplateArgs, Args, CandidateSet,
12522                                    /*SuppressUserConversions=*/false,
12523                                    PartialOverloading);
12524     return;
12525   }
12526 
12527   assert(!KnownValid && "unhandled case in overloaded call candidate");
12528 }
12529 
12530 /// Add the overload candidates named by callee and/or found by argument
12531 /// dependent lookup to the given overload set.
12532 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12533                                        ArrayRef<Expr *> Args,
12534                                        OverloadCandidateSet &CandidateSet,
12535                                        bool PartialOverloading) {
12536 
12537 #ifndef NDEBUG
12538   // Verify that ArgumentDependentLookup is consistent with the rules
12539   // in C++0x [basic.lookup.argdep]p3:
12540   //
12541   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12542   //   and let Y be the lookup set produced by argument dependent
12543   //   lookup (defined as follows). If X contains
12544   //
12545   //     -- a declaration of a class member, or
12546   //
12547   //     -- a block-scope function declaration that is not a
12548   //        using-declaration, or
12549   //
12550   //     -- a declaration that is neither a function or a function
12551   //        template
12552   //
12553   //   then Y is empty.
12554 
12555   if (ULE->requiresADL()) {
12556     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12557            E = ULE->decls_end(); I != E; ++I) {
12558       assert(!(*I)->getDeclContext()->isRecord());
12559       assert(isa<UsingShadowDecl>(*I) ||
12560              !(*I)->getDeclContext()->isFunctionOrMethod());
12561       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12562     }
12563   }
12564 #endif
12565 
12566   // It would be nice to avoid this copy.
12567   TemplateArgumentListInfo TABuffer;
12568   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12569   if (ULE->hasExplicitTemplateArgs()) {
12570     ULE->copyTemplateArgumentsInto(TABuffer);
12571     ExplicitTemplateArgs = &TABuffer;
12572   }
12573 
12574   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12575          E = ULE->decls_end(); I != E; ++I)
12576     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12577                                CandidateSet, PartialOverloading,
12578                                /*KnownValid*/ true);
12579 
12580   if (ULE->requiresADL())
12581     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12582                                          Args, ExplicitTemplateArgs,
12583                                          CandidateSet, PartialOverloading);
12584 }
12585 
12586 /// Determine whether a declaration with the specified name could be moved into
12587 /// a different namespace.
12588 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12589   switch (Name.getCXXOverloadedOperator()) {
12590   case OO_New: case OO_Array_New:
12591   case OO_Delete: case OO_Array_Delete:
12592     return false;
12593 
12594   default:
12595     return true;
12596   }
12597 }
12598 
12599 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12600 /// template, where the non-dependent name was declared after the template
12601 /// was defined. This is common in code written for a compilers which do not
12602 /// correctly implement two-stage name lookup.
12603 ///
12604 /// Returns true if a viable candidate was found and a diagnostic was issued.
12605 static bool
12606 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12607                        const CXXScopeSpec &SS, LookupResult &R,
12608                        OverloadCandidateSet::CandidateSetKind CSK,
12609                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12610                        ArrayRef<Expr *> Args,
12611                        bool *DoDiagnoseEmptyLookup = nullptr) {
12612   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12613     return false;
12614 
12615   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12616     if (DC->isTransparentContext())
12617       continue;
12618 
12619     SemaRef.LookupQualifiedName(R, DC);
12620 
12621     if (!R.empty()) {
12622       R.suppressDiagnostics();
12623 
12624       if (isa<CXXRecordDecl>(DC)) {
12625         // Don't diagnose names we find in classes; we get much better
12626         // diagnostics for these from DiagnoseEmptyLookup.
12627         R.clear();
12628         if (DoDiagnoseEmptyLookup)
12629           *DoDiagnoseEmptyLookup = true;
12630         return false;
12631       }
12632 
12633       OverloadCandidateSet Candidates(FnLoc, CSK);
12634       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12635         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12636                                    ExplicitTemplateArgs, Args,
12637                                    Candidates, false, /*KnownValid*/ false);
12638 
12639       OverloadCandidateSet::iterator Best;
12640       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12641         // No viable functions. Don't bother the user with notes for functions
12642         // which don't work and shouldn't be found anyway.
12643         R.clear();
12644         return false;
12645       }
12646 
12647       // Find the namespaces where ADL would have looked, and suggest
12648       // declaring the function there instead.
12649       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12650       Sema::AssociatedClassSet AssociatedClasses;
12651       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12652                                                  AssociatedNamespaces,
12653                                                  AssociatedClasses);
12654       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12655       if (canBeDeclaredInNamespace(R.getLookupName())) {
12656         DeclContext *Std = SemaRef.getStdNamespace();
12657         for (Sema::AssociatedNamespaceSet::iterator
12658                it = AssociatedNamespaces.begin(),
12659                end = AssociatedNamespaces.end(); it != end; ++it) {
12660           // Never suggest declaring a function within namespace 'std'.
12661           if (Std && Std->Encloses(*it))
12662             continue;
12663 
12664           // Never suggest declaring a function within a namespace with a
12665           // reserved name, like __gnu_cxx.
12666           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12667           if (NS &&
12668               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12669             continue;
12670 
12671           SuggestedNamespaces.insert(*it);
12672         }
12673       }
12674 
12675       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12676         << R.getLookupName();
12677       if (SuggestedNamespaces.empty()) {
12678         SemaRef.Diag(Best->Function->getLocation(),
12679                      diag::note_not_found_by_two_phase_lookup)
12680           << R.getLookupName() << 0;
12681       } else if (SuggestedNamespaces.size() == 1) {
12682         SemaRef.Diag(Best->Function->getLocation(),
12683                      diag::note_not_found_by_two_phase_lookup)
12684           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12685       } else {
12686         // FIXME: It would be useful to list the associated namespaces here,
12687         // but the diagnostics infrastructure doesn't provide a way to produce
12688         // a localized representation of a list of items.
12689         SemaRef.Diag(Best->Function->getLocation(),
12690                      diag::note_not_found_by_two_phase_lookup)
12691           << R.getLookupName() << 2;
12692       }
12693 
12694       // Try to recover by calling this function.
12695       return true;
12696     }
12697 
12698     R.clear();
12699   }
12700 
12701   return false;
12702 }
12703 
12704 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12705 /// template, where the non-dependent operator was declared after the template
12706 /// was defined.
12707 ///
12708 /// Returns true if a viable candidate was found and a diagnostic was issued.
12709 static bool
12710 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12711                                SourceLocation OpLoc,
12712                                ArrayRef<Expr *> Args) {
12713   DeclarationName OpName =
12714     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12715   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12716   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12717                                 OverloadCandidateSet::CSK_Operator,
12718                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12719 }
12720 
12721 namespace {
12722 class BuildRecoveryCallExprRAII {
12723   Sema &SemaRef;
12724 public:
12725   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12726     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12727     SemaRef.IsBuildingRecoveryCallExpr = true;
12728   }
12729 
12730   ~BuildRecoveryCallExprRAII() {
12731     SemaRef.IsBuildingRecoveryCallExpr = false;
12732   }
12733 };
12734 
12735 }
12736 
12737 /// Attempts to recover from a call where no functions were found.
12738 static ExprResult
12739 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12740                       UnresolvedLookupExpr *ULE,
12741                       SourceLocation LParenLoc,
12742                       MutableArrayRef<Expr *> Args,
12743                       SourceLocation RParenLoc,
12744                       bool EmptyLookup, bool AllowTypoCorrection) {
12745   // Do not try to recover if it is already building a recovery call.
12746   // This stops infinite loops for template instantiations like
12747   //
12748   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12749   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12750   //
12751   if (SemaRef.IsBuildingRecoveryCallExpr)
12752     return ExprError();
12753   BuildRecoveryCallExprRAII RCE(SemaRef);
12754 
12755   CXXScopeSpec SS;
12756   SS.Adopt(ULE->getQualifierLoc());
12757   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12758 
12759   TemplateArgumentListInfo TABuffer;
12760   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12761   if (ULE->hasExplicitTemplateArgs()) {
12762     ULE->copyTemplateArgumentsInto(TABuffer);
12763     ExplicitTemplateArgs = &TABuffer;
12764   }
12765 
12766   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12767                  Sema::LookupOrdinaryName);
12768   bool DoDiagnoseEmptyLookup = EmptyLookup;
12769   if (!DiagnoseTwoPhaseLookup(
12770           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12771           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12772     NoTypoCorrectionCCC NoTypoValidator{};
12773     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12774                                                 ExplicitTemplateArgs != nullptr,
12775                                                 dyn_cast<MemberExpr>(Fn));
12776     CorrectionCandidateCallback &Validator =
12777         AllowTypoCorrection
12778             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12779             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12780     if (!DoDiagnoseEmptyLookup ||
12781         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12782                                     Args))
12783       return ExprError();
12784   }
12785 
12786   assert(!R.empty() && "lookup results empty despite recovery");
12787 
12788   // If recovery created an ambiguity, just bail out.
12789   if (R.isAmbiguous()) {
12790     R.suppressDiagnostics();
12791     return ExprError();
12792   }
12793 
12794   // Build an implicit member access expression if appropriate. Just drop the
12795   // casts and such from the call, we don't really care.
12796   ExprResult NewFn = ExprError();
12797   if ((*R.begin())->isCXXClassMember())
12798     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12799                                                     ExplicitTemplateArgs, S);
12800   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12801     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12802                                         ExplicitTemplateArgs);
12803   else
12804     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12805 
12806   if (NewFn.isInvalid())
12807     return ExprError();
12808 
12809   auto CallE =
12810       SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12811                             MultiExprArg(Args.data(), Args.size()), RParenLoc);
12812   if (CallE.isInvalid())
12813     return ExprError();
12814   // We now have recovered a callee. However, building a real call may lead to
12815   // incorrect secondary diagnostics if our recovery wasn't correct.
12816   // We keep the recovery behavior but suppress all following diagnostics by
12817   // using RecoveryExpr. We deliberately drop the return type of the recovery
12818   // function, and rely on clang's dependent mechanism to suppress following
12819   // diagnostics.
12820   return SemaRef.CreateRecoveryExpr(CallE.get()->getBeginLoc(),
12821                                     CallE.get()->getEndLoc(), {CallE.get()});
12822 }
12823 
12824 /// Constructs and populates an OverloadedCandidateSet from
12825 /// the given function.
12826 /// \returns true when an the ExprResult output parameter has been set.
12827 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12828                                   UnresolvedLookupExpr *ULE,
12829                                   MultiExprArg Args,
12830                                   SourceLocation RParenLoc,
12831                                   OverloadCandidateSet *CandidateSet,
12832                                   ExprResult *Result) {
12833 #ifndef NDEBUG
12834   if (ULE->requiresADL()) {
12835     // To do ADL, we must have found an unqualified name.
12836     assert(!ULE->getQualifier() && "qualified name with ADL");
12837 
12838     // We don't perform ADL for implicit declarations of builtins.
12839     // Verify that this was correctly set up.
12840     FunctionDecl *F;
12841     if (ULE->decls_begin() != ULE->decls_end() &&
12842         ULE->decls_begin() + 1 == ULE->decls_end() &&
12843         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12844         F->getBuiltinID() && F->isImplicit())
12845       llvm_unreachable("performing ADL for builtin");
12846 
12847     // We don't perform ADL in C.
12848     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12849   }
12850 #endif
12851 
12852   UnbridgedCastsSet UnbridgedCasts;
12853   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12854     *Result = ExprError();
12855     return true;
12856   }
12857 
12858   // Add the functions denoted by the callee to the set of candidate
12859   // functions, including those from argument-dependent lookup.
12860   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12861 
12862   if (getLangOpts().MSVCCompat &&
12863       CurContext->isDependentContext() && !isSFINAEContext() &&
12864       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12865 
12866     OverloadCandidateSet::iterator Best;
12867     if (CandidateSet->empty() ||
12868         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12869             OR_No_Viable_Function) {
12870       // In Microsoft mode, if we are inside a template class member function
12871       // then create a type dependent CallExpr. The goal is to postpone name
12872       // lookup to instantiation time to be able to search into type dependent
12873       // base classes.
12874       CallExpr *CE =
12875           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue,
12876                            RParenLoc, CurFPFeatureOverrides());
12877       CE->markDependentForPostponedNameLookup();
12878       *Result = CE;
12879       return true;
12880     }
12881   }
12882 
12883   if (CandidateSet->empty())
12884     return false;
12885 
12886   UnbridgedCasts.restore();
12887   return false;
12888 }
12889 
12890 // Guess at what the return type for an unresolvable overload should be.
12891 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12892                                    OverloadCandidateSet::iterator *Best) {
12893   llvm::Optional<QualType> Result;
12894   // Adjust Type after seeing a candidate.
12895   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12896     if (!Candidate.Function)
12897       return;
12898     if (Candidate.Function->isInvalidDecl())
12899       return;
12900     QualType T = Candidate.Function->getReturnType();
12901     if (T.isNull())
12902       return;
12903     if (!Result)
12904       Result = T;
12905     else if (Result != T)
12906       Result = QualType();
12907   };
12908 
12909   // Look for an unambiguous type from a progressively larger subset.
12910   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12911   //
12912   // First, consider only the best candidate.
12913   if (Best && *Best != CS.end())
12914     ConsiderCandidate(**Best);
12915   // Next, consider only viable candidates.
12916   if (!Result)
12917     for (const auto &C : CS)
12918       if (C.Viable)
12919         ConsiderCandidate(C);
12920   // Finally, consider all candidates.
12921   if (!Result)
12922     for (const auto &C : CS)
12923       ConsiderCandidate(C);
12924 
12925   if (!Result)
12926     return QualType();
12927   auto Value = Result.getValue();
12928   if (Value.isNull() || Value->isUndeducedType())
12929     return QualType();
12930   return Value;
12931 }
12932 
12933 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12934 /// the completed call expression. If overload resolution fails, emits
12935 /// diagnostics and returns ExprError()
12936 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12937                                            UnresolvedLookupExpr *ULE,
12938                                            SourceLocation LParenLoc,
12939                                            MultiExprArg Args,
12940                                            SourceLocation RParenLoc,
12941                                            Expr *ExecConfig,
12942                                            OverloadCandidateSet *CandidateSet,
12943                                            OverloadCandidateSet::iterator *Best,
12944                                            OverloadingResult OverloadResult,
12945                                            bool AllowTypoCorrection) {
12946   if (CandidateSet->empty())
12947     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12948                                  RParenLoc, /*EmptyLookup=*/true,
12949                                  AllowTypoCorrection);
12950 
12951   switch (OverloadResult) {
12952   case OR_Success: {
12953     FunctionDecl *FDecl = (*Best)->Function;
12954     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12955     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12956       return ExprError();
12957     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12958     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12959                                          ExecConfig, /*IsExecConfig=*/false,
12960                                          (*Best)->IsADLCandidate);
12961   }
12962 
12963   case OR_No_Viable_Function: {
12964     // Try to recover by looking for viable functions which the user might
12965     // have meant to call.
12966     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12967                                                 Args, RParenLoc,
12968                                                 /*EmptyLookup=*/false,
12969                                                 AllowTypoCorrection);
12970     if (!Recovery.isInvalid())
12971       return Recovery;
12972 
12973     // If the user passes in a function that we can't take the address of, we
12974     // generally end up emitting really bad error messages. Here, we attempt to
12975     // emit better ones.
12976     for (const Expr *Arg : Args) {
12977       if (!Arg->getType()->isFunctionType())
12978         continue;
12979       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12980         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12981         if (FD &&
12982             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12983                                                        Arg->getExprLoc()))
12984           return ExprError();
12985       }
12986     }
12987 
12988     CandidateSet->NoteCandidates(
12989         PartialDiagnosticAt(
12990             Fn->getBeginLoc(),
12991             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12992                 << ULE->getName() << Fn->getSourceRange()),
12993         SemaRef, OCD_AllCandidates, Args);
12994     break;
12995   }
12996 
12997   case OR_Ambiguous:
12998     CandidateSet->NoteCandidates(
12999         PartialDiagnosticAt(Fn->getBeginLoc(),
13000                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13001                                 << ULE->getName() << Fn->getSourceRange()),
13002         SemaRef, OCD_AmbiguousCandidates, Args);
13003     break;
13004 
13005   case OR_Deleted: {
13006     CandidateSet->NoteCandidates(
13007         PartialDiagnosticAt(Fn->getBeginLoc(),
13008                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13009                                 << ULE->getName() << Fn->getSourceRange()),
13010         SemaRef, OCD_AllCandidates, Args);
13011 
13012     // We emitted an error for the unavailable/deleted function call but keep
13013     // the call in the AST.
13014     FunctionDecl *FDecl = (*Best)->Function;
13015     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13016     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13017                                          ExecConfig, /*IsExecConfig=*/false,
13018                                          (*Best)->IsADLCandidate);
13019   }
13020   }
13021 
13022   // Overload resolution failed, try to recover.
13023   SmallVector<Expr *, 8> SubExprs = {Fn};
13024   SubExprs.append(Args.begin(), Args.end());
13025   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13026                                     chooseRecoveryType(*CandidateSet, Best));
13027 }
13028 
13029 static void markUnaddressableCandidatesUnviable(Sema &S,
13030                                                 OverloadCandidateSet &CS) {
13031   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13032     if (I->Viable &&
13033         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13034       I->Viable = false;
13035       I->FailureKind = ovl_fail_addr_not_available;
13036     }
13037   }
13038 }
13039 
13040 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13041 /// (which eventually refers to the declaration Func) and the call
13042 /// arguments Args/NumArgs, attempt to resolve the function call down
13043 /// to a specific function. If overload resolution succeeds, returns
13044 /// the call expression produced by overload resolution.
13045 /// Otherwise, emits diagnostics and returns ExprError.
13046 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13047                                          UnresolvedLookupExpr *ULE,
13048                                          SourceLocation LParenLoc,
13049                                          MultiExprArg Args,
13050                                          SourceLocation RParenLoc,
13051                                          Expr *ExecConfig,
13052                                          bool AllowTypoCorrection,
13053                                          bool CalleesAddressIsTaken) {
13054   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13055                                     OverloadCandidateSet::CSK_Normal);
13056   ExprResult result;
13057 
13058   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13059                              &result))
13060     return result;
13061 
13062   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13063   // functions that aren't addressible are considered unviable.
13064   if (CalleesAddressIsTaken)
13065     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13066 
13067   OverloadCandidateSet::iterator Best;
13068   OverloadingResult OverloadResult =
13069       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13070 
13071   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13072                                   ExecConfig, &CandidateSet, &Best,
13073                                   OverloadResult, AllowTypoCorrection);
13074 }
13075 
13076 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13077   return Functions.size() > 1 ||
13078          (Functions.size() == 1 &&
13079           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13080 }
13081 
13082 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13083                                             NestedNameSpecifierLoc NNSLoc,
13084                                             DeclarationNameInfo DNI,
13085                                             const UnresolvedSetImpl &Fns,
13086                                             bool PerformADL) {
13087   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13088                                       PerformADL, IsOverloaded(Fns),
13089                                       Fns.begin(), Fns.end());
13090 }
13091 
13092 /// Create a unary operation that may resolve to an overloaded
13093 /// operator.
13094 ///
13095 /// \param OpLoc The location of the operator itself (e.g., '*').
13096 ///
13097 /// \param Opc The UnaryOperatorKind that describes this operator.
13098 ///
13099 /// \param Fns The set of non-member functions that will be
13100 /// considered by overload resolution. The caller needs to build this
13101 /// set based on the context using, e.g.,
13102 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13103 /// set should not contain any member functions; those will be added
13104 /// by CreateOverloadedUnaryOp().
13105 ///
13106 /// \param Input The input argument.
13107 ExprResult
13108 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13109                               const UnresolvedSetImpl &Fns,
13110                               Expr *Input, bool PerformADL) {
13111   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13112   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13113   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13114   // TODO: provide better source location info.
13115   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13116 
13117   if (checkPlaceholderForOverload(*this, Input))
13118     return ExprError();
13119 
13120   Expr *Args[2] = { Input, nullptr };
13121   unsigned NumArgs = 1;
13122 
13123   // For post-increment and post-decrement, add the implicit '0' as
13124   // the second argument, so that we know this is a post-increment or
13125   // post-decrement.
13126   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13127     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13128     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13129                                      SourceLocation());
13130     NumArgs = 2;
13131   }
13132 
13133   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13134 
13135   if (Input->isTypeDependent()) {
13136     if (Fns.empty())
13137       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13138                                    VK_RValue, OK_Ordinary, OpLoc, false,
13139                                    CurFPFeatureOverrides());
13140 
13141     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13142     ExprResult Fn = CreateUnresolvedLookupExpr(
13143         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13144     if (Fn.isInvalid())
13145       return ExprError();
13146     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13147                                        Context.DependentTy, VK_RValue, OpLoc,
13148                                        CurFPFeatureOverrides());
13149   }
13150 
13151   // Build an empty overload set.
13152   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13153 
13154   // Add the candidates from the given function set.
13155   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13156 
13157   // Add operator candidates that are member functions.
13158   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13159 
13160   // Add candidates from ADL.
13161   if (PerformADL) {
13162     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13163                                          /*ExplicitTemplateArgs*/nullptr,
13164                                          CandidateSet);
13165   }
13166 
13167   // Add builtin operator candidates.
13168   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13169 
13170   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13171 
13172   // Perform overload resolution.
13173   OverloadCandidateSet::iterator Best;
13174   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13175   case OR_Success: {
13176     // We found a built-in operator or an overloaded operator.
13177     FunctionDecl *FnDecl = Best->Function;
13178 
13179     if (FnDecl) {
13180       Expr *Base = nullptr;
13181       // We matched an overloaded operator. Build a call to that
13182       // operator.
13183 
13184       // Convert the arguments.
13185       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13186         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13187 
13188         ExprResult InputRes =
13189           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13190                                               Best->FoundDecl, Method);
13191         if (InputRes.isInvalid())
13192           return ExprError();
13193         Base = Input = InputRes.get();
13194       } else {
13195         // Convert the arguments.
13196         ExprResult InputInit
13197           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13198                                                       Context,
13199                                                       FnDecl->getParamDecl(0)),
13200                                       SourceLocation(),
13201                                       Input);
13202         if (InputInit.isInvalid())
13203           return ExprError();
13204         Input = InputInit.get();
13205       }
13206 
13207       // Build the actual expression node.
13208       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13209                                                 Base, HadMultipleCandidates,
13210                                                 OpLoc);
13211       if (FnExpr.isInvalid())
13212         return ExprError();
13213 
13214       // Determine the result type.
13215       QualType ResultTy = FnDecl->getReturnType();
13216       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13217       ResultTy = ResultTy.getNonLValueExprType(Context);
13218 
13219       Args[0] = Input;
13220       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13221           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13222           CurFPFeatureOverrides(), Best->IsADLCandidate);
13223 
13224       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13225         return ExprError();
13226 
13227       if (CheckFunctionCall(FnDecl, TheCall,
13228                             FnDecl->getType()->castAs<FunctionProtoType>()))
13229         return ExprError();
13230       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13231     } else {
13232       // We matched a built-in operator. Convert the arguments, then
13233       // break out so that we will build the appropriate built-in
13234       // operator node.
13235       ExprResult InputRes = PerformImplicitConversion(
13236           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13237           CCK_ForBuiltinOverloadedOp);
13238       if (InputRes.isInvalid())
13239         return ExprError();
13240       Input = InputRes.get();
13241       break;
13242     }
13243   }
13244 
13245   case OR_No_Viable_Function:
13246     // This is an erroneous use of an operator which can be overloaded by
13247     // a non-member function. Check for non-member operators which were
13248     // defined too late to be candidates.
13249     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13250       // FIXME: Recover by calling the found function.
13251       return ExprError();
13252 
13253     // No viable function; fall through to handling this as a
13254     // built-in operator, which will produce an error message for us.
13255     break;
13256 
13257   case OR_Ambiguous:
13258     CandidateSet.NoteCandidates(
13259         PartialDiagnosticAt(OpLoc,
13260                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13261                                 << UnaryOperator::getOpcodeStr(Opc)
13262                                 << Input->getType() << Input->getSourceRange()),
13263         *this, OCD_AmbiguousCandidates, ArgsArray,
13264         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13265     return ExprError();
13266 
13267   case OR_Deleted:
13268     CandidateSet.NoteCandidates(
13269         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13270                                        << UnaryOperator::getOpcodeStr(Opc)
13271                                        << Input->getSourceRange()),
13272         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13273         OpLoc);
13274     return ExprError();
13275   }
13276 
13277   // Either we found no viable overloaded operator or we matched a
13278   // built-in operator. In either case, fall through to trying to
13279   // build a built-in operation.
13280   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13281 }
13282 
13283 /// Perform lookup for an overloaded binary operator.
13284 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13285                                  OverloadedOperatorKind Op,
13286                                  const UnresolvedSetImpl &Fns,
13287                                  ArrayRef<Expr *> Args, bool PerformADL) {
13288   SourceLocation OpLoc = CandidateSet.getLocation();
13289 
13290   OverloadedOperatorKind ExtraOp =
13291       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13292           ? getRewrittenOverloadedOperator(Op)
13293           : OO_None;
13294 
13295   // Add the candidates from the given function set. This also adds the
13296   // rewritten candidates using these functions if necessary.
13297   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13298 
13299   // Add operator candidates that are member functions.
13300   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13301   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13302     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13303                                 OverloadCandidateParamOrder::Reversed);
13304 
13305   // In C++20, also add any rewritten member candidates.
13306   if (ExtraOp) {
13307     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13308     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13309       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13310                                   CandidateSet,
13311                                   OverloadCandidateParamOrder::Reversed);
13312   }
13313 
13314   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13315   // performed for an assignment operator (nor for operator[] nor operator->,
13316   // which don't get here).
13317   if (Op != OO_Equal && PerformADL) {
13318     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13319     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13320                                          /*ExplicitTemplateArgs*/ nullptr,
13321                                          CandidateSet);
13322     if (ExtraOp) {
13323       DeclarationName ExtraOpName =
13324           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13325       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13326                                            /*ExplicitTemplateArgs*/ nullptr,
13327                                            CandidateSet);
13328     }
13329   }
13330 
13331   // Add builtin operator candidates.
13332   //
13333   // FIXME: We don't add any rewritten candidates here. This is strictly
13334   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13335   // resulting in our selecting a rewritten builtin candidate. For example:
13336   //
13337   //   enum class E { e };
13338   //   bool operator!=(E, E) requires false;
13339   //   bool k = E::e != E::e;
13340   //
13341   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13342   // it seems unreasonable to consider rewritten builtin candidates. A core
13343   // issue has been filed proposing to removed this requirement.
13344   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13345 }
13346 
13347 /// Create a binary operation that may resolve to an overloaded
13348 /// operator.
13349 ///
13350 /// \param OpLoc The location of the operator itself (e.g., '+').
13351 ///
13352 /// \param Opc The BinaryOperatorKind that describes this operator.
13353 ///
13354 /// \param Fns The set of non-member functions that will be
13355 /// considered by overload resolution. The caller needs to build this
13356 /// set based on the context using, e.g.,
13357 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13358 /// set should not contain any member functions; those will be added
13359 /// by CreateOverloadedBinOp().
13360 ///
13361 /// \param LHS Left-hand argument.
13362 /// \param RHS Right-hand argument.
13363 /// \param PerformADL Whether to consider operator candidates found by ADL.
13364 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13365 ///        C++20 operator rewrites.
13366 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13367 ///        the function in question. Such a function is never a candidate in
13368 ///        our overload resolution. This also enables synthesizing a three-way
13369 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13370 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13371                                        BinaryOperatorKind Opc,
13372                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13373                                        Expr *RHS, bool PerformADL,
13374                                        bool AllowRewrittenCandidates,
13375                                        FunctionDecl *DefaultedFn) {
13376   Expr *Args[2] = { LHS, RHS };
13377   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13378 
13379   if (!getLangOpts().CPlusPlus20)
13380     AllowRewrittenCandidates = false;
13381 
13382   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13383 
13384   // If either side is type-dependent, create an appropriate dependent
13385   // expression.
13386   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13387     if (Fns.empty()) {
13388       // If there are no functions to store, just build a dependent
13389       // BinaryOperator or CompoundAssignment.
13390       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13391         return CompoundAssignOperator::Create(
13392             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13393             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13394             Context.DependentTy);
13395       return BinaryOperator::Create(Context, Args[0], Args[1], Opc,
13396                                     Context.DependentTy, VK_RValue, OK_Ordinary,
13397                                     OpLoc, CurFPFeatureOverrides());
13398     }
13399 
13400     // FIXME: save results of ADL from here?
13401     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13402     // TODO: provide better source location info in DNLoc component.
13403     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13404     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13405     ExprResult Fn = CreateUnresolvedLookupExpr(
13406         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13407     if (Fn.isInvalid())
13408       return ExprError();
13409     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13410                                        Context.DependentTy, VK_RValue, OpLoc,
13411                                        CurFPFeatureOverrides());
13412   }
13413 
13414   // Always do placeholder-like conversions on the RHS.
13415   if (checkPlaceholderForOverload(*this, Args[1]))
13416     return ExprError();
13417 
13418   // Do placeholder-like conversion on the LHS; note that we should
13419   // not get here with a PseudoObject LHS.
13420   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13421   if (checkPlaceholderForOverload(*this, Args[0]))
13422     return ExprError();
13423 
13424   // If this is the assignment operator, we only perform overload resolution
13425   // if the left-hand side is a class or enumeration type. This is actually
13426   // a hack. The standard requires that we do overload resolution between the
13427   // various built-in candidates, but as DR507 points out, this can lead to
13428   // problems. So we do it this way, which pretty much follows what GCC does.
13429   // Note that we go the traditional code path for compound assignment forms.
13430   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13431     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13432 
13433   // If this is the .* operator, which is not overloadable, just
13434   // create a built-in binary operator.
13435   if (Opc == BO_PtrMemD)
13436     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13437 
13438   // Build the overload set.
13439   OverloadCandidateSet CandidateSet(
13440       OpLoc, OverloadCandidateSet::CSK_Operator,
13441       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13442   if (DefaultedFn)
13443     CandidateSet.exclude(DefaultedFn);
13444   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13445 
13446   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13447 
13448   // Perform overload resolution.
13449   OverloadCandidateSet::iterator Best;
13450   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13451     case OR_Success: {
13452       // We found a built-in operator or an overloaded operator.
13453       FunctionDecl *FnDecl = Best->Function;
13454 
13455       bool IsReversed = Best->isReversed();
13456       if (IsReversed)
13457         std::swap(Args[0], Args[1]);
13458 
13459       if (FnDecl) {
13460         Expr *Base = nullptr;
13461         // We matched an overloaded operator. Build a call to that
13462         // operator.
13463 
13464         OverloadedOperatorKind ChosenOp =
13465             FnDecl->getDeclName().getCXXOverloadedOperator();
13466 
13467         // C++2a [over.match.oper]p9:
13468         //   If a rewritten operator== candidate is selected by overload
13469         //   resolution for an operator@, its return type shall be cv bool
13470         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13471             !FnDecl->getReturnType()->isBooleanType()) {
13472           bool IsExtension =
13473               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13474           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13475                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13476               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13477               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13478           Diag(FnDecl->getLocation(), diag::note_declared_at);
13479           if (!IsExtension)
13480             return ExprError();
13481         }
13482 
13483         if (AllowRewrittenCandidates && !IsReversed &&
13484             CandidateSet.getRewriteInfo().isReversible()) {
13485           // We could have reversed this operator, but didn't. Check if some
13486           // reversed form was a viable candidate, and if so, if it had a
13487           // better conversion for either parameter. If so, this call is
13488           // formally ambiguous, and allowing it is an extension.
13489           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13490           for (OverloadCandidate &Cand : CandidateSet) {
13491             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13492                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13493               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13494                 if (CompareImplicitConversionSequences(
13495                         *this, OpLoc, Cand.Conversions[ArgIdx],
13496                         Best->Conversions[ArgIdx]) ==
13497                     ImplicitConversionSequence::Better) {
13498                   AmbiguousWith.push_back(Cand.Function);
13499                   break;
13500                 }
13501               }
13502             }
13503           }
13504 
13505           if (!AmbiguousWith.empty()) {
13506             bool AmbiguousWithSelf =
13507                 AmbiguousWith.size() == 1 &&
13508                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13509             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13510                 << BinaryOperator::getOpcodeStr(Opc)
13511                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13512                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13513             if (AmbiguousWithSelf) {
13514               Diag(FnDecl->getLocation(),
13515                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13516             } else {
13517               Diag(FnDecl->getLocation(),
13518                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13519               for (auto *F : AmbiguousWith)
13520                 Diag(F->getLocation(),
13521                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13522             }
13523           }
13524         }
13525 
13526         // Convert the arguments.
13527         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13528           // Best->Access is only meaningful for class members.
13529           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13530 
13531           ExprResult Arg1 =
13532             PerformCopyInitialization(
13533               InitializedEntity::InitializeParameter(Context,
13534                                                      FnDecl->getParamDecl(0)),
13535               SourceLocation(), Args[1]);
13536           if (Arg1.isInvalid())
13537             return ExprError();
13538 
13539           ExprResult Arg0 =
13540             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13541                                                 Best->FoundDecl, Method);
13542           if (Arg0.isInvalid())
13543             return ExprError();
13544           Base = Args[0] = Arg0.getAs<Expr>();
13545           Args[1] = RHS = Arg1.getAs<Expr>();
13546         } else {
13547           // Convert the arguments.
13548           ExprResult Arg0 = PerformCopyInitialization(
13549             InitializedEntity::InitializeParameter(Context,
13550                                                    FnDecl->getParamDecl(0)),
13551             SourceLocation(), Args[0]);
13552           if (Arg0.isInvalid())
13553             return ExprError();
13554 
13555           ExprResult Arg1 =
13556             PerformCopyInitialization(
13557               InitializedEntity::InitializeParameter(Context,
13558                                                      FnDecl->getParamDecl(1)),
13559               SourceLocation(), Args[1]);
13560           if (Arg1.isInvalid())
13561             return ExprError();
13562           Args[0] = LHS = Arg0.getAs<Expr>();
13563           Args[1] = RHS = Arg1.getAs<Expr>();
13564         }
13565 
13566         // Build the actual expression node.
13567         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13568                                                   Best->FoundDecl, Base,
13569                                                   HadMultipleCandidates, OpLoc);
13570         if (FnExpr.isInvalid())
13571           return ExprError();
13572 
13573         // Determine the result type.
13574         QualType ResultTy = FnDecl->getReturnType();
13575         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13576         ResultTy = ResultTy.getNonLValueExprType(Context);
13577 
13578         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13579             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13580             CurFPFeatureOverrides(), Best->IsADLCandidate);
13581 
13582         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13583                                 FnDecl))
13584           return ExprError();
13585 
13586         ArrayRef<const Expr *> ArgsArray(Args, 2);
13587         const Expr *ImplicitThis = nullptr;
13588         // Cut off the implicit 'this'.
13589         if (isa<CXXMethodDecl>(FnDecl)) {
13590           ImplicitThis = ArgsArray[0];
13591           ArgsArray = ArgsArray.slice(1);
13592         }
13593 
13594         // Check for a self move.
13595         if (Op == OO_Equal)
13596           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13597 
13598         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13599                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13600                   VariadicDoesNotApply);
13601 
13602         ExprResult R = MaybeBindToTemporary(TheCall);
13603         if (R.isInvalid())
13604           return ExprError();
13605 
13606         R = CheckForImmediateInvocation(R, FnDecl);
13607         if (R.isInvalid())
13608           return ExprError();
13609 
13610         // For a rewritten candidate, we've already reversed the arguments
13611         // if needed. Perform the rest of the rewrite now.
13612         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13613             (Op == OO_Spaceship && IsReversed)) {
13614           if (Op == OO_ExclaimEqual) {
13615             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13616             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13617           } else {
13618             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13619             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13620             Expr *ZeroLiteral =
13621                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13622 
13623             Sema::CodeSynthesisContext Ctx;
13624             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13625             Ctx.Entity = FnDecl;
13626             pushCodeSynthesisContext(Ctx);
13627 
13628             R = CreateOverloadedBinOp(
13629                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13630                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13631                 /*AllowRewrittenCandidates=*/false);
13632 
13633             popCodeSynthesisContext();
13634           }
13635           if (R.isInvalid())
13636             return ExprError();
13637         } else {
13638           assert(ChosenOp == Op && "unexpected operator name");
13639         }
13640 
13641         // Make a note in the AST if we did any rewriting.
13642         if (Best->RewriteKind != CRK_None)
13643           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13644 
13645         return R;
13646       } else {
13647         // We matched a built-in operator. Convert the arguments, then
13648         // break out so that we will build the appropriate built-in
13649         // operator node.
13650         ExprResult ArgsRes0 = PerformImplicitConversion(
13651             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13652             AA_Passing, CCK_ForBuiltinOverloadedOp);
13653         if (ArgsRes0.isInvalid())
13654           return ExprError();
13655         Args[0] = ArgsRes0.get();
13656 
13657         ExprResult ArgsRes1 = PerformImplicitConversion(
13658             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13659             AA_Passing, CCK_ForBuiltinOverloadedOp);
13660         if (ArgsRes1.isInvalid())
13661           return ExprError();
13662         Args[1] = ArgsRes1.get();
13663         break;
13664       }
13665     }
13666 
13667     case OR_No_Viable_Function: {
13668       // C++ [over.match.oper]p9:
13669       //   If the operator is the operator , [...] and there are no
13670       //   viable functions, then the operator is assumed to be the
13671       //   built-in operator and interpreted according to clause 5.
13672       if (Opc == BO_Comma)
13673         break;
13674 
13675       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13676       // compare result using '==' and '<'.
13677       if (DefaultedFn && Opc == BO_Cmp) {
13678         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13679                                                           Args[1], DefaultedFn);
13680         if (E.isInvalid() || E.isUsable())
13681           return E;
13682       }
13683 
13684       // For class as left operand for assignment or compound assignment
13685       // operator do not fall through to handling in built-in, but report that
13686       // no overloaded assignment operator found
13687       ExprResult Result = ExprError();
13688       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13689       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13690                                                    Args, OpLoc);
13691       if (Args[0]->getType()->isRecordType() &&
13692           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13693         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13694              << BinaryOperator::getOpcodeStr(Opc)
13695              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13696         if (Args[0]->getType()->isIncompleteType()) {
13697           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13698             << Args[0]->getType()
13699             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13700         }
13701       } else {
13702         // This is an erroneous use of an operator which can be overloaded by
13703         // a non-member function. Check for non-member operators which were
13704         // defined too late to be candidates.
13705         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13706           // FIXME: Recover by calling the found function.
13707           return ExprError();
13708 
13709         // No viable function; try to create a built-in operation, which will
13710         // produce an error. Then, show the non-viable candidates.
13711         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13712       }
13713       assert(Result.isInvalid() &&
13714              "C++ binary operator overloading is missing candidates!");
13715       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13716       return Result;
13717     }
13718 
13719     case OR_Ambiguous:
13720       CandidateSet.NoteCandidates(
13721           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13722                                          << BinaryOperator::getOpcodeStr(Opc)
13723                                          << Args[0]->getType()
13724                                          << Args[1]->getType()
13725                                          << Args[0]->getSourceRange()
13726                                          << Args[1]->getSourceRange()),
13727           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13728           OpLoc);
13729       return ExprError();
13730 
13731     case OR_Deleted:
13732       if (isImplicitlyDeleted(Best->Function)) {
13733         FunctionDecl *DeletedFD = Best->Function;
13734         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13735         if (DFK.isSpecialMember()) {
13736           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13737             << Args[0]->getType() << DFK.asSpecialMember();
13738         } else {
13739           assert(DFK.isComparison());
13740           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13741             << Args[0]->getType() << DeletedFD;
13742         }
13743 
13744         // The user probably meant to call this special member. Just
13745         // explain why it's deleted.
13746         NoteDeletedFunction(DeletedFD);
13747         return ExprError();
13748       }
13749       CandidateSet.NoteCandidates(
13750           PartialDiagnosticAt(
13751               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13752                          << getOperatorSpelling(Best->Function->getDeclName()
13753                                                     .getCXXOverloadedOperator())
13754                          << Args[0]->getSourceRange()
13755                          << Args[1]->getSourceRange()),
13756           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13757           OpLoc);
13758       return ExprError();
13759   }
13760 
13761   // We matched a built-in operator; build it.
13762   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13763 }
13764 
13765 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13766     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13767     FunctionDecl *DefaultedFn) {
13768   const ComparisonCategoryInfo *Info =
13769       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13770   // If we're not producing a known comparison category type, we can't
13771   // synthesize a three-way comparison. Let the caller diagnose this.
13772   if (!Info)
13773     return ExprResult((Expr*)nullptr);
13774 
13775   // If we ever want to perform this synthesis more generally, we will need to
13776   // apply the temporary materialization conversion to the operands.
13777   assert(LHS->isGLValue() && RHS->isGLValue() &&
13778          "cannot use prvalue expressions more than once");
13779   Expr *OrigLHS = LHS;
13780   Expr *OrigRHS = RHS;
13781 
13782   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13783   // each of them multiple times below.
13784   LHS = new (Context)
13785       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13786                       LHS->getObjectKind(), LHS);
13787   RHS = new (Context)
13788       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13789                       RHS->getObjectKind(), RHS);
13790 
13791   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13792                                         DefaultedFn);
13793   if (Eq.isInvalid())
13794     return ExprError();
13795 
13796   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13797                                           true, DefaultedFn);
13798   if (Less.isInvalid())
13799     return ExprError();
13800 
13801   ExprResult Greater;
13802   if (Info->isPartial()) {
13803     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13804                                     DefaultedFn);
13805     if (Greater.isInvalid())
13806       return ExprError();
13807   }
13808 
13809   // Form the list of comparisons we're going to perform.
13810   struct Comparison {
13811     ExprResult Cmp;
13812     ComparisonCategoryResult Result;
13813   } Comparisons[4] =
13814   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13815                           : ComparisonCategoryResult::Equivalent},
13816     {Less, ComparisonCategoryResult::Less},
13817     {Greater, ComparisonCategoryResult::Greater},
13818     {ExprResult(), ComparisonCategoryResult::Unordered},
13819   };
13820 
13821   int I = Info->isPartial() ? 3 : 2;
13822 
13823   // Combine the comparisons with suitable conditional expressions.
13824   ExprResult Result;
13825   for (; I >= 0; --I) {
13826     // Build a reference to the comparison category constant.
13827     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13828     // FIXME: Missing a constant for a comparison category. Diagnose this?
13829     if (!VI)
13830       return ExprResult((Expr*)nullptr);
13831     ExprResult ThisResult =
13832         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13833     if (ThisResult.isInvalid())
13834       return ExprError();
13835 
13836     // Build a conditional unless this is the final case.
13837     if (Result.get()) {
13838       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13839                                   ThisResult.get(), Result.get());
13840       if (Result.isInvalid())
13841         return ExprError();
13842     } else {
13843       Result = ThisResult;
13844     }
13845   }
13846 
13847   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13848   // bind the OpaqueValueExprs before they're (repeatedly) used.
13849   Expr *SyntacticForm = BinaryOperator::Create(
13850       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13851       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13852       CurFPFeatureOverrides());
13853   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13854   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13855 }
13856 
13857 ExprResult
13858 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13859                                          SourceLocation RLoc,
13860                                          Expr *Base, Expr *Idx) {
13861   Expr *Args[2] = { Base, Idx };
13862   DeclarationName OpName =
13863       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13864 
13865   // If either side is type-dependent, create an appropriate dependent
13866   // expression.
13867   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13868 
13869     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13870     // CHECKME: no 'operator' keyword?
13871     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13872     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13873     ExprResult Fn = CreateUnresolvedLookupExpr(
13874         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
13875     if (Fn.isInvalid())
13876       return ExprError();
13877     // Can't add any actual overloads yet
13878 
13879     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
13880                                        Context.DependentTy, VK_RValue, RLoc,
13881                                        CurFPFeatureOverrides());
13882   }
13883 
13884   // Handle placeholders on both operands.
13885   if (checkPlaceholderForOverload(*this, Args[0]))
13886     return ExprError();
13887   if (checkPlaceholderForOverload(*this, Args[1]))
13888     return ExprError();
13889 
13890   // Build an empty overload set.
13891   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13892 
13893   // Subscript can only be overloaded as a member function.
13894 
13895   // Add operator candidates that are member functions.
13896   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13897 
13898   // Add builtin operator candidates.
13899   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13900 
13901   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13902 
13903   // Perform overload resolution.
13904   OverloadCandidateSet::iterator Best;
13905   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13906     case OR_Success: {
13907       // We found a built-in operator or an overloaded operator.
13908       FunctionDecl *FnDecl = Best->Function;
13909 
13910       if (FnDecl) {
13911         // We matched an overloaded operator. Build a call to that
13912         // operator.
13913 
13914         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13915 
13916         // Convert the arguments.
13917         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13918         ExprResult Arg0 =
13919           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13920                                               Best->FoundDecl, Method);
13921         if (Arg0.isInvalid())
13922           return ExprError();
13923         Args[0] = Arg0.get();
13924 
13925         // Convert the arguments.
13926         ExprResult InputInit
13927           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13928                                                       Context,
13929                                                       FnDecl->getParamDecl(0)),
13930                                       SourceLocation(),
13931                                       Args[1]);
13932         if (InputInit.isInvalid())
13933           return ExprError();
13934 
13935         Args[1] = InputInit.getAs<Expr>();
13936 
13937         // Build the actual expression node.
13938         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13939         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13940         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13941                                                   Best->FoundDecl,
13942                                                   Base,
13943                                                   HadMultipleCandidates,
13944                                                   OpLocInfo.getLoc(),
13945                                                   OpLocInfo.getInfo());
13946         if (FnExpr.isInvalid())
13947           return ExprError();
13948 
13949         // Determine the result type
13950         QualType ResultTy = FnDecl->getReturnType();
13951         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13952         ResultTy = ResultTy.getNonLValueExprType(Context);
13953 
13954         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13955             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13956             CurFPFeatureOverrides());
13957         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13958           return ExprError();
13959 
13960         if (CheckFunctionCall(Method, TheCall,
13961                               Method->getType()->castAs<FunctionProtoType>()))
13962           return ExprError();
13963 
13964         return MaybeBindToTemporary(TheCall);
13965       } else {
13966         // We matched a built-in operator. Convert the arguments, then
13967         // break out so that we will build the appropriate built-in
13968         // operator node.
13969         ExprResult ArgsRes0 = PerformImplicitConversion(
13970             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13971             AA_Passing, CCK_ForBuiltinOverloadedOp);
13972         if (ArgsRes0.isInvalid())
13973           return ExprError();
13974         Args[0] = ArgsRes0.get();
13975 
13976         ExprResult ArgsRes1 = PerformImplicitConversion(
13977             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13978             AA_Passing, CCK_ForBuiltinOverloadedOp);
13979         if (ArgsRes1.isInvalid())
13980           return ExprError();
13981         Args[1] = ArgsRes1.get();
13982 
13983         break;
13984       }
13985     }
13986 
13987     case OR_No_Viable_Function: {
13988       PartialDiagnostic PD = CandidateSet.empty()
13989           ? (PDiag(diag::err_ovl_no_oper)
13990              << Args[0]->getType() << /*subscript*/ 0
13991              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13992           : (PDiag(diag::err_ovl_no_viable_subscript)
13993              << Args[0]->getType() << Args[0]->getSourceRange()
13994              << Args[1]->getSourceRange());
13995       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13996                                   OCD_AllCandidates, Args, "[]", LLoc);
13997       return ExprError();
13998     }
13999 
14000     case OR_Ambiguous:
14001       CandidateSet.NoteCandidates(
14002           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14003                                         << "[]" << Args[0]->getType()
14004                                         << Args[1]->getType()
14005                                         << Args[0]->getSourceRange()
14006                                         << Args[1]->getSourceRange()),
14007           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14008       return ExprError();
14009 
14010     case OR_Deleted:
14011       CandidateSet.NoteCandidates(
14012           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14013                                         << "[]" << Args[0]->getSourceRange()
14014                                         << Args[1]->getSourceRange()),
14015           *this, OCD_AllCandidates, Args, "[]", LLoc);
14016       return ExprError();
14017     }
14018 
14019   // We matched a built-in operator; build it.
14020   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14021 }
14022 
14023 /// BuildCallToMemberFunction - Build a call to a member
14024 /// function. MemExpr is the expression that refers to the member
14025 /// function (and includes the object parameter), Args/NumArgs are the
14026 /// arguments to the function call (not including the object
14027 /// parameter). The caller needs to validate that the member
14028 /// expression refers to a non-static member function or an overloaded
14029 /// member function.
14030 ExprResult
14031 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14032                                 SourceLocation LParenLoc,
14033                                 MultiExprArg Args,
14034                                 SourceLocation RParenLoc) {
14035   assert(MemExprE->getType() == Context.BoundMemberTy ||
14036          MemExprE->getType() == Context.OverloadTy);
14037 
14038   // Dig out the member expression. This holds both the object
14039   // argument and the member function we're referring to.
14040   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14041 
14042   // Determine whether this is a call to a pointer-to-member function.
14043   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14044     assert(op->getType() == Context.BoundMemberTy);
14045     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14046 
14047     QualType fnType =
14048       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14049 
14050     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14051     QualType resultType = proto->getCallResultType(Context);
14052     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14053 
14054     // Check that the object type isn't more qualified than the
14055     // member function we're calling.
14056     Qualifiers funcQuals = proto->getMethodQuals();
14057 
14058     QualType objectType = op->getLHS()->getType();
14059     if (op->getOpcode() == BO_PtrMemI)
14060       objectType = objectType->castAs<PointerType>()->getPointeeType();
14061     Qualifiers objectQuals = objectType.getQualifiers();
14062 
14063     Qualifiers difference = objectQuals - funcQuals;
14064     difference.removeObjCGCAttr();
14065     difference.removeAddressSpace();
14066     if (difference) {
14067       std::string qualsString = difference.getAsString();
14068       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14069         << fnType.getUnqualifiedType()
14070         << qualsString
14071         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14072     }
14073 
14074     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14075         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14076         CurFPFeatureOverrides(), proto->getNumParams());
14077 
14078     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14079                             call, nullptr))
14080       return ExprError();
14081 
14082     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14083       return ExprError();
14084 
14085     if (CheckOtherCall(call, proto))
14086       return ExprError();
14087 
14088     return MaybeBindToTemporary(call);
14089   }
14090 
14091   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14092     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14093                             RParenLoc, CurFPFeatureOverrides());
14094 
14095   UnbridgedCastsSet UnbridgedCasts;
14096   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14097     return ExprError();
14098 
14099   MemberExpr *MemExpr;
14100   CXXMethodDecl *Method = nullptr;
14101   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14102   NestedNameSpecifier *Qualifier = nullptr;
14103   if (isa<MemberExpr>(NakedMemExpr)) {
14104     MemExpr = cast<MemberExpr>(NakedMemExpr);
14105     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14106     FoundDecl = MemExpr->getFoundDecl();
14107     Qualifier = MemExpr->getQualifier();
14108     UnbridgedCasts.restore();
14109   } else {
14110     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14111     Qualifier = UnresExpr->getQualifier();
14112 
14113     QualType ObjectType = UnresExpr->getBaseType();
14114     Expr::Classification ObjectClassification
14115       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14116                             : UnresExpr->getBase()->Classify(Context);
14117 
14118     // Add overload candidates
14119     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14120                                       OverloadCandidateSet::CSK_Normal);
14121 
14122     // FIXME: avoid copy.
14123     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14124     if (UnresExpr->hasExplicitTemplateArgs()) {
14125       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14126       TemplateArgs = &TemplateArgsBuffer;
14127     }
14128 
14129     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14130            E = UnresExpr->decls_end(); I != E; ++I) {
14131 
14132       NamedDecl *Func = *I;
14133       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14134       if (isa<UsingShadowDecl>(Func))
14135         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14136 
14137 
14138       // Microsoft supports direct constructor calls.
14139       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14140         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14141                              CandidateSet,
14142                              /*SuppressUserConversions*/ false);
14143       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14144         // If explicit template arguments were provided, we can't call a
14145         // non-template member function.
14146         if (TemplateArgs)
14147           continue;
14148 
14149         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14150                            ObjectClassification, Args, CandidateSet,
14151                            /*SuppressUserConversions=*/false);
14152       } else {
14153         AddMethodTemplateCandidate(
14154             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14155             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14156             /*SuppressUserConversions=*/false);
14157       }
14158     }
14159 
14160     DeclarationName DeclName = UnresExpr->getMemberName();
14161 
14162     UnbridgedCasts.restore();
14163 
14164     OverloadCandidateSet::iterator Best;
14165     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14166                                             Best)) {
14167     case OR_Success:
14168       Method = cast<CXXMethodDecl>(Best->Function);
14169       FoundDecl = Best->FoundDecl;
14170       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14171       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14172         return ExprError();
14173       // If FoundDecl is different from Method (such as if one is a template
14174       // and the other a specialization), make sure DiagnoseUseOfDecl is
14175       // called on both.
14176       // FIXME: This would be more comprehensively addressed by modifying
14177       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14178       // being used.
14179       if (Method != FoundDecl.getDecl() &&
14180                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14181         return ExprError();
14182       break;
14183 
14184     case OR_No_Viable_Function:
14185       CandidateSet.NoteCandidates(
14186           PartialDiagnosticAt(
14187               UnresExpr->getMemberLoc(),
14188               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14189                   << DeclName << MemExprE->getSourceRange()),
14190           *this, OCD_AllCandidates, Args);
14191       // FIXME: Leaking incoming expressions!
14192       return ExprError();
14193 
14194     case OR_Ambiguous:
14195       CandidateSet.NoteCandidates(
14196           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14197                               PDiag(diag::err_ovl_ambiguous_member_call)
14198                                   << DeclName << MemExprE->getSourceRange()),
14199           *this, OCD_AmbiguousCandidates, Args);
14200       // FIXME: Leaking incoming expressions!
14201       return ExprError();
14202 
14203     case OR_Deleted:
14204       CandidateSet.NoteCandidates(
14205           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14206                               PDiag(diag::err_ovl_deleted_member_call)
14207                                   << DeclName << MemExprE->getSourceRange()),
14208           *this, OCD_AllCandidates, Args);
14209       // FIXME: Leaking incoming expressions!
14210       return ExprError();
14211     }
14212 
14213     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14214 
14215     // If overload resolution picked a static member, build a
14216     // non-member call based on that function.
14217     if (Method->isStatic()) {
14218       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14219                                    RParenLoc);
14220     }
14221 
14222     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14223   }
14224 
14225   QualType ResultType = Method->getReturnType();
14226   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14227   ResultType = ResultType.getNonLValueExprType(Context);
14228 
14229   assert(Method && "Member call to something that isn't a method?");
14230   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14231   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14232       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14233       CurFPFeatureOverrides(), Proto->getNumParams());
14234 
14235   // Check for a valid return type.
14236   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14237                           TheCall, Method))
14238     return ExprError();
14239 
14240   // Convert the object argument (for a non-static member function call).
14241   // We only need to do this if there was actually an overload; otherwise
14242   // it was done at lookup.
14243   if (!Method->isStatic()) {
14244     ExprResult ObjectArg =
14245       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14246                                           FoundDecl, Method);
14247     if (ObjectArg.isInvalid())
14248       return ExprError();
14249     MemExpr->setBase(ObjectArg.get());
14250   }
14251 
14252   // Convert the rest of the arguments
14253   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14254                               RParenLoc))
14255     return ExprError();
14256 
14257   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14258 
14259   if (CheckFunctionCall(Method, TheCall, Proto))
14260     return ExprError();
14261 
14262   // In the case the method to call was not selected by the overloading
14263   // resolution process, we still need to handle the enable_if attribute. Do
14264   // that here, so it will not hide previous -- and more relevant -- errors.
14265   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14266     if (const EnableIfAttr *Attr =
14267             CheckEnableIf(Method, LParenLoc, Args, true)) {
14268       Diag(MemE->getMemberLoc(),
14269            diag::err_ovl_no_viable_member_function_in_call)
14270           << Method << Method->getSourceRange();
14271       Diag(Method->getLocation(),
14272            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14273           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14274       return ExprError();
14275     }
14276   }
14277 
14278   if ((isa<CXXConstructorDecl>(CurContext) ||
14279        isa<CXXDestructorDecl>(CurContext)) &&
14280       TheCall->getMethodDecl()->isPure()) {
14281     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14282 
14283     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14284         MemExpr->performsVirtualDispatch(getLangOpts())) {
14285       Diag(MemExpr->getBeginLoc(),
14286            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14287           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14288           << MD->getParent();
14289 
14290       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14291       if (getLangOpts().AppleKext)
14292         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14293             << MD->getParent() << MD->getDeclName();
14294     }
14295   }
14296 
14297   if (CXXDestructorDecl *DD =
14298           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14299     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14300     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14301     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14302                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14303                          MemExpr->getMemberLoc());
14304   }
14305 
14306   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14307                                      TheCall->getMethodDecl());
14308 }
14309 
14310 /// BuildCallToObjectOfClassType - Build a call to an object of class
14311 /// type (C++ [over.call.object]), which can end up invoking an
14312 /// overloaded function call operator (@c operator()) or performing a
14313 /// user-defined conversion on the object argument.
14314 ExprResult
14315 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14316                                    SourceLocation LParenLoc,
14317                                    MultiExprArg Args,
14318                                    SourceLocation RParenLoc) {
14319   if (checkPlaceholderForOverload(*this, Obj))
14320     return ExprError();
14321   ExprResult Object = Obj;
14322 
14323   UnbridgedCastsSet UnbridgedCasts;
14324   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14325     return ExprError();
14326 
14327   assert(Object.get()->getType()->isRecordType() &&
14328          "Requires object type argument");
14329 
14330   // C++ [over.call.object]p1:
14331   //  If the primary-expression E in the function call syntax
14332   //  evaluates to a class object of type "cv T", then the set of
14333   //  candidate functions includes at least the function call
14334   //  operators of T. The function call operators of T are obtained by
14335   //  ordinary lookup of the name operator() in the context of
14336   //  (E).operator().
14337   OverloadCandidateSet CandidateSet(LParenLoc,
14338                                     OverloadCandidateSet::CSK_Operator);
14339   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14340 
14341   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14342                           diag::err_incomplete_object_call, Object.get()))
14343     return true;
14344 
14345   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14346   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14347   LookupQualifiedName(R, Record->getDecl());
14348   R.suppressDiagnostics();
14349 
14350   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14351        Oper != OperEnd; ++Oper) {
14352     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14353                        Object.get()->Classify(Context), Args, CandidateSet,
14354                        /*SuppressUserConversion=*/false);
14355   }
14356 
14357   // C++ [over.call.object]p2:
14358   //   In addition, for each (non-explicit in C++0x) conversion function
14359   //   declared in T of the form
14360   //
14361   //        operator conversion-type-id () cv-qualifier;
14362   //
14363   //   where cv-qualifier is the same cv-qualification as, or a
14364   //   greater cv-qualification than, cv, and where conversion-type-id
14365   //   denotes the type "pointer to function of (P1,...,Pn) returning
14366   //   R", or the type "reference to pointer to function of
14367   //   (P1,...,Pn) returning R", or the type "reference to function
14368   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14369   //   is also considered as a candidate function. Similarly,
14370   //   surrogate call functions are added to the set of candidate
14371   //   functions for each conversion function declared in an
14372   //   accessible base class provided the function is not hidden
14373   //   within T by another intervening declaration.
14374   const auto &Conversions =
14375       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14376   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14377     NamedDecl *D = *I;
14378     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14379     if (isa<UsingShadowDecl>(D))
14380       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14381 
14382     // Skip over templated conversion functions; they aren't
14383     // surrogates.
14384     if (isa<FunctionTemplateDecl>(D))
14385       continue;
14386 
14387     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14388     if (!Conv->isExplicit()) {
14389       // Strip the reference type (if any) and then the pointer type (if
14390       // any) to get down to what might be a function type.
14391       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14392       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14393         ConvType = ConvPtrType->getPointeeType();
14394 
14395       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14396       {
14397         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14398                               Object.get(), Args, CandidateSet);
14399       }
14400     }
14401   }
14402 
14403   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14404 
14405   // Perform overload resolution.
14406   OverloadCandidateSet::iterator Best;
14407   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14408                                           Best)) {
14409   case OR_Success:
14410     // Overload resolution succeeded; we'll build the appropriate call
14411     // below.
14412     break;
14413 
14414   case OR_No_Viable_Function: {
14415     PartialDiagnostic PD =
14416         CandidateSet.empty()
14417             ? (PDiag(diag::err_ovl_no_oper)
14418                << Object.get()->getType() << /*call*/ 1
14419                << Object.get()->getSourceRange())
14420             : (PDiag(diag::err_ovl_no_viable_object_call)
14421                << Object.get()->getType() << Object.get()->getSourceRange());
14422     CandidateSet.NoteCandidates(
14423         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14424         OCD_AllCandidates, Args);
14425     break;
14426   }
14427   case OR_Ambiguous:
14428     CandidateSet.NoteCandidates(
14429         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14430                             PDiag(diag::err_ovl_ambiguous_object_call)
14431                                 << Object.get()->getType()
14432                                 << Object.get()->getSourceRange()),
14433         *this, OCD_AmbiguousCandidates, Args);
14434     break;
14435 
14436   case OR_Deleted:
14437     CandidateSet.NoteCandidates(
14438         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14439                             PDiag(diag::err_ovl_deleted_object_call)
14440                                 << Object.get()->getType()
14441                                 << Object.get()->getSourceRange()),
14442         *this, OCD_AllCandidates, Args);
14443     break;
14444   }
14445 
14446   if (Best == CandidateSet.end())
14447     return true;
14448 
14449   UnbridgedCasts.restore();
14450 
14451   if (Best->Function == nullptr) {
14452     // Since there is no function declaration, this is one of the
14453     // surrogate candidates. Dig out the conversion function.
14454     CXXConversionDecl *Conv
14455       = cast<CXXConversionDecl>(
14456                          Best->Conversions[0].UserDefined.ConversionFunction);
14457 
14458     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14459                               Best->FoundDecl);
14460     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14461       return ExprError();
14462     assert(Conv == Best->FoundDecl.getDecl() &&
14463              "Found Decl & conversion-to-functionptr should be same, right?!");
14464     // We selected one of the surrogate functions that converts the
14465     // object parameter to a function pointer. Perform the conversion
14466     // on the object argument, then let BuildCallExpr finish the job.
14467 
14468     // Create an implicit member expr to refer to the conversion operator.
14469     // and then call it.
14470     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14471                                              Conv, HadMultipleCandidates);
14472     if (Call.isInvalid())
14473       return ExprError();
14474     // Record usage of conversion in an implicit cast.
14475     Call = ImplicitCastExpr::Create(
14476         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14477         nullptr, VK_RValue, CurFPFeatureOverrides());
14478 
14479     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14480   }
14481 
14482   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14483 
14484   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14485   // that calls this method, using Object for the implicit object
14486   // parameter and passing along the remaining arguments.
14487   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14488 
14489   // An error diagnostic has already been printed when parsing the declaration.
14490   if (Method->isInvalidDecl())
14491     return ExprError();
14492 
14493   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14494   unsigned NumParams = Proto->getNumParams();
14495 
14496   DeclarationNameInfo OpLocInfo(
14497                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14498   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14499   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14500                                            Obj, HadMultipleCandidates,
14501                                            OpLocInfo.getLoc(),
14502                                            OpLocInfo.getInfo());
14503   if (NewFn.isInvalid())
14504     return true;
14505 
14506   // The number of argument slots to allocate in the call. If we have default
14507   // arguments we need to allocate space for them as well. We additionally
14508   // need one more slot for the object parameter.
14509   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14510 
14511   // Build the full argument list for the method call (the implicit object
14512   // parameter is placed at the beginning of the list).
14513   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14514 
14515   bool IsError = false;
14516 
14517   // Initialize the implicit object parameter.
14518   ExprResult ObjRes =
14519     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14520                                         Best->FoundDecl, Method);
14521   if (ObjRes.isInvalid())
14522     IsError = true;
14523   else
14524     Object = ObjRes;
14525   MethodArgs[0] = Object.get();
14526 
14527   // Check the argument types.
14528   for (unsigned i = 0; i != NumParams; i++) {
14529     Expr *Arg;
14530     if (i < Args.size()) {
14531       Arg = Args[i];
14532 
14533       // Pass the argument.
14534 
14535       ExprResult InputInit
14536         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14537                                                     Context,
14538                                                     Method->getParamDecl(i)),
14539                                     SourceLocation(), Arg);
14540 
14541       IsError |= InputInit.isInvalid();
14542       Arg = InputInit.getAs<Expr>();
14543     } else {
14544       ExprResult DefArg
14545         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14546       if (DefArg.isInvalid()) {
14547         IsError = true;
14548         break;
14549       }
14550 
14551       Arg = DefArg.getAs<Expr>();
14552     }
14553 
14554     MethodArgs[i + 1] = Arg;
14555   }
14556 
14557   // If this is a variadic call, handle args passed through "...".
14558   if (Proto->isVariadic()) {
14559     // Promote the arguments (C99 6.5.2.2p7).
14560     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14561       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14562                                                         nullptr);
14563       IsError |= Arg.isInvalid();
14564       MethodArgs[i + 1] = Arg.get();
14565     }
14566   }
14567 
14568   if (IsError)
14569     return true;
14570 
14571   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14572 
14573   // Once we've built TheCall, all of the expressions are properly owned.
14574   QualType ResultTy = Method->getReturnType();
14575   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14576   ResultTy = ResultTy.getNonLValueExprType(Context);
14577 
14578   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14579       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14580       CurFPFeatureOverrides());
14581 
14582   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14583     return true;
14584 
14585   if (CheckFunctionCall(Method, TheCall, Proto))
14586     return true;
14587 
14588   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14589 }
14590 
14591 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14592 ///  (if one exists), where @c Base is an expression of class type and
14593 /// @c Member is the name of the member we're trying to find.
14594 ExprResult
14595 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14596                                bool *NoArrowOperatorFound) {
14597   assert(Base->getType()->isRecordType() &&
14598          "left-hand side must have class type");
14599 
14600   if (checkPlaceholderForOverload(*this, Base))
14601     return ExprError();
14602 
14603   SourceLocation Loc = Base->getExprLoc();
14604 
14605   // C++ [over.ref]p1:
14606   //
14607   //   [...] An expression x->m is interpreted as (x.operator->())->m
14608   //   for a class object x of type T if T::operator->() exists and if
14609   //   the operator is selected as the best match function by the
14610   //   overload resolution mechanism (13.3).
14611   DeclarationName OpName =
14612     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14613   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14614 
14615   if (RequireCompleteType(Loc, Base->getType(),
14616                           diag::err_typecheck_incomplete_tag, Base))
14617     return ExprError();
14618 
14619   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14620   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14621   R.suppressDiagnostics();
14622 
14623   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14624        Oper != OperEnd; ++Oper) {
14625     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14626                        None, CandidateSet, /*SuppressUserConversion=*/false);
14627   }
14628 
14629   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14630 
14631   // Perform overload resolution.
14632   OverloadCandidateSet::iterator Best;
14633   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14634   case OR_Success:
14635     // Overload resolution succeeded; we'll build the call below.
14636     break;
14637 
14638   case OR_No_Viable_Function: {
14639     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14640     if (CandidateSet.empty()) {
14641       QualType BaseType = Base->getType();
14642       if (NoArrowOperatorFound) {
14643         // Report this specific error to the caller instead of emitting a
14644         // diagnostic, as requested.
14645         *NoArrowOperatorFound = true;
14646         return ExprError();
14647       }
14648       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14649         << BaseType << Base->getSourceRange();
14650       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14651         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14652           << FixItHint::CreateReplacement(OpLoc, ".");
14653       }
14654     } else
14655       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14656         << "operator->" << Base->getSourceRange();
14657     CandidateSet.NoteCandidates(*this, Base, Cands);
14658     return ExprError();
14659   }
14660   case OR_Ambiguous:
14661     CandidateSet.NoteCandidates(
14662         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14663                                        << "->" << Base->getType()
14664                                        << Base->getSourceRange()),
14665         *this, OCD_AmbiguousCandidates, Base);
14666     return ExprError();
14667 
14668   case OR_Deleted:
14669     CandidateSet.NoteCandidates(
14670         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14671                                        << "->" << Base->getSourceRange()),
14672         *this, OCD_AllCandidates, Base);
14673     return ExprError();
14674   }
14675 
14676   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14677 
14678   // Convert the object parameter.
14679   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14680   ExprResult BaseResult =
14681     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14682                                         Best->FoundDecl, Method);
14683   if (BaseResult.isInvalid())
14684     return ExprError();
14685   Base = BaseResult.get();
14686 
14687   // Build the operator call.
14688   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14689                                             Base, HadMultipleCandidates, OpLoc);
14690   if (FnExpr.isInvalid())
14691     return ExprError();
14692 
14693   QualType ResultTy = Method->getReturnType();
14694   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14695   ResultTy = ResultTy.getNonLValueExprType(Context);
14696   CXXOperatorCallExpr *TheCall =
14697       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14698                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14699 
14700   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14701     return ExprError();
14702 
14703   if (CheckFunctionCall(Method, TheCall,
14704                         Method->getType()->castAs<FunctionProtoType>()))
14705     return ExprError();
14706 
14707   return MaybeBindToTemporary(TheCall);
14708 }
14709 
14710 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14711 /// a literal operator described by the provided lookup results.
14712 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14713                                           DeclarationNameInfo &SuffixInfo,
14714                                           ArrayRef<Expr*> Args,
14715                                           SourceLocation LitEndLoc,
14716                                        TemplateArgumentListInfo *TemplateArgs) {
14717   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14718 
14719   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14720                                     OverloadCandidateSet::CSK_Normal);
14721   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14722                                  TemplateArgs);
14723 
14724   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14725 
14726   // Perform overload resolution. This will usually be trivial, but might need
14727   // to perform substitutions for a literal operator template.
14728   OverloadCandidateSet::iterator Best;
14729   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14730   case OR_Success:
14731   case OR_Deleted:
14732     break;
14733 
14734   case OR_No_Viable_Function:
14735     CandidateSet.NoteCandidates(
14736         PartialDiagnosticAt(UDSuffixLoc,
14737                             PDiag(diag::err_ovl_no_viable_function_in_call)
14738                                 << R.getLookupName()),
14739         *this, OCD_AllCandidates, Args);
14740     return ExprError();
14741 
14742   case OR_Ambiguous:
14743     CandidateSet.NoteCandidates(
14744         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14745                                                 << R.getLookupName()),
14746         *this, OCD_AmbiguousCandidates, Args);
14747     return ExprError();
14748   }
14749 
14750   FunctionDecl *FD = Best->Function;
14751   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14752                                         nullptr, HadMultipleCandidates,
14753                                         SuffixInfo.getLoc(),
14754                                         SuffixInfo.getInfo());
14755   if (Fn.isInvalid())
14756     return true;
14757 
14758   // Check the argument types. This should almost always be a no-op, except
14759   // that array-to-pointer decay is applied to string literals.
14760   Expr *ConvArgs[2];
14761   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14762     ExprResult InputInit = PerformCopyInitialization(
14763       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14764       SourceLocation(), Args[ArgIdx]);
14765     if (InputInit.isInvalid())
14766       return true;
14767     ConvArgs[ArgIdx] = InputInit.get();
14768   }
14769 
14770   QualType ResultTy = FD->getReturnType();
14771   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14772   ResultTy = ResultTy.getNonLValueExprType(Context);
14773 
14774   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14775       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14776       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14777 
14778   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14779     return ExprError();
14780 
14781   if (CheckFunctionCall(FD, UDL, nullptr))
14782     return ExprError();
14783 
14784   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14785 }
14786 
14787 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14788 /// given LookupResult is non-empty, it is assumed to describe a member which
14789 /// will be invoked. Otherwise, the function will be found via argument
14790 /// dependent lookup.
14791 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14792 /// otherwise CallExpr is set to ExprError() and some non-success value
14793 /// is returned.
14794 Sema::ForRangeStatus
14795 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14796                                 SourceLocation RangeLoc,
14797                                 const DeclarationNameInfo &NameInfo,
14798                                 LookupResult &MemberLookup,
14799                                 OverloadCandidateSet *CandidateSet,
14800                                 Expr *Range, ExprResult *CallExpr) {
14801   Scope *S = nullptr;
14802 
14803   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14804   if (!MemberLookup.empty()) {
14805     ExprResult MemberRef =
14806         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14807                                  /*IsPtr=*/false, CXXScopeSpec(),
14808                                  /*TemplateKWLoc=*/SourceLocation(),
14809                                  /*FirstQualifierInScope=*/nullptr,
14810                                  MemberLookup,
14811                                  /*TemplateArgs=*/nullptr, S);
14812     if (MemberRef.isInvalid()) {
14813       *CallExpr = ExprError();
14814       return FRS_DiagnosticIssued;
14815     }
14816     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14817     if (CallExpr->isInvalid()) {
14818       *CallExpr = ExprError();
14819       return FRS_DiagnosticIssued;
14820     }
14821   } else {
14822     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14823                                                 NestedNameSpecifierLoc(),
14824                                                 NameInfo, UnresolvedSet<0>());
14825     if (FnR.isInvalid())
14826       return FRS_DiagnosticIssued;
14827     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14828 
14829     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14830                                                     CandidateSet, CallExpr);
14831     if (CandidateSet->empty() || CandidateSetError) {
14832       *CallExpr = ExprError();
14833       return FRS_NoViableFunction;
14834     }
14835     OverloadCandidateSet::iterator Best;
14836     OverloadingResult OverloadResult =
14837         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14838 
14839     if (OverloadResult == OR_No_Viable_Function) {
14840       *CallExpr = ExprError();
14841       return FRS_NoViableFunction;
14842     }
14843     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14844                                          Loc, nullptr, CandidateSet, &Best,
14845                                          OverloadResult,
14846                                          /*AllowTypoCorrection=*/false);
14847     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14848       *CallExpr = ExprError();
14849       return FRS_DiagnosticIssued;
14850     }
14851   }
14852   return FRS_Success;
14853 }
14854 
14855 
14856 /// FixOverloadedFunctionReference - E is an expression that refers to
14857 /// a C++ overloaded function (possibly with some parentheses and
14858 /// perhaps a '&' around it). We have resolved the overloaded function
14859 /// to the function declaration Fn, so patch up the expression E to
14860 /// refer (possibly indirectly) to Fn. Returns the new expr.
14861 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14862                                            FunctionDecl *Fn) {
14863   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14864     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14865                                                    Found, Fn);
14866     if (SubExpr == PE->getSubExpr())
14867       return PE;
14868 
14869     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14870   }
14871 
14872   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14873     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14874                                                    Found, Fn);
14875     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14876                                SubExpr->getType()) &&
14877            "Implicit cast type cannot be determined from overload");
14878     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14879     if (SubExpr == ICE->getSubExpr())
14880       return ICE;
14881 
14882     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
14883                                     SubExpr, nullptr, ICE->getValueKind(),
14884                                     CurFPFeatureOverrides());
14885   }
14886 
14887   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14888     if (!GSE->isResultDependent()) {
14889       Expr *SubExpr =
14890           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14891       if (SubExpr == GSE->getResultExpr())
14892         return GSE;
14893 
14894       // Replace the resulting type information before rebuilding the generic
14895       // selection expression.
14896       ArrayRef<Expr *> A = GSE->getAssocExprs();
14897       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14898       unsigned ResultIdx = GSE->getResultIndex();
14899       AssocExprs[ResultIdx] = SubExpr;
14900 
14901       return GenericSelectionExpr::Create(
14902           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14903           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14904           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14905           ResultIdx);
14906     }
14907     // Rather than fall through to the unreachable, return the original generic
14908     // selection expression.
14909     return GSE;
14910   }
14911 
14912   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14913     assert(UnOp->getOpcode() == UO_AddrOf &&
14914            "Can only take the address of an overloaded function");
14915     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14916       if (Method->isStatic()) {
14917         // Do nothing: static member functions aren't any different
14918         // from non-member functions.
14919       } else {
14920         // Fix the subexpression, which really has to be an
14921         // UnresolvedLookupExpr holding an overloaded member function
14922         // or template.
14923         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14924                                                        Found, Fn);
14925         if (SubExpr == UnOp->getSubExpr())
14926           return UnOp;
14927 
14928         assert(isa<DeclRefExpr>(SubExpr)
14929                && "fixed to something other than a decl ref");
14930         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14931                && "fixed to a member ref with no nested name qualifier");
14932 
14933         // We have taken the address of a pointer to member
14934         // function. Perform the computation here so that we get the
14935         // appropriate pointer to member type.
14936         QualType ClassType
14937           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14938         QualType MemPtrType
14939           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14940         // Under the MS ABI, lock down the inheritance model now.
14941         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14942           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14943 
14944         return UnaryOperator::Create(
14945             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14946             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14947       }
14948     }
14949     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14950                                                    Found, Fn);
14951     if (SubExpr == UnOp->getSubExpr())
14952       return UnOp;
14953 
14954     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14955                                  Context.getPointerType(SubExpr->getType()),
14956                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14957                                  false, CurFPFeatureOverrides());
14958   }
14959 
14960   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14961     // FIXME: avoid copy.
14962     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14963     if (ULE->hasExplicitTemplateArgs()) {
14964       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14965       TemplateArgs = &TemplateArgsBuffer;
14966     }
14967 
14968     DeclRefExpr *DRE =
14969         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14970                          ULE->getQualifierLoc(), Found.getDecl(),
14971                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14972     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14973     return DRE;
14974   }
14975 
14976   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14977     // FIXME: avoid copy.
14978     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14979     if (MemExpr->hasExplicitTemplateArgs()) {
14980       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14981       TemplateArgs = &TemplateArgsBuffer;
14982     }
14983 
14984     Expr *Base;
14985 
14986     // If we're filling in a static method where we used to have an
14987     // implicit member access, rewrite to a simple decl ref.
14988     if (MemExpr->isImplicitAccess()) {
14989       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14990         DeclRefExpr *DRE = BuildDeclRefExpr(
14991             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14992             MemExpr->getQualifierLoc(), Found.getDecl(),
14993             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14994         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14995         return DRE;
14996       } else {
14997         SourceLocation Loc = MemExpr->getMemberLoc();
14998         if (MemExpr->getQualifier())
14999           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15000         Base =
15001             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15002       }
15003     } else
15004       Base = MemExpr->getBase();
15005 
15006     ExprValueKind valueKind;
15007     QualType type;
15008     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15009       valueKind = VK_LValue;
15010       type = Fn->getType();
15011     } else {
15012       valueKind = VK_RValue;
15013       type = Context.BoundMemberTy;
15014     }
15015 
15016     return BuildMemberExpr(
15017         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15018         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15019         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15020         type, valueKind, OK_Ordinary, TemplateArgs);
15021   }
15022 
15023   llvm_unreachable("Invalid reference to overloaded function");
15024 }
15025 
15026 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15027                                                 DeclAccessPair Found,
15028                                                 FunctionDecl *Fn) {
15029   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15030 }
15031