1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 using AllowedExplicit = Sema::AllowedExplicit;
42 
43 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
44   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
45     return P->hasAttr<PassObjectSizeAttr>();
46   });
47 }
48 
49 /// A convenience routine for creating a decayed reference to a function.
50 static ExprResult
51 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
52                       const Expr *Base, bool HadMultipleCandidates,
53                       SourceLocation Loc = SourceLocation(),
54                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
55   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
56     return ExprError();
57   // If FoundDecl is different from Fn (such as if one is a template
58   // and the other a specialization), make sure DiagnoseUseOfDecl is
59   // called on both.
60   // FIXME: This would be more comprehensively addressed by modifying
61   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
62   // being used.
63   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
64     return ExprError();
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
72     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
73       S.ResolveExceptionSpec(Loc, FPT);
74       DRE->setType(Fn->getType());
75     }
76   }
77   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
78                              CK_FunctionToPointerDecay);
79 }
80 
81 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
82                                  bool InOverloadResolution,
83                                  StandardConversionSequence &SCS,
84                                  bool CStyle,
85                                  bool AllowObjCWritebackConversion);
86 
87 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
88                                                  QualType &ToType,
89                                                  bool InOverloadResolution,
90                                                  StandardConversionSequence &SCS,
91                                                  bool CStyle);
92 static OverloadingResult
93 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
94                         UserDefinedConversionSequence& User,
95                         OverloadCandidateSet& Conversions,
96                         AllowedExplicit AllowExplicit,
97                         bool AllowObjCConversionOnExplicit);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
101                                    const StandardConversionSequence& SCS1,
102                                    const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareQualificationConversions(Sema &S,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 static ImplicitConversionSequence::CompareKind
110 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
111                                 const StandardConversionSequence& SCS1,
112                                 const StandardConversionSequence& SCS2);
113 
114 /// GetConversionRank - Retrieve the implicit conversion rank
115 /// corresponding to the given implicit conversion kind.
116 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
117   static const ImplicitConversionRank
118     Rank[(int)ICK_Num_Conversion_Kinds] = {
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Promotion,
126     ICR_Promotion,
127     ICR_Promotion,
128     ICR_Conversion,
129     ICR_Conversion,
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_OCL_Scalar_Widening,
139     ICR_Complex_Real_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Writeback_Conversion,
143     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
144                      // it was omitted by the patch that added
145                      // ICK_Zero_Event_Conversion
146     ICR_C_Conversion,
147     ICR_C_Conversion_Extension
148   };
149   return Rank[(int)Kind];
150 }
151 
152 /// GetImplicitConversionName - Return the name of this kind of
153 /// implicit conversion.
154 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
155   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
156     "No conversion",
157     "Lvalue-to-rvalue",
158     "Array-to-pointer",
159     "Function-to-pointer",
160     "Function pointer conversion",
161     "Qualification",
162     "Integral promotion",
163     "Floating point promotion",
164     "Complex promotion",
165     "Integral conversion",
166     "Floating conversion",
167     "Complex conversion",
168     "Floating-integral conversion",
169     "Pointer conversion",
170     "Pointer-to-member conversion",
171     "Boolean conversion",
172     "Compatible-types conversion",
173     "Derived-to-base conversion",
174     "Vector conversion",
175     "Vector splat",
176     "Complex-real conversion",
177     "Block Pointer conversion",
178     "Transparent Union Conversion",
179     "Writeback conversion",
180     "OpenCL Zero Event Conversion",
181     "C specific type conversion",
182     "Incompatible pointer conversion"
183   };
184   return Name[Kind];
185 }
186 
187 /// StandardConversionSequence - Set the standard conversion
188 /// sequence to the identity conversion.
189 void StandardConversionSequence::setAsIdentityConversion() {
190   First = ICK_Identity;
191   Second = ICK_Identity;
192   Third = ICK_Identity;
193   DeprecatedStringLiteralToCharPtr = false;
194   QualificationIncludesObjCLifetime = false;
195   ReferenceBinding = false;
196   DirectBinding = false;
197   IsLvalueReference = true;
198   BindsToFunctionLvalue = false;
199   BindsToRvalue = false;
200   BindsImplicitObjectArgumentWithoutRefQualifier = false;
201   ObjCLifetimeConversionBinding = false;
202   CopyConstructor = nullptr;
203 }
204 
205 /// getRank - Retrieve the rank of this standard conversion sequence
206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207 /// implicit conversions.
208 ImplicitConversionRank StandardConversionSequence::getRank() const {
209   ImplicitConversionRank Rank = ICR_Exact_Match;
210   if  (GetConversionRank(First) > Rank)
211     Rank = GetConversionRank(First);
212   if  (GetConversionRank(Second) > Rank)
213     Rank = GetConversionRank(Second);
214   if  (GetConversionRank(Third) > Rank)
215     Rank = GetConversionRank(Third);
216   return Rank;
217 }
218 
219 /// isPointerConversionToBool - Determines whether this conversion is
220 /// a conversion of a pointer or pointer-to-member to bool. This is
221 /// used as part of the ranking of standard conversion sequences
222 /// (C++ 13.3.3.2p4).
223 bool StandardConversionSequence::isPointerConversionToBool() const {
224   // Note that FromType has not necessarily been transformed by the
225   // array-to-pointer or function-to-pointer implicit conversions, so
226   // check for their presence as well as checking whether FromType is
227   // a pointer.
228   if (getToType(1)->isBooleanType() &&
229       (getFromType()->isPointerType() ||
230        getFromType()->isMemberPointerType() ||
231        getFromType()->isObjCObjectPointerType() ||
232        getFromType()->isBlockPointerType() ||
233        getFromType()->isNullPtrType() ||
234        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235     return true;
236 
237   return false;
238 }
239 
240 /// isPointerConversionToVoidPointer - Determines whether this
241 /// conversion is a conversion of a pointer to a void pointer. This is
242 /// used as part of the ranking of standard conversion sequences (C++
243 /// 13.3.3.2p4).
244 bool
245 StandardConversionSequence::
246 isPointerConversionToVoidPointer(ASTContext& Context) const {
247   QualType FromType = getFromType();
248   QualType ToType = getToType(1);
249 
250   // Note that FromType has not necessarily been transformed by the
251   // array-to-pointer implicit conversion, so check for its presence
252   // and redo the conversion to get a pointer.
253   if (First == ICK_Array_To_Pointer)
254     FromType = Context.getArrayDecayedType(FromType);
255 
256   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
257     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
258       return ToPtrType->getPointeeType()->isVoidType();
259 
260   return false;
261 }
262 
263 /// Skip any implicit casts which could be either part of a narrowing conversion
264 /// or after one in an implicit conversion.
265 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
266                                              const Expr *Converted) {
267   // We can have cleanups wrapping the converted expression; these need to be
268   // preserved so that destructors run if necessary.
269   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
270     Expr *Inner =
271         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
272     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
273                                     EWC->getObjects());
274   }
275 
276   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
277     switch (ICE->getCastKind()) {
278     case CK_NoOp:
279     case CK_IntegralCast:
280     case CK_IntegralToBoolean:
281     case CK_IntegralToFloating:
282     case CK_BooleanToSignedIntegral:
283     case CK_FloatingToIntegral:
284     case CK_FloatingToBoolean:
285     case CK_FloatingCast:
286       Converted = ICE->getSubExpr();
287       continue;
288 
289     default:
290       return Converted;
291     }
292   }
293 
294   return Converted;
295 }
296 
297 /// Check if this standard conversion sequence represents a narrowing
298 /// conversion, according to C++11 [dcl.init.list]p7.
299 ///
300 /// \param Ctx  The AST context.
301 /// \param Converted  The result of applying this standard conversion sequence.
302 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
303 ///        value of the expression prior to the narrowing conversion.
304 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
305 ///        type of the expression prior to the narrowing conversion.
306 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
307 ///        from floating point types to integral types should be ignored.
308 NarrowingKind StandardConversionSequence::getNarrowingKind(
309     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
310     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
311   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
312 
313   // C++11 [dcl.init.list]p7:
314   //   A narrowing conversion is an implicit conversion ...
315   QualType FromType = getToType(0);
316   QualType ToType = getToType(1);
317 
318   // A conversion to an enumeration type is narrowing if the conversion to
319   // the underlying type is narrowing. This only arises for expressions of
320   // the form 'Enum{init}'.
321   if (auto *ET = ToType->getAs<EnumType>())
322     ToType = ET->getDecl()->getIntegerType();
323 
324   switch (Second) {
325   // 'bool' is an integral type; dispatch to the right place to handle it.
326   case ICK_Boolean_Conversion:
327     if (FromType->isRealFloatingType())
328       goto FloatingIntegralConversion;
329     if (FromType->isIntegralOrUnscopedEnumerationType())
330       goto IntegralConversion;
331     // Boolean conversions can be from pointers and pointers to members
332     // [conv.bool], and those aren't considered narrowing conversions.
333     return NK_Not_Narrowing;
334 
335   // -- from a floating-point type to an integer type, or
336   //
337   // -- from an integer type or unscoped enumeration type to a floating-point
338   //    type, except where the source is a constant expression and the actual
339   //    value after conversion will fit into the target type and will produce
340   //    the original value when converted back to the original type, or
341   case ICK_Floating_Integral:
342   FloatingIntegralConversion:
343     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
344       return NK_Type_Narrowing;
345     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
346                ToType->isRealFloatingType()) {
347       if (IgnoreFloatToIntegralConversion)
348         return NK_Not_Narrowing;
349       llvm::APSInt IntConstantValue;
350       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351       assert(Initializer && "Unknown conversion expression");
352 
353       // If it's value-dependent, we can't tell whether it's narrowing.
354       if (Initializer->isValueDependent())
355         return NK_Dependent_Narrowing;
356 
357       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
358         // Convert the integer to the floating type.
359         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
360         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
361                                 llvm::APFloat::rmNearestTiesToEven);
362         // And back.
363         llvm::APSInt ConvertedValue = IntConstantValue;
364         bool ignored;
365         Result.convertToInteger(ConvertedValue,
366                                 llvm::APFloat::rmTowardZero, &ignored);
367         // If the resulting value is different, this was a narrowing conversion.
368         if (IntConstantValue != ConvertedValue) {
369           ConstantValue = APValue(IntConstantValue);
370           ConstantType = Initializer->getType();
371           return NK_Constant_Narrowing;
372         }
373       } else {
374         // Variables are always narrowings.
375         return NK_Variable_Narrowing;
376       }
377     }
378     return NK_Not_Narrowing;
379 
380   // -- from long double to double or float, or from double to float, except
381   //    where the source is a constant expression and the actual value after
382   //    conversion is within the range of values that can be represented (even
383   //    if it cannot be represented exactly), or
384   case ICK_Floating_Conversion:
385     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
386         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
387       // FromType is larger than ToType.
388       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
389 
390       // If it's value-dependent, we can't tell whether it's narrowing.
391       if (Initializer->isValueDependent())
392         return NK_Dependent_Narrowing;
393 
394       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
395         // Constant!
396         assert(ConstantValue.isFloat());
397         llvm::APFloat FloatVal = ConstantValue.getFloat();
398         // Convert the source value into the target type.
399         bool ignored;
400         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
401           Ctx.getFloatTypeSemantics(ToType),
402           llvm::APFloat::rmNearestTiesToEven, &ignored);
403         // If there was no overflow, the source value is within the range of
404         // values that can be represented.
405         if (ConvertStatus & llvm::APFloat::opOverflow) {
406           ConstantType = Initializer->getType();
407           return NK_Constant_Narrowing;
408         }
409       } else {
410         return NK_Variable_Narrowing;
411       }
412     }
413     return NK_Not_Narrowing;
414 
415   // -- from an integer type or unscoped enumeration type to an integer type
416   //    that cannot represent all the values of the original type, except where
417   //    the source is a constant expression and the actual value after
418   //    conversion will fit into the target type and will produce the original
419   //    value when converted back to the original type.
420   case ICK_Integral_Conversion:
421   IntegralConversion: {
422     assert(FromType->isIntegralOrUnscopedEnumerationType());
423     assert(ToType->isIntegralOrUnscopedEnumerationType());
424     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
425     const unsigned FromWidth = Ctx.getIntWidth(FromType);
426     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
427     const unsigned ToWidth = Ctx.getIntWidth(ToType);
428 
429     if (FromWidth > ToWidth ||
430         (FromWidth == ToWidth && FromSigned != ToSigned) ||
431         (FromSigned && !ToSigned)) {
432       // Not all values of FromType can be represented in ToType.
433       llvm::APSInt InitializerValue;
434       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436       // If it's value-dependent, we can't tell whether it's narrowing.
437       if (Initializer->isValueDependent())
438         return NK_Dependent_Narrowing;
439 
440       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
441         // Such conversions on variables are always narrowing.
442         return NK_Variable_Narrowing;
443       }
444       bool Narrowing = false;
445       if (FromWidth < ToWidth) {
446         // Negative -> unsigned is narrowing. Otherwise, more bits is never
447         // narrowing.
448         if (InitializerValue.isSigned() && InitializerValue.isNegative())
449           Narrowing = true;
450       } else {
451         // Add a bit to the InitializerValue so we don't have to worry about
452         // signed vs. unsigned comparisons.
453         InitializerValue = InitializerValue.extend(
454           InitializerValue.getBitWidth() + 1);
455         // Convert the initializer to and from the target width and signed-ness.
456         llvm::APSInt ConvertedValue = InitializerValue;
457         ConvertedValue = ConvertedValue.trunc(ToWidth);
458         ConvertedValue.setIsSigned(ToSigned);
459         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
460         ConvertedValue.setIsSigned(InitializerValue.isSigned());
461         // If the result is different, this was a narrowing conversion.
462         if (ConvertedValue != InitializerValue)
463           Narrowing = true;
464       }
465       if (Narrowing) {
466         ConstantType = Initializer->getType();
467         ConstantValue = APValue(InitializerValue);
468         return NK_Constant_Narrowing;
469       }
470     }
471     return NK_Not_Narrowing;
472   }
473 
474   default:
475     // Other kinds of conversions are not narrowings.
476     return NK_Not_Narrowing;
477   }
478 }
479 
480 /// dump - Print this standard conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
483   raw_ostream &OS = llvm::errs();
484   bool PrintedSomething = false;
485   if (First != ICK_Identity) {
486     OS << GetImplicitConversionName(First);
487     PrintedSomething = true;
488   }
489 
490   if (Second != ICK_Identity) {
491     if (PrintedSomething) {
492       OS << " -> ";
493     }
494     OS << GetImplicitConversionName(Second);
495 
496     if (CopyConstructor) {
497       OS << " (by copy constructor)";
498     } else if (DirectBinding) {
499       OS << " (direct reference binding)";
500     } else if (ReferenceBinding) {
501       OS << " (reference binding)";
502     }
503     PrintedSomething = true;
504   }
505 
506   if (Third != ICK_Identity) {
507     if (PrintedSomething) {
508       OS << " -> ";
509     }
510     OS << GetImplicitConversionName(Third);
511     PrintedSomething = true;
512   }
513 
514   if (!PrintedSomething) {
515     OS << "No conversions required";
516   }
517 }
518 
519 /// dump - Print this user-defined conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void UserDefinedConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (Before.First || Before.Second || Before.Third) {
524     Before.dump();
525     OS << " -> ";
526   }
527   if (ConversionFunction)
528     OS << '\'' << *ConversionFunction << '\'';
529   else
530     OS << "aggregate initialization";
531   if (After.First || After.Second || After.Third) {
532     OS << " -> ";
533     After.dump();
534   }
535 }
536 
537 /// dump - Print this implicit conversion sequence to standard
538 /// error. Useful for debugging overloading issues.
539 void ImplicitConversionSequence::dump() const {
540   raw_ostream &OS = llvm::errs();
541   if (isStdInitializerListElement())
542     OS << "Worst std::initializer_list element conversion: ";
543   switch (ConversionKind) {
544   case StandardConversion:
545     OS << "Standard conversion: ";
546     Standard.dump();
547     break;
548   case UserDefinedConversion:
549     OS << "User-defined conversion: ";
550     UserDefined.dump();
551     break;
552   case EllipsisConversion:
553     OS << "Ellipsis conversion";
554     break;
555   case AmbiguousConversion:
556     OS << "Ambiguous conversion";
557     break;
558   case BadConversion:
559     OS << "Bad conversion";
560     break;
561   }
562 
563   OS << "\n";
564 }
565 
566 void AmbiguousConversionSequence::construct() {
567   new (&conversions()) ConversionSet();
568 }
569 
570 void AmbiguousConversionSequence::destruct() {
571   conversions().~ConversionSet();
572 }
573 
574 void
575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
576   FromTypePtr = O.FromTypePtr;
577   ToTypePtr = O.ToTypePtr;
578   new (&conversions()) ConversionSet(O.conversions());
579 }
580 
581 namespace {
582   // Structure used by DeductionFailureInfo to store
583   // template argument information.
584   struct DFIArguments {
585     TemplateArgument FirstArg;
586     TemplateArgument SecondArg;
587   };
588   // Structure used by DeductionFailureInfo to store
589   // template parameter and template argument information.
590   struct DFIParamWithArguments : DFIArguments {
591     TemplateParameter Param;
592   };
593   // Structure used by DeductionFailureInfo to store template argument
594   // information and the index of the problematic call argument.
595   struct DFIDeducedMismatchArgs : DFIArguments {
596     TemplateArgumentList *TemplateArgs;
597     unsigned CallArgIndex;
598   };
599   // Structure used by DeductionFailureInfo to store information about
600   // unsatisfied constraints.
601   struct CNSInfo {
602     TemplateArgumentList *TemplateArgs;
603     ConstraintSatisfaction Satisfaction;
604   };
605 }
606 
607 /// Convert from Sema's representation of template deduction information
608 /// to the form used in overload-candidate information.
609 DeductionFailureInfo
610 clang::MakeDeductionFailureInfo(ASTContext &Context,
611                                 Sema::TemplateDeductionResult TDK,
612                                 TemplateDeductionInfo &Info) {
613   DeductionFailureInfo Result;
614   Result.Result = static_cast<unsigned>(TDK);
615   Result.HasDiagnostic = false;
616   switch (TDK) {
617   case Sema::TDK_Invalid:
618   case Sema::TDK_InstantiationDepth:
619   case Sema::TDK_TooManyArguments:
620   case Sema::TDK_TooFewArguments:
621   case Sema::TDK_MiscellaneousDeductionFailure:
622   case Sema::TDK_CUDATargetMismatch:
623     Result.Data = nullptr;
624     break;
625 
626   case Sema::TDK_Incomplete:
627   case Sema::TDK_InvalidExplicitArguments:
628     Result.Data = Info.Param.getOpaqueValue();
629     break;
630 
631   case Sema::TDK_DeducedMismatch:
632   case Sema::TDK_DeducedMismatchNested: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     auto *Saved = new (Context) DFIDeducedMismatchArgs;
635     Saved->FirstArg = Info.FirstArg;
636     Saved->SecondArg = Info.SecondArg;
637     Saved->TemplateArgs = Info.take();
638     Saved->CallArgIndex = Info.CallArgIndex;
639     Result.Data = Saved;
640     break;
641   }
642 
643   case Sema::TDK_NonDeducedMismatch: {
644     // FIXME: Should allocate from normal heap so that we can free this later.
645     DFIArguments *Saved = new (Context) DFIArguments;
646     Saved->FirstArg = Info.FirstArg;
647     Saved->SecondArg = Info.SecondArg;
648     Result.Data = Saved;
649     break;
650   }
651 
652   case Sema::TDK_IncompletePack:
653     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
654   case Sema::TDK_Inconsistent:
655   case Sema::TDK_Underqualified: {
656     // FIXME: Should allocate from normal heap so that we can free this later.
657     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
658     Saved->Param = Info.Param;
659     Saved->FirstArg = Info.FirstArg;
660     Saved->SecondArg = Info.SecondArg;
661     Result.Data = Saved;
662     break;
663   }
664 
665   case Sema::TDK_SubstitutionFailure:
666     Result.Data = Info.take();
667     if (Info.hasSFINAEDiagnostic()) {
668       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
669           SourceLocation(), PartialDiagnostic::NullDiagnostic());
670       Info.takeSFINAEDiagnostic(*Diag);
671       Result.HasDiagnostic = true;
672     }
673     break;
674 
675   case Sema::TDK_ConstraintsNotSatisfied: {
676     CNSInfo *Saved = new (Context) CNSInfo;
677     Saved->TemplateArgs = Info.take();
678     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
679     Result.Data = Saved;
680     break;
681   }
682 
683   case Sema::TDK_Success:
684   case Sema::TDK_NonDependentConversionFailure:
685     llvm_unreachable("not a deduction failure");
686   }
687 
688   return Result;
689 }
690 
691 void DeductionFailureInfo::Destroy() {
692   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
693   case Sema::TDK_Success:
694   case Sema::TDK_Invalid:
695   case Sema::TDK_InstantiationDepth:
696   case Sema::TDK_Incomplete:
697   case Sema::TDK_TooManyArguments:
698   case Sema::TDK_TooFewArguments:
699   case Sema::TDK_InvalidExplicitArguments:
700   case Sema::TDK_CUDATargetMismatch:
701   case Sema::TDK_NonDependentConversionFailure:
702     break;
703 
704   case Sema::TDK_IncompletePack:
705   case Sema::TDK_Inconsistent:
706   case Sema::TDK_Underqualified:
707   case Sema::TDK_DeducedMismatch:
708   case Sema::TDK_DeducedMismatchNested:
709   case Sema::TDK_NonDeducedMismatch:
710     // FIXME: Destroy the data?
711     Data = nullptr;
712     break;
713 
714   case Sema::TDK_SubstitutionFailure:
715     // FIXME: Destroy the template argument list?
716     Data = nullptr;
717     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
718       Diag->~PartialDiagnosticAt();
719       HasDiagnostic = false;
720     }
721     break;
722 
723   case Sema::TDK_ConstraintsNotSatisfied:
724     // FIXME: Destroy the template argument list?
725     Data = nullptr;
726     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
727       Diag->~PartialDiagnosticAt();
728       HasDiagnostic = false;
729     }
730     break;
731 
732   // Unhandled
733   case Sema::TDK_MiscellaneousDeductionFailure:
734     break;
735   }
736 }
737 
738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
739   if (HasDiagnostic)
740     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
741   return nullptr;
742 }
743 
744 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
745   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
746   case Sema::TDK_Success:
747   case Sema::TDK_Invalid:
748   case Sema::TDK_InstantiationDepth:
749   case Sema::TDK_TooManyArguments:
750   case Sema::TDK_TooFewArguments:
751   case Sema::TDK_SubstitutionFailure:
752   case Sema::TDK_DeducedMismatch:
753   case Sema::TDK_DeducedMismatchNested:
754   case Sema::TDK_NonDeducedMismatch:
755   case Sema::TDK_CUDATargetMismatch:
756   case Sema::TDK_NonDependentConversionFailure:
757   case Sema::TDK_ConstraintsNotSatisfied:
758     return TemplateParameter();
759 
760   case Sema::TDK_Incomplete:
761   case Sema::TDK_InvalidExplicitArguments:
762     return TemplateParameter::getFromOpaqueValue(Data);
763 
764   case Sema::TDK_IncompletePack:
765   case Sema::TDK_Inconsistent:
766   case Sema::TDK_Underqualified:
767     return static_cast<DFIParamWithArguments*>(Data)->Param;
768 
769   // Unhandled
770   case Sema::TDK_MiscellaneousDeductionFailure:
771     break;
772   }
773 
774   return TemplateParameter();
775 }
776 
777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
778   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
779   case Sema::TDK_Success:
780   case Sema::TDK_Invalid:
781   case Sema::TDK_InstantiationDepth:
782   case Sema::TDK_TooManyArguments:
783   case Sema::TDK_TooFewArguments:
784   case Sema::TDK_Incomplete:
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_InvalidExplicitArguments:
787   case Sema::TDK_Inconsistent:
788   case Sema::TDK_Underqualified:
789   case Sema::TDK_NonDeducedMismatch:
790   case Sema::TDK_CUDATargetMismatch:
791   case Sema::TDK_NonDependentConversionFailure:
792     return nullptr;
793 
794   case Sema::TDK_DeducedMismatch:
795   case Sema::TDK_DeducedMismatchNested:
796     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
797 
798   case Sema::TDK_SubstitutionFailure:
799     return static_cast<TemplateArgumentList*>(Data);
800 
801   case Sema::TDK_ConstraintsNotSatisfied:
802     return static_cast<CNSInfo*>(Data)->TemplateArgs;
803 
804   // Unhandled
805   case Sema::TDK_MiscellaneousDeductionFailure:
806     break;
807   }
808 
809   return nullptr;
810 }
811 
812 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
813   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
814   case Sema::TDK_Success:
815   case Sema::TDK_Invalid:
816   case Sema::TDK_InstantiationDepth:
817   case Sema::TDK_Incomplete:
818   case Sema::TDK_TooManyArguments:
819   case Sema::TDK_TooFewArguments:
820   case Sema::TDK_InvalidExplicitArguments:
821   case Sema::TDK_SubstitutionFailure:
822   case Sema::TDK_CUDATargetMismatch:
823   case Sema::TDK_NonDependentConversionFailure:
824   case Sema::TDK_ConstraintsNotSatisfied:
825     return nullptr;
826 
827   case Sema::TDK_IncompletePack:
828   case Sema::TDK_Inconsistent:
829   case Sema::TDK_Underqualified:
830   case Sema::TDK_DeducedMismatch:
831   case Sema::TDK_DeducedMismatchNested:
832   case Sema::TDK_NonDeducedMismatch:
833     return &static_cast<DFIArguments*>(Data)->FirstArg;
834 
835   // Unhandled
836   case Sema::TDK_MiscellaneousDeductionFailure:
837     break;
838   }
839 
840   return nullptr;
841 }
842 
843 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
844   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
845   case Sema::TDK_Success:
846   case Sema::TDK_Invalid:
847   case Sema::TDK_InstantiationDepth:
848   case Sema::TDK_Incomplete:
849   case Sema::TDK_IncompletePack:
850   case Sema::TDK_TooManyArguments:
851   case Sema::TDK_TooFewArguments:
852   case Sema::TDK_InvalidExplicitArguments:
853   case Sema::TDK_SubstitutionFailure:
854   case Sema::TDK_CUDATargetMismatch:
855   case Sema::TDK_NonDependentConversionFailure:
856   case Sema::TDK_ConstraintsNotSatisfied:
857     return nullptr;
858 
859   case Sema::TDK_Inconsistent:
860   case Sema::TDK_Underqualified:
861   case Sema::TDK_DeducedMismatch:
862   case Sema::TDK_DeducedMismatchNested:
863   case Sema::TDK_NonDeducedMismatch:
864     return &static_cast<DFIArguments*>(Data)->SecondArg;
865 
866   // Unhandled
867   case Sema::TDK_MiscellaneousDeductionFailure:
868     break;
869   }
870 
871   return nullptr;
872 }
873 
874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
875   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
876   case Sema::TDK_DeducedMismatch:
877   case Sema::TDK_DeducedMismatchNested:
878     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
879 
880   default:
881     return llvm::None;
882   }
883 }
884 
885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
886     OverloadedOperatorKind Op) {
887   if (!AllowRewrittenCandidates)
888     return false;
889   return Op == OO_EqualEqual || Op == OO_Spaceship;
890 }
891 
892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
893     ASTContext &Ctx, const FunctionDecl *FD) {
894   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
895     return false;
896   // Don't bother adding a reversed candidate that can never be a better
897   // match than the non-reversed version.
898   return FD->getNumParams() != 2 ||
899          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
900                                      FD->getParamDecl(1)->getType()) ||
901          FD->hasAttr<EnableIfAttr>();
902 }
903 
904 void OverloadCandidateSet::destroyCandidates() {
905   for (iterator i = begin(), e = end(); i != e; ++i) {
906     for (auto &C : i->Conversions)
907       C.~ImplicitConversionSequence();
908     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
909       i->DeductionFailure.Destroy();
910   }
911 }
912 
913 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
914   destroyCandidates();
915   SlabAllocator.Reset();
916   NumInlineBytesUsed = 0;
917   Candidates.clear();
918   Functions.clear();
919   Kind = CSK;
920 }
921 
922 namespace {
923   class UnbridgedCastsSet {
924     struct Entry {
925       Expr **Addr;
926       Expr *Saved;
927     };
928     SmallVector<Entry, 2> Entries;
929 
930   public:
931     void save(Sema &S, Expr *&E) {
932       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
933       Entry entry = { &E, E };
934       Entries.push_back(entry);
935       E = S.stripARCUnbridgedCast(E);
936     }
937 
938     void restore() {
939       for (SmallVectorImpl<Entry>::iterator
940              i = Entries.begin(), e = Entries.end(); i != e; ++i)
941         *i->Addr = i->Saved;
942     }
943   };
944 }
945 
946 /// checkPlaceholderForOverload - Do any interesting placeholder-like
947 /// preprocessing on the given expression.
948 ///
949 /// \param unbridgedCasts a collection to which to add unbridged casts;
950 ///   without this, they will be immediately diagnosed as errors
951 ///
952 /// Return true on unrecoverable error.
953 static bool
954 checkPlaceholderForOverload(Sema &S, Expr *&E,
955                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
956   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
957     // We can't handle overloaded expressions here because overload
958     // resolution might reasonably tweak them.
959     if (placeholder->getKind() == BuiltinType::Overload) return false;
960 
961     // If the context potentially accepts unbridged ARC casts, strip
962     // the unbridged cast and add it to the collection for later restoration.
963     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
964         unbridgedCasts) {
965       unbridgedCasts->save(S, E);
966       return false;
967     }
968 
969     // Go ahead and check everything else.
970     ExprResult result = S.CheckPlaceholderExpr(E);
971     if (result.isInvalid())
972       return true;
973 
974     E = result.get();
975     return false;
976   }
977 
978   // Nothing to do.
979   return false;
980 }
981 
982 /// checkArgPlaceholdersForOverload - Check a set of call operands for
983 /// placeholders.
984 static bool checkArgPlaceholdersForOverload(Sema &S,
985                                             MultiExprArg Args,
986                                             UnbridgedCastsSet &unbridged) {
987   for (unsigned i = 0, e = Args.size(); i != e; ++i)
988     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
989       return true;
990 
991   return false;
992 }
993 
994 /// Determine whether the given New declaration is an overload of the
995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
996 /// New and Old cannot be overloaded, e.g., if New has the same signature as
997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
998 /// functions (or function templates) at all. When it does return Ovl_Match or
999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1001 /// declaration.
1002 ///
1003 /// Example: Given the following input:
1004 ///
1005 ///   void f(int, float); // #1
1006 ///   void f(int, int); // #2
1007 ///   int f(int, int); // #3
1008 ///
1009 /// When we process #1, there is no previous declaration of "f", so IsOverload
1010 /// will not be used.
1011 ///
1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1015 /// unchanged.
1016 ///
1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1021 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1022 ///
1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1024 /// by a using declaration. The rules for whether to hide shadow declarations
1025 /// ignore some properties which otherwise figure into a function template's
1026 /// signature.
1027 Sema::OverloadKind
1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1029                     NamedDecl *&Match, bool NewIsUsingDecl) {
1030   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1031          I != E; ++I) {
1032     NamedDecl *OldD = *I;
1033 
1034     bool OldIsUsingDecl = false;
1035     if (isa<UsingShadowDecl>(OldD)) {
1036       OldIsUsingDecl = true;
1037 
1038       // We can always introduce two using declarations into the same
1039       // context, even if they have identical signatures.
1040       if (NewIsUsingDecl) continue;
1041 
1042       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1043     }
1044 
1045     // A using-declaration does not conflict with another declaration
1046     // if one of them is hidden.
1047     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1048       continue;
1049 
1050     // If either declaration was introduced by a using declaration,
1051     // we'll need to use slightly different rules for matching.
1052     // Essentially, these rules are the normal rules, except that
1053     // function templates hide function templates with different
1054     // return types or template parameter lists.
1055     bool UseMemberUsingDeclRules =
1056       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1057       !New->getFriendObjectKind();
1058 
1059     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1060       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1061         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1062           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1063           continue;
1064         }
1065 
1066         if (!isa<FunctionTemplateDecl>(OldD) &&
1067             !shouldLinkPossiblyHiddenDecl(*I, New))
1068           continue;
1069 
1070         Match = *I;
1071         return Ovl_Match;
1072       }
1073 
1074       // Builtins that have custom typechecking or have a reference should
1075       // not be overloadable or redeclarable.
1076       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1077         Match = *I;
1078         return Ovl_NonFunction;
1079       }
1080     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1081       // We can overload with these, which can show up when doing
1082       // redeclaration checks for UsingDecls.
1083       assert(Old.getLookupKind() == LookupUsingDeclName);
1084     } else if (isa<TagDecl>(OldD)) {
1085       // We can always overload with tags by hiding them.
1086     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1087       // Optimistically assume that an unresolved using decl will
1088       // overload; if it doesn't, we'll have to diagnose during
1089       // template instantiation.
1090       //
1091       // Exception: if the scope is dependent and this is not a class
1092       // member, the using declaration can only introduce an enumerator.
1093       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1094         Match = *I;
1095         return Ovl_NonFunction;
1096       }
1097     } else {
1098       // (C++ 13p1):
1099       //   Only function declarations can be overloaded; object and type
1100       //   declarations cannot be overloaded.
1101       Match = *I;
1102       return Ovl_NonFunction;
1103     }
1104   }
1105 
1106   // C++ [temp.friend]p1:
1107   //   For a friend function declaration that is not a template declaration:
1108   //    -- if the name of the friend is a qualified or unqualified template-id,
1109   //       [...], otherwise
1110   //    -- if the name of the friend is a qualified-id and a matching
1111   //       non-template function is found in the specified class or namespace,
1112   //       the friend declaration refers to that function, otherwise,
1113   //    -- if the name of the friend is a qualified-id and a matching function
1114   //       template is found in the specified class or namespace, the friend
1115   //       declaration refers to the deduced specialization of that function
1116   //       template, otherwise
1117   //    -- the name shall be an unqualified-id [...]
1118   // If we get here for a qualified friend declaration, we've just reached the
1119   // third bullet. If the type of the friend is dependent, skip this lookup
1120   // until instantiation.
1121   if (New->getFriendObjectKind() && New->getQualifier() &&
1122       !New->getDescribedFunctionTemplate() &&
1123       !New->getDependentSpecializationInfo() &&
1124       !New->getType()->isDependentType()) {
1125     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1126     TemplateSpecResult.addAllDecls(Old);
1127     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1128                                             /*QualifiedFriend*/true)) {
1129       New->setInvalidDecl();
1130       return Ovl_Overload;
1131     }
1132 
1133     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1134     return Ovl_Match;
1135   }
1136 
1137   return Ovl_Overload;
1138 }
1139 
1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1141                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1142                       bool ConsiderRequiresClauses) {
1143   // C++ [basic.start.main]p2: This function shall not be overloaded.
1144   if (New->isMain())
1145     return false;
1146 
1147   // MSVCRT user defined entry points cannot be overloaded.
1148   if (New->isMSVCRTEntryPoint())
1149     return false;
1150 
1151   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1152   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1153 
1154   // C++ [temp.fct]p2:
1155   //   A function template can be overloaded with other function templates
1156   //   and with normal (non-template) functions.
1157   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1158     return true;
1159 
1160   // Is the function New an overload of the function Old?
1161   QualType OldQType = Context.getCanonicalType(Old->getType());
1162   QualType NewQType = Context.getCanonicalType(New->getType());
1163 
1164   // Compare the signatures (C++ 1.3.10) of the two functions to
1165   // determine whether they are overloads. If we find any mismatch
1166   // in the signature, they are overloads.
1167 
1168   // If either of these functions is a K&R-style function (no
1169   // prototype), then we consider them to have matching signatures.
1170   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1171       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1172     return false;
1173 
1174   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1175   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1176 
1177   // The signature of a function includes the types of its
1178   // parameters (C++ 1.3.10), which includes the presence or absence
1179   // of the ellipsis; see C++ DR 357).
1180   if (OldQType != NewQType &&
1181       (OldType->getNumParams() != NewType->getNumParams() ||
1182        OldType->isVariadic() != NewType->isVariadic() ||
1183        !FunctionParamTypesAreEqual(OldType, NewType)))
1184     return true;
1185 
1186   // C++ [temp.over.link]p4:
1187   //   The signature of a function template consists of its function
1188   //   signature, its return type and its template parameter list. The names
1189   //   of the template parameters are significant only for establishing the
1190   //   relationship between the template parameters and the rest of the
1191   //   signature.
1192   //
1193   // We check the return type and template parameter lists for function
1194   // templates first; the remaining checks follow.
1195   //
1196   // However, we don't consider either of these when deciding whether
1197   // a member introduced by a shadow declaration is hidden.
1198   if (!UseMemberUsingDeclRules && NewTemplate &&
1199       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1200                                        OldTemplate->getTemplateParameters(),
1201                                        false, TPL_TemplateMatch) ||
1202        !Context.hasSameType(Old->getDeclaredReturnType(),
1203                             New->getDeclaredReturnType())))
1204     return true;
1205 
1206   // If the function is a class member, its signature includes the
1207   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1208   //
1209   // As part of this, also check whether one of the member functions
1210   // is static, in which case they are not overloads (C++
1211   // 13.1p2). While not part of the definition of the signature,
1212   // this check is important to determine whether these functions
1213   // can be overloaded.
1214   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1215   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1216   if (OldMethod && NewMethod &&
1217       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1218     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1219       if (!UseMemberUsingDeclRules &&
1220           (OldMethod->getRefQualifier() == RQ_None ||
1221            NewMethod->getRefQualifier() == RQ_None)) {
1222         // C++0x [over.load]p2:
1223         //   - Member function declarations with the same name and the same
1224         //     parameter-type-list as well as member function template
1225         //     declarations with the same name, the same parameter-type-list, and
1226         //     the same template parameter lists cannot be overloaded if any of
1227         //     them, but not all, have a ref-qualifier (8.3.5).
1228         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1229           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1230         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1231       }
1232       return true;
1233     }
1234 
1235     // We may not have applied the implicit const for a constexpr member
1236     // function yet (because we haven't yet resolved whether this is a static
1237     // or non-static member function). Add it now, on the assumption that this
1238     // is a redeclaration of OldMethod.
1239     auto OldQuals = OldMethod->getMethodQualifiers();
1240     auto NewQuals = NewMethod->getMethodQualifiers();
1241     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1242         !isa<CXXConstructorDecl>(NewMethod))
1243       NewQuals.addConst();
1244     // We do not allow overloading based off of '__restrict'.
1245     OldQuals.removeRestrict();
1246     NewQuals.removeRestrict();
1247     if (OldQuals != NewQuals)
1248       return true;
1249   }
1250 
1251   // Though pass_object_size is placed on parameters and takes an argument, we
1252   // consider it to be a function-level modifier for the sake of function
1253   // identity. Either the function has one or more parameters with
1254   // pass_object_size or it doesn't.
1255   if (functionHasPassObjectSizeParams(New) !=
1256       functionHasPassObjectSizeParams(Old))
1257     return true;
1258 
1259   // enable_if attributes are an order-sensitive part of the signature.
1260   for (specific_attr_iterator<EnableIfAttr>
1261          NewI = New->specific_attr_begin<EnableIfAttr>(),
1262          NewE = New->specific_attr_end<EnableIfAttr>(),
1263          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1264          OldE = Old->specific_attr_end<EnableIfAttr>();
1265        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1266     if (NewI == NewE || OldI == OldE)
1267       return true;
1268     llvm::FoldingSetNodeID NewID, OldID;
1269     NewI->getCond()->Profile(NewID, Context, true);
1270     OldI->getCond()->Profile(OldID, Context, true);
1271     if (NewID != OldID)
1272       return true;
1273   }
1274 
1275   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1276     // Don't allow overloading of destructors.  (In theory we could, but it
1277     // would be a giant change to clang.)
1278     if (!isa<CXXDestructorDecl>(New)) {
1279       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1280                          OldTarget = IdentifyCUDATarget(Old);
1281       if (NewTarget != CFT_InvalidTarget) {
1282         assert((OldTarget != CFT_InvalidTarget) &&
1283                "Unexpected invalid target.");
1284 
1285         // Allow overloading of functions with same signature and different CUDA
1286         // target attributes.
1287         if (NewTarget != OldTarget)
1288           return true;
1289       }
1290     }
1291   }
1292 
1293   if (ConsiderRequiresClauses) {
1294     Expr *NewRC = New->getTrailingRequiresClause(),
1295          *OldRC = Old->getTrailingRequiresClause();
1296     if ((NewRC != nullptr) != (OldRC != nullptr))
1297       // RC are most certainly different - these are overloads.
1298       return true;
1299 
1300     if (NewRC) {
1301       llvm::FoldingSetNodeID NewID, OldID;
1302       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1303       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1304       if (NewID != OldID)
1305         // RCs are not equivalent - these are overloads.
1306         return true;
1307     }
1308   }
1309 
1310   // The signatures match; this is not an overload.
1311   return false;
1312 }
1313 
1314 /// Tries a user-defined conversion from From to ToType.
1315 ///
1316 /// Produces an implicit conversion sequence for when a standard conversion
1317 /// is not an option. See TryImplicitConversion for more information.
1318 static ImplicitConversionSequence
1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1320                          bool SuppressUserConversions,
1321                          AllowedExplicit AllowExplicit,
1322                          bool InOverloadResolution,
1323                          bool CStyle,
1324                          bool AllowObjCWritebackConversion,
1325                          bool AllowObjCConversionOnExplicit) {
1326   ImplicitConversionSequence ICS;
1327 
1328   if (SuppressUserConversions) {
1329     // We're not in the case above, so there is no conversion that
1330     // we can perform.
1331     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1332     return ICS;
1333   }
1334 
1335   // Attempt user-defined conversion.
1336   OverloadCandidateSet Conversions(From->getExprLoc(),
1337                                    OverloadCandidateSet::CSK_Normal);
1338   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1339                                   Conversions, AllowExplicit,
1340                                   AllowObjCConversionOnExplicit)) {
1341   case OR_Success:
1342   case OR_Deleted:
1343     ICS.setUserDefined();
1344     // C++ [over.ics.user]p4:
1345     //   A conversion of an expression of class type to the same class
1346     //   type is given Exact Match rank, and a conversion of an
1347     //   expression of class type to a base class of that type is
1348     //   given Conversion rank, in spite of the fact that a copy
1349     //   constructor (i.e., a user-defined conversion function) is
1350     //   called for those cases.
1351     if (CXXConstructorDecl *Constructor
1352           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1353       QualType FromCanon
1354         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1355       QualType ToCanon
1356         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1357       if (Constructor->isCopyConstructor() &&
1358           (FromCanon == ToCanon ||
1359            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1360         // Turn this into a "standard" conversion sequence, so that it
1361         // gets ranked with standard conversion sequences.
1362         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1363         ICS.setStandard();
1364         ICS.Standard.setAsIdentityConversion();
1365         ICS.Standard.setFromType(From->getType());
1366         ICS.Standard.setAllToTypes(ToType);
1367         ICS.Standard.CopyConstructor = Constructor;
1368         ICS.Standard.FoundCopyConstructor = Found;
1369         if (ToCanon != FromCanon)
1370           ICS.Standard.Second = ICK_Derived_To_Base;
1371       }
1372     }
1373     break;
1374 
1375   case OR_Ambiguous:
1376     ICS.setAmbiguous();
1377     ICS.Ambiguous.setFromType(From->getType());
1378     ICS.Ambiguous.setToType(ToType);
1379     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1380          Cand != Conversions.end(); ++Cand)
1381       if (Cand->Best)
1382         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1383     break;
1384 
1385     // Fall through.
1386   case OR_No_Viable_Function:
1387     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1388     break;
1389   }
1390 
1391   return ICS;
1392 }
1393 
1394 /// TryImplicitConversion - Attempt to perform an implicit conversion
1395 /// from the given expression (Expr) to the given type (ToType). This
1396 /// function returns an implicit conversion sequence that can be used
1397 /// to perform the initialization. Given
1398 ///
1399 ///   void f(float f);
1400 ///   void g(int i) { f(i); }
1401 ///
1402 /// this routine would produce an implicit conversion sequence to
1403 /// describe the initialization of f from i, which will be a standard
1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1406 //
1407 /// Note that this routine only determines how the conversion can be
1408 /// performed; it does not actually perform the conversion. As such,
1409 /// it will not produce any diagnostics if no conversion is available,
1410 /// but will instead return an implicit conversion sequence of kind
1411 /// "BadConversion".
1412 ///
1413 /// If @p SuppressUserConversions, then user-defined conversions are
1414 /// not permitted.
1415 /// If @p AllowExplicit, then explicit user-defined conversions are
1416 /// permitted.
1417 ///
1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1419 /// writeback conversion, which allows __autoreleasing id* parameters to
1420 /// be initialized with __strong id* or __weak id* arguments.
1421 static ImplicitConversionSequence
1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1423                       bool SuppressUserConversions,
1424                       AllowedExplicit AllowExplicit,
1425                       bool InOverloadResolution,
1426                       bool CStyle,
1427                       bool AllowObjCWritebackConversion,
1428                       bool AllowObjCConversionOnExplicit) {
1429   ImplicitConversionSequence ICS;
1430   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1431                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1432     ICS.setStandard();
1433     return ICS;
1434   }
1435 
1436   if (!S.getLangOpts().CPlusPlus) {
1437     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1438     return ICS;
1439   }
1440 
1441   // C++ [over.ics.user]p4:
1442   //   A conversion of an expression of class type to the same class
1443   //   type is given Exact Match rank, and a conversion of an
1444   //   expression of class type to a base class of that type is
1445   //   given Conversion rank, in spite of the fact that a copy/move
1446   //   constructor (i.e., a user-defined conversion function) is
1447   //   called for those cases.
1448   QualType FromType = From->getType();
1449   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1450       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1451        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1452     ICS.setStandard();
1453     ICS.Standard.setAsIdentityConversion();
1454     ICS.Standard.setFromType(FromType);
1455     ICS.Standard.setAllToTypes(ToType);
1456 
1457     // We don't actually check at this point whether there is a valid
1458     // copy/move constructor, since overloading just assumes that it
1459     // exists. When we actually perform initialization, we'll find the
1460     // appropriate constructor to copy the returned object, if needed.
1461     ICS.Standard.CopyConstructor = nullptr;
1462 
1463     // Determine whether this is considered a derived-to-base conversion.
1464     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1465       ICS.Standard.Second = ICK_Derived_To_Base;
1466 
1467     return ICS;
1468   }
1469 
1470   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1471                                   AllowExplicit, InOverloadResolution, CStyle,
1472                                   AllowObjCWritebackConversion,
1473                                   AllowObjCConversionOnExplicit);
1474 }
1475 
1476 ImplicitConversionSequence
1477 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1478                             bool SuppressUserConversions,
1479                             AllowedExplicit AllowExplicit,
1480                             bool InOverloadResolution,
1481                             bool CStyle,
1482                             bool AllowObjCWritebackConversion) {
1483   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1484                                  AllowExplicit, InOverloadResolution, CStyle,
1485                                  AllowObjCWritebackConversion,
1486                                  /*AllowObjCConversionOnExplicit=*/false);
1487 }
1488 
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1494 ExprResult
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                 AssignmentAction Action, bool AllowExplicit) {
1497   ImplicitConversionSequence ICS;
1498   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499 }
1500 
1501 ExprResult
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503                                 AssignmentAction Action, bool AllowExplicit,
1504                                 ImplicitConversionSequence& ICS) {
1505   if (checkPlaceholderForOverload(*this, From))
1506     return ExprError();
1507 
1508   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509   bool AllowObjCWritebackConversion
1510     = getLangOpts().ObjCAutoRefCount &&
1511       (Action == AA_Passing || Action == AA_Sending);
1512   if (getLangOpts().ObjC)
1513     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514                                       From->getType(), From);
1515   ICS = ::TryImplicitConversion(*this, From, ToType,
1516                                 /*SuppressUserConversions=*/false,
1517                                 AllowExplicit ? AllowedExplicit::All
1518                                               : AllowedExplicit::None,
1519                                 /*InOverloadResolution=*/false,
1520                                 /*CStyle=*/false, AllowObjCWritebackConversion,
1521                                 /*AllowObjCConversionOnExplicit=*/false);
1522   return PerformImplicitConversion(From, ToType, ICS, Action);
1523 }
1524 
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1527 /// type.
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529                                 QualType &ResultTy) {
1530   if (Context.hasSameUnqualifiedType(FromType, ToType))
1531     return false;
1532 
1533   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534   //                    or F(t noexcept) -> F(t)
1535   // where F adds one of the following at most once:
1536   //   - a pointer
1537   //   - a member pointer
1538   //   - a block pointer
1539   // Changes here need matching changes in FindCompositePointerType.
1540   CanQualType CanTo = Context.getCanonicalType(ToType);
1541   CanQualType CanFrom = Context.getCanonicalType(FromType);
1542   Type::TypeClass TyClass = CanTo->getTypeClass();
1543   if (TyClass != CanFrom->getTypeClass()) return false;
1544   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545     if (TyClass == Type::Pointer) {
1546       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548     } else if (TyClass == Type::BlockPointer) {
1549       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551     } else if (TyClass == Type::MemberPointer) {
1552       auto ToMPT = CanTo.castAs<MemberPointerType>();
1553       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554       // A function pointer conversion cannot change the class of the function.
1555       if (ToMPT->getClass() != FromMPT->getClass())
1556         return false;
1557       CanTo = ToMPT->getPointeeType();
1558       CanFrom = FromMPT->getPointeeType();
1559     } else {
1560       return false;
1561     }
1562 
1563     TyClass = CanTo->getTypeClass();
1564     if (TyClass != CanFrom->getTypeClass()) return false;
1565     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566       return false;
1567   }
1568 
1569   const auto *FromFn = cast<FunctionType>(CanFrom);
1570   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571 
1572   const auto *ToFn = cast<FunctionType>(CanTo);
1573   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574 
1575   bool Changed = false;
1576 
1577   // Drop 'noreturn' if not present in target type.
1578   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580     Changed = true;
1581   }
1582 
1583   // Drop 'noexcept' if not present in target type.
1584   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587       FromFn = cast<FunctionType>(
1588           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589                                                    EST_None)
1590                  .getTypePtr());
1591       Changed = true;
1592     }
1593 
1594     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595     // only if the ExtParameterInfo lists of the two function prototypes can be
1596     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598     bool CanUseToFPT, CanUseFromFPT;
1599     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600                                       CanUseFromFPT, NewParamInfos) &&
1601         CanUseToFPT && !CanUseFromFPT) {
1602       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603       ExtInfo.ExtParameterInfos =
1604           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606                                             FromFPT->getParamTypes(), ExtInfo);
1607       FromFn = QT->getAs<FunctionType>();
1608       Changed = true;
1609     }
1610   }
1611 
1612   if (!Changed)
1613     return false;
1614 
1615   assert(QualType(FromFn, 0).isCanonical());
1616   if (QualType(FromFn, 0) != CanTo) return false;
1617 
1618   ResultTy = ToType;
1619   return true;
1620 }
1621 
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1624 ///
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1626 /// conversion.
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628                                QualType ToType, ImplicitConversionKind &ICK) {
1629   // We need at least one of these types to be a vector type to have a vector
1630   // conversion.
1631   if (!ToType->isVectorType() && !FromType->isVectorType())
1632     return false;
1633 
1634   // Identical types require no conversions.
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636     return false;
1637 
1638   // There are no conversions between extended vector types, only identity.
1639   if (ToType->isExtVectorType()) {
1640     // There are no conversions between extended vector types other than the
1641     // identity conversion.
1642     if (FromType->isExtVectorType())
1643       return false;
1644 
1645     // Vector splat from any arithmetic type to a vector.
1646     if (FromType->isArithmeticType()) {
1647       ICK = ICK_Vector_Splat;
1648       return true;
1649     }
1650   }
1651 
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   // 3)the destination type does not have the ARM MVE strict-polymorphism
1657   //   attribute, which inhibits lax vector conversion for overload resolution
1658   //   only
1659   if (ToType->isVectorType() && FromType->isVectorType()) {
1660     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661         (S.isLaxVectorConversion(FromType, ToType) &&
1662          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663       ICK = ICK_Vector_Conversion;
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672                                 bool InOverloadResolution,
1673                                 StandardConversionSequence &SCS,
1674                                 bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685                                  bool InOverloadResolution,
1686                                  StandardConversionSequence &SCS,
1687                                  bool CStyle,
1688                                  bool AllowObjCWritebackConversion) {
1689   QualType FromType = From->getType();
1690 
1691   // Standard conversions (C++ [conv])
1692   SCS.setAsIdentityConversion();
1693   SCS.IncompatibleObjC = false;
1694   SCS.setFromType(FromType);
1695   SCS.CopyConstructor = nullptr;
1696 
1697   // There are no standard conversions for class types in C++, so
1698   // abort early. When overloading in C, however, we do permit them.
1699   if (S.getLangOpts().CPlusPlus &&
1700       (FromType->isRecordType() || ToType->isRecordType()))
1701     return false;
1702 
1703   // The first conversion can be an lvalue-to-rvalue conversion,
1704   // array-to-pointer conversion, or function-to-pointer conversion
1705   // (C++ 4p1).
1706 
1707   if (FromType == S.Context.OverloadTy) {
1708     DeclAccessPair AccessPair;
1709     if (FunctionDecl *Fn
1710           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711                                                  AccessPair)) {
1712       // We were able to resolve the address of the overloaded function,
1713       // so we can convert to the type of that function.
1714       FromType = Fn->getType();
1715       SCS.setFromType(FromType);
1716 
1717       // we can sometimes resolve &foo<int> regardless of ToType, so check
1718       // if the type matches (identity) or we are converting to bool
1719       if (!S.Context.hasSameUnqualifiedType(
1720                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721         QualType resultTy;
1722         // if the function type matches except for [[noreturn]], it's ok
1723         if (!S.IsFunctionConversion(FromType,
1724               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725           // otherwise, only a boolean conversion is standard
1726           if (!ToType->isBooleanType())
1727             return false;
1728       }
1729 
1730       // Check if the "from" expression is taking the address of an overloaded
1731       // function and recompute the FromType accordingly. Take advantage of the
1732       // fact that non-static member functions *must* have such an address-of
1733       // expression.
1734       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735       if (Method && !Method->isStatic()) {
1736         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737                "Non-unary operator on non-static member address");
1738         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739                == UO_AddrOf &&
1740                "Non-address-of operator on non-static member address");
1741         const Type *ClassType
1742           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746                UO_AddrOf &&
1747                "Non-address-of operator for overloaded function expression");
1748         FromType = S.Context.getPointerType(FromType);
1749       }
1750 
1751       // Check that we've computed the proper type after overload resolution.
1752       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1753       // be calling it from within an NDEBUG block.
1754       assert(S.Context.hasSameType(
1755         FromType,
1756         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757     } else {
1758       return false;
1759     }
1760   }
1761   // Lvalue-to-rvalue conversion (C++11 4.1):
1762   //   A glvalue (3.10) of a non-function, non-array type T can
1763   //   be converted to a prvalue.
1764   bool argIsLValue = From->isGLValue();
1765   if (argIsLValue &&
1766       !FromType->isFunctionType() && !FromType->isArrayType() &&
1767       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1768     SCS.First = ICK_Lvalue_To_Rvalue;
1769 
1770     // C11 6.3.2.1p2:
1771     //   ... if the lvalue has atomic type, the value has the non-atomic version
1772     //   of the type of the lvalue ...
1773     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1774       FromType = Atomic->getValueType();
1775 
1776     // If T is a non-class type, the type of the rvalue is the
1777     // cv-unqualified version of T. Otherwise, the type of the rvalue
1778     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1779     // just strip the qualifiers because they don't matter.
1780     FromType = FromType.getUnqualifiedType();
1781   } else if (FromType->isArrayType()) {
1782     // Array-to-pointer conversion (C++ 4.2)
1783     SCS.First = ICK_Array_To_Pointer;
1784 
1785     // An lvalue or rvalue of type "array of N T" or "array of unknown
1786     // bound of T" can be converted to an rvalue of type "pointer to
1787     // T" (C++ 4.2p1).
1788     FromType = S.Context.getArrayDecayedType(FromType);
1789 
1790     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1791       // This conversion is deprecated in C++03 (D.4)
1792       SCS.DeprecatedStringLiteralToCharPtr = true;
1793 
1794       // For the purpose of ranking in overload resolution
1795       // (13.3.3.1.1), this conversion is considered an
1796       // array-to-pointer conversion followed by a qualification
1797       // conversion (4.4). (C++ 4.2p2)
1798       SCS.Second = ICK_Identity;
1799       SCS.Third = ICK_Qualification;
1800       SCS.QualificationIncludesObjCLifetime = false;
1801       SCS.setAllToTypes(FromType);
1802       return true;
1803     }
1804   } else if (FromType->isFunctionType() && argIsLValue) {
1805     // Function-to-pointer conversion (C++ 4.3).
1806     SCS.First = ICK_Function_To_Pointer;
1807 
1808     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1809       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1810         if (!S.checkAddressOfFunctionIsAvailable(FD))
1811           return false;
1812 
1813     // An lvalue of function type T can be converted to an rvalue of
1814     // type "pointer to T." The result is a pointer to the
1815     // function. (C++ 4.3p1).
1816     FromType = S.Context.getPointerType(FromType);
1817   } else {
1818     // We don't require any conversions for the first step.
1819     SCS.First = ICK_Identity;
1820   }
1821   SCS.setToType(0, FromType);
1822 
1823   // The second conversion can be an integral promotion, floating
1824   // point promotion, integral conversion, floating point conversion,
1825   // floating-integral conversion, pointer conversion,
1826   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1827   // For overloading in C, this can also be a "compatible-type"
1828   // conversion.
1829   bool IncompatibleObjC = false;
1830   ImplicitConversionKind SecondICK = ICK_Identity;
1831   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1832     // The unqualified versions of the types are the same: there's no
1833     // conversion to do.
1834     SCS.Second = ICK_Identity;
1835   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1836     // Integral promotion (C++ 4.5).
1837     SCS.Second = ICK_Integral_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1840     // Floating point promotion (C++ 4.6).
1841     SCS.Second = ICK_Floating_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsComplexPromotion(FromType, ToType)) {
1844     // Complex promotion (Clang extension)
1845     SCS.Second = ICK_Complex_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (ToType->isBooleanType() &&
1848              (FromType->isArithmeticType() ||
1849               FromType->isAnyPointerType() ||
1850               FromType->isBlockPointerType() ||
1851               FromType->isMemberPointerType() ||
1852               FromType->isNullPtrType())) {
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     if (&S.Context.getFloatTypeSemantics(FromType) !=
1875         &S.Context.getFloatTypeSemantics(ToType)) {
1876       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1877                                     ToType == S.Context.LongDoubleTy) ||
1878                                    (FromType == S.Context.LongDoubleTy &&
1879                                     ToType == S.Context.Float128Ty));
1880       if (Float128AndLongDouble &&
1881           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1882            &llvm::APFloat::PPCDoubleDouble()))
1883         return false;
1884     }
1885     // Floating point conversions (C++ 4.8).
1886     SCS.Second = ICK_Floating_Conversion;
1887     FromType = ToType.getUnqualifiedType();
1888   } else if ((FromType->isRealFloatingType() &&
1889               ToType->isIntegralType(S.Context)) ||
1890              (FromType->isIntegralOrUnscopedEnumerationType() &&
1891               ToType->isRealFloatingType())) {
1892     // Floating-integral conversions (C++ 4.9).
1893     SCS.Second = ICK_Floating_Integral;
1894     FromType = ToType.getUnqualifiedType();
1895   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1896     SCS.Second = ICK_Block_Pointer_Conversion;
1897   } else if (AllowObjCWritebackConversion &&
1898              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1899     SCS.Second = ICK_Writeback_Conversion;
1900   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1901                                    FromType, IncompatibleObjC)) {
1902     // Pointer conversions (C++ 4.10).
1903     SCS.Second = ICK_Pointer_Conversion;
1904     SCS.IncompatibleObjC = IncompatibleObjC;
1905     FromType = FromType.getUnqualifiedType();
1906   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1907                                          InOverloadResolution, FromType)) {
1908     // Pointer to member conversions (4.11).
1909     SCS.Second = ICK_Pointer_Member;
1910   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1911     SCS.Second = SecondICK;
1912     FromType = ToType.getUnqualifiedType();
1913   } else if (!S.getLangOpts().CPlusPlus &&
1914              S.Context.typesAreCompatible(ToType, FromType)) {
1915     // Compatible conversions (Clang extension for C function overloading)
1916     SCS.Second = ICK_Compatible_Conversion;
1917     FromType = ToType.getUnqualifiedType();
1918   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1919                                              InOverloadResolution,
1920                                              SCS, CStyle)) {
1921     SCS.Second = ICK_TransparentUnionConversion;
1922     FromType = ToType;
1923   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1924                                  CStyle)) {
1925     // tryAtomicConversion has updated the standard conversion sequence
1926     // appropriately.
1927     return true;
1928   } else if (ToType->isEventT() &&
1929              From->isIntegerConstantExpr(S.getASTContext()) &&
1930              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1931     SCS.Second = ICK_Zero_Event_Conversion;
1932     FromType = ToType;
1933   } else if (ToType->isQueueT() &&
1934              From->isIntegerConstantExpr(S.getASTContext()) &&
1935              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1936     SCS.Second = ICK_Zero_Queue_Conversion;
1937     FromType = ToType;
1938   } else if (ToType->isSamplerT() &&
1939              From->isIntegerConstantExpr(S.getASTContext())) {
1940     SCS.Second = ICK_Compatible_Conversion;
1941     FromType = ToType;
1942   } else {
1943     // No second conversion required.
1944     SCS.Second = ICK_Identity;
1945   }
1946   SCS.setToType(1, FromType);
1947 
1948   // The third conversion can be a function pointer conversion or a
1949   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1950   bool ObjCLifetimeConversion;
1951   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1952     // Function pointer conversions (removing 'noexcept') including removal of
1953     // 'noreturn' (Clang extension).
1954     SCS.Third = ICK_Function_Conversion;
1955   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1956                                          ObjCLifetimeConversion)) {
1957     SCS.Third = ICK_Qualification;
1958     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1959     FromType = ToType;
1960   } else {
1961     // No conversion required
1962     SCS.Third = ICK_Identity;
1963   }
1964 
1965   // C++ [over.best.ics]p6:
1966   //   [...] Any difference in top-level cv-qualification is
1967   //   subsumed by the initialization itself and does not constitute
1968   //   a conversion. [...]
1969   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1970   QualType CanonTo = S.Context.getCanonicalType(ToType);
1971   if (CanonFrom.getLocalUnqualifiedType()
1972                                      == CanonTo.getLocalUnqualifiedType() &&
1973       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1974     FromType = ToType;
1975     CanonFrom = CanonTo;
1976   }
1977 
1978   SCS.setToType(2, FromType);
1979 
1980   if (CanonFrom == CanonTo)
1981     return true;
1982 
1983   // If we have not converted the argument type to the parameter type,
1984   // this is a bad conversion sequence, unless we're resolving an overload in C.
1985   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1986     return false;
1987 
1988   ExprResult ER = ExprResult{From};
1989   Sema::AssignConvertType Conv =
1990       S.CheckSingleAssignmentConstraints(ToType, ER,
1991                                          /*Diagnose=*/false,
1992                                          /*DiagnoseCFAudited=*/false,
1993                                          /*ConvertRHS=*/false);
1994   ImplicitConversionKind SecondConv;
1995   switch (Conv) {
1996   case Sema::Compatible:
1997     SecondConv = ICK_C_Only_Conversion;
1998     break;
1999   // For our purposes, discarding qualifiers is just as bad as using an
2000   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2001   // qualifiers, as well.
2002   case Sema::CompatiblePointerDiscardsQualifiers:
2003   case Sema::IncompatiblePointer:
2004   case Sema::IncompatiblePointerSign:
2005     SecondConv = ICK_Incompatible_Pointer_Conversion;
2006     break;
2007   default:
2008     return false;
2009   }
2010 
2011   // First can only be an lvalue conversion, so we pretend that this was the
2012   // second conversion. First should already be valid from earlier in the
2013   // function.
2014   SCS.Second = SecondConv;
2015   SCS.setToType(1, ToType);
2016 
2017   // Third is Identity, because Second should rank us worse than any other
2018   // conversion. This could also be ICK_Qualification, but it's simpler to just
2019   // lump everything in with the second conversion, and we don't gain anything
2020   // from making this ICK_Qualification.
2021   SCS.Third = ICK_Identity;
2022   SCS.setToType(2, ToType);
2023   return true;
2024 }
2025 
2026 static bool
2027 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2028                                      QualType &ToType,
2029                                      bool InOverloadResolution,
2030                                      StandardConversionSequence &SCS,
2031                                      bool CStyle) {
2032 
2033   const RecordType *UT = ToType->getAsUnionType();
2034   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2035     return false;
2036   // The field to initialize within the transparent union.
2037   RecordDecl *UD = UT->getDecl();
2038   // It's compatible if the expression matches any of the fields.
2039   for (const auto *it : UD->fields()) {
2040     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2041                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2042       ToType = it->getType();
2043       return true;
2044     }
2045   }
2046   return false;
2047 }
2048 
2049 /// IsIntegralPromotion - Determines whether the conversion from the
2050 /// expression From (whose potentially-adjusted type is FromType) to
2051 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2052 /// sets PromotedType to the promoted type.
2053 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2054   const BuiltinType *To = ToType->getAs<BuiltinType>();
2055   // All integers are built-in.
2056   if (!To) {
2057     return false;
2058   }
2059 
2060   // An rvalue of type char, signed char, unsigned char, short int, or
2061   // unsigned short int can be converted to an rvalue of type int if
2062   // int can represent all the values of the source type; otherwise,
2063   // the source rvalue can be converted to an rvalue of type unsigned
2064   // int (C++ 4.5p1).
2065   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2066       !FromType->isEnumeralType()) {
2067     if (// We can promote any signed, promotable integer type to an int
2068         (FromType->isSignedIntegerType() ||
2069          // We can promote any unsigned integer type whose size is
2070          // less than int to an int.
2071          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2072       return To->getKind() == BuiltinType::Int;
2073     }
2074 
2075     return To->getKind() == BuiltinType::UInt;
2076   }
2077 
2078   // C++11 [conv.prom]p3:
2079   //   A prvalue of an unscoped enumeration type whose underlying type is not
2080   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2081   //   following types that can represent all the values of the enumeration
2082   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2083   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2084   //   long long int. If none of the types in that list can represent all the
2085   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2086   //   type can be converted to an rvalue a prvalue of the extended integer type
2087   //   with lowest integer conversion rank (4.13) greater than the rank of long
2088   //   long in which all the values of the enumeration can be represented. If
2089   //   there are two such extended types, the signed one is chosen.
2090   // C++11 [conv.prom]p4:
2091   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2092   //   can be converted to a prvalue of its underlying type. Moreover, if
2093   //   integral promotion can be applied to its underlying type, a prvalue of an
2094   //   unscoped enumeration type whose underlying type is fixed can also be
2095   //   converted to a prvalue of the promoted underlying type.
2096   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2097     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2098     // provided for a scoped enumeration.
2099     if (FromEnumType->getDecl()->isScoped())
2100       return false;
2101 
2102     // We can perform an integral promotion to the underlying type of the enum,
2103     // even if that's not the promoted type. Note that the check for promoting
2104     // the underlying type is based on the type alone, and does not consider
2105     // the bitfield-ness of the actual source expression.
2106     if (FromEnumType->getDecl()->isFixed()) {
2107       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2108       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2109              IsIntegralPromotion(nullptr, Underlying, ToType);
2110     }
2111 
2112     // We have already pre-calculated the promotion type, so this is trivial.
2113     if (ToType->isIntegerType() &&
2114         isCompleteType(From->getBeginLoc(), FromType))
2115       return Context.hasSameUnqualifiedType(
2116           ToType, FromEnumType->getDecl()->getPromotionType());
2117 
2118     // C++ [conv.prom]p5:
2119     //   If the bit-field has an enumerated type, it is treated as any other
2120     //   value of that type for promotion purposes.
2121     //
2122     // ... so do not fall through into the bit-field checks below in C++.
2123     if (getLangOpts().CPlusPlus)
2124       return false;
2125   }
2126 
2127   // C++0x [conv.prom]p2:
2128   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2129   //   to an rvalue a prvalue of the first of the following types that can
2130   //   represent all the values of its underlying type: int, unsigned int,
2131   //   long int, unsigned long int, long long int, or unsigned long long int.
2132   //   If none of the types in that list can represent all the values of its
2133   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2134   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2135   //   type.
2136   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2137       ToType->isIntegerType()) {
2138     // Determine whether the type we're converting from is signed or
2139     // unsigned.
2140     bool FromIsSigned = FromType->isSignedIntegerType();
2141     uint64_t FromSize = Context.getTypeSize(FromType);
2142 
2143     // The types we'll try to promote to, in the appropriate
2144     // order. Try each of these types.
2145     QualType PromoteTypes[6] = {
2146       Context.IntTy, Context.UnsignedIntTy,
2147       Context.LongTy, Context.UnsignedLongTy ,
2148       Context.LongLongTy, Context.UnsignedLongLongTy
2149     };
2150     for (int Idx = 0; Idx < 6; ++Idx) {
2151       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2152       if (FromSize < ToSize ||
2153           (FromSize == ToSize &&
2154            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2155         // We found the type that we can promote to. If this is the
2156         // type we wanted, we have a promotion. Otherwise, no
2157         // promotion.
2158         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2159       }
2160     }
2161   }
2162 
2163   // An rvalue for an integral bit-field (9.6) can be converted to an
2164   // rvalue of type int if int can represent all the values of the
2165   // bit-field; otherwise, it can be converted to unsigned int if
2166   // unsigned int can represent all the values of the bit-field. If
2167   // the bit-field is larger yet, no integral promotion applies to
2168   // it. If the bit-field has an enumerated type, it is treated as any
2169   // other value of that type for promotion purposes (C++ 4.5p3).
2170   // FIXME: We should delay checking of bit-fields until we actually perform the
2171   // conversion.
2172   //
2173   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2174   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2175   // bit-fields and those whose underlying type is larger than int) for GCC
2176   // compatibility.
2177   if (From) {
2178     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2179       llvm::APSInt BitWidth;
2180       if (FromType->isIntegralType(Context) &&
2181           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2182         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2183         ToSize = Context.getTypeSize(ToType);
2184 
2185         // Are we promoting to an int from a bitfield that fits in an int?
2186         if (BitWidth < ToSize ||
2187             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2188           return To->getKind() == BuiltinType::Int;
2189         }
2190 
2191         // Are we promoting to an unsigned int from an unsigned bitfield
2192         // that fits into an unsigned int?
2193         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2194           return To->getKind() == BuiltinType::UInt;
2195         }
2196 
2197         return false;
2198       }
2199     }
2200   }
2201 
2202   // An rvalue of type bool can be converted to an rvalue of type int,
2203   // with false becoming zero and true becoming one (C++ 4.5p4).
2204   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2205     return true;
2206   }
2207 
2208   return false;
2209 }
2210 
2211 /// IsFloatingPointPromotion - Determines whether the conversion from
2212 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2213 /// returns true and sets PromotedType to the promoted type.
2214 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2215   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2216     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2217       /// An rvalue of type float can be converted to an rvalue of type
2218       /// double. (C++ 4.6p1).
2219       if (FromBuiltin->getKind() == BuiltinType::Float &&
2220           ToBuiltin->getKind() == BuiltinType::Double)
2221         return true;
2222 
2223       // C99 6.3.1.5p1:
2224       //   When a float is promoted to double or long double, or a
2225       //   double is promoted to long double [...].
2226       if (!getLangOpts().CPlusPlus &&
2227           (FromBuiltin->getKind() == BuiltinType::Float ||
2228            FromBuiltin->getKind() == BuiltinType::Double) &&
2229           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2230            ToBuiltin->getKind() == BuiltinType::Float128))
2231         return true;
2232 
2233       // Half can be promoted to float.
2234       if (!getLangOpts().NativeHalfType &&
2235            FromBuiltin->getKind() == BuiltinType::Half &&
2236           ToBuiltin->getKind() == BuiltinType::Float)
2237         return true;
2238     }
2239 
2240   return false;
2241 }
2242 
2243 /// Determine if a conversion is a complex promotion.
2244 ///
2245 /// A complex promotion is defined as a complex -> complex conversion
2246 /// where the conversion between the underlying real types is a
2247 /// floating-point or integral promotion.
2248 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2249   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2250   if (!FromComplex)
2251     return false;
2252 
2253   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2254   if (!ToComplex)
2255     return false;
2256 
2257   return IsFloatingPointPromotion(FromComplex->getElementType(),
2258                                   ToComplex->getElementType()) ||
2259     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2260                         ToComplex->getElementType());
2261 }
2262 
2263 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2264 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2265 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2266 /// if non-empty, will be a pointer to ToType that may or may not have
2267 /// the right set of qualifiers on its pointee.
2268 ///
2269 static QualType
2270 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2271                                    QualType ToPointee, QualType ToType,
2272                                    ASTContext &Context,
2273                                    bool StripObjCLifetime = false) {
2274   assert((FromPtr->getTypeClass() == Type::Pointer ||
2275           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2276          "Invalid similarly-qualified pointer type");
2277 
2278   /// Conversions to 'id' subsume cv-qualifier conversions.
2279   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2280     return ToType.getUnqualifiedType();
2281 
2282   QualType CanonFromPointee
2283     = Context.getCanonicalType(FromPtr->getPointeeType());
2284   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2285   Qualifiers Quals = CanonFromPointee.getQualifiers();
2286 
2287   if (StripObjCLifetime)
2288     Quals.removeObjCLifetime();
2289 
2290   // Exact qualifier match -> return the pointer type we're converting to.
2291   if (CanonToPointee.getLocalQualifiers() == Quals) {
2292     // ToType is exactly what we need. Return it.
2293     if (!ToType.isNull())
2294       return ToType.getUnqualifiedType();
2295 
2296     // Build a pointer to ToPointee. It has the right qualifiers
2297     // already.
2298     if (isa<ObjCObjectPointerType>(ToType))
2299       return Context.getObjCObjectPointerType(ToPointee);
2300     return Context.getPointerType(ToPointee);
2301   }
2302 
2303   // Just build a canonical type that has the right qualifiers.
2304   QualType QualifiedCanonToPointee
2305     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2306 
2307   if (isa<ObjCObjectPointerType>(ToType))
2308     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2309   return Context.getPointerType(QualifiedCanonToPointee);
2310 }
2311 
2312 static bool isNullPointerConstantForConversion(Expr *Expr,
2313                                                bool InOverloadResolution,
2314                                                ASTContext &Context) {
2315   // Handle value-dependent integral null pointer constants correctly.
2316   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2317   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2318       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2319     return !InOverloadResolution;
2320 
2321   return Expr->isNullPointerConstant(Context,
2322                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2323                                         : Expr::NPC_ValueDependentIsNull);
2324 }
2325 
2326 /// IsPointerConversion - Determines whether the conversion of the
2327 /// expression From, which has the (possibly adjusted) type FromType,
2328 /// can be converted to the type ToType via a pointer conversion (C++
2329 /// 4.10). If so, returns true and places the converted type (that
2330 /// might differ from ToType in its cv-qualifiers at some level) into
2331 /// ConvertedType.
2332 ///
2333 /// This routine also supports conversions to and from block pointers
2334 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2335 /// pointers to interfaces. FIXME: Once we've determined the
2336 /// appropriate overloading rules for Objective-C, we may want to
2337 /// split the Objective-C checks into a different routine; however,
2338 /// GCC seems to consider all of these conversions to be pointer
2339 /// conversions, so for now they live here. IncompatibleObjC will be
2340 /// set if the conversion is an allowed Objective-C conversion that
2341 /// should result in a warning.
2342 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2343                                bool InOverloadResolution,
2344                                QualType& ConvertedType,
2345                                bool &IncompatibleObjC) {
2346   IncompatibleObjC = false;
2347   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2348                               IncompatibleObjC))
2349     return true;
2350 
2351   // Conversion from a null pointer constant to any Objective-C pointer type.
2352   if (ToType->isObjCObjectPointerType() &&
2353       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2354     ConvertedType = ToType;
2355     return true;
2356   }
2357 
2358   // Blocks: Block pointers can be converted to void*.
2359   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2360       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2361     ConvertedType = ToType;
2362     return true;
2363   }
2364   // Blocks: A null pointer constant can be converted to a block
2365   // pointer type.
2366   if (ToType->isBlockPointerType() &&
2367       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2368     ConvertedType = ToType;
2369     return true;
2370   }
2371 
2372   // If the left-hand-side is nullptr_t, the right side can be a null
2373   // pointer constant.
2374   if (ToType->isNullPtrType() &&
2375       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2376     ConvertedType = ToType;
2377     return true;
2378   }
2379 
2380   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2381   if (!ToTypePtr)
2382     return false;
2383 
2384   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2385   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386     ConvertedType = ToType;
2387     return true;
2388   }
2389 
2390   // Beyond this point, both types need to be pointers
2391   // , including objective-c pointers.
2392   QualType ToPointeeType = ToTypePtr->getPointeeType();
2393   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2394       !getLangOpts().ObjCAutoRefCount) {
2395     ConvertedType = BuildSimilarlyQualifiedPointerType(
2396                                       FromType->getAs<ObjCObjectPointerType>(),
2397                                                        ToPointeeType,
2398                                                        ToType, Context);
2399     return true;
2400   }
2401   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2402   if (!FromTypePtr)
2403     return false;
2404 
2405   QualType FromPointeeType = FromTypePtr->getPointeeType();
2406 
2407   // If the unqualified pointee types are the same, this can't be a
2408   // pointer conversion, so don't do all of the work below.
2409   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2410     return false;
2411 
2412   // An rvalue of type "pointer to cv T," where T is an object type,
2413   // can be converted to an rvalue of type "pointer to cv void" (C++
2414   // 4.10p2).
2415   if (FromPointeeType->isIncompleteOrObjectType() &&
2416       ToPointeeType->isVoidType()) {
2417     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2418                                                        ToPointeeType,
2419                                                        ToType, Context,
2420                                                    /*StripObjCLifetime=*/true);
2421     return true;
2422   }
2423 
2424   // MSVC allows implicit function to void* type conversion.
2425   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2426       ToPointeeType->isVoidType()) {
2427     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428                                                        ToPointeeType,
2429                                                        ToType, Context);
2430     return true;
2431   }
2432 
2433   // When we're overloading in C, we allow a special kind of pointer
2434   // conversion for compatible-but-not-identical pointee types.
2435   if (!getLangOpts().CPlusPlus &&
2436       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2437     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438                                                        ToPointeeType,
2439                                                        ToType, Context);
2440     return true;
2441   }
2442 
2443   // C++ [conv.ptr]p3:
2444   //
2445   //   An rvalue of type "pointer to cv D," where D is a class type,
2446   //   can be converted to an rvalue of type "pointer to cv B," where
2447   //   B is a base class (clause 10) of D. If B is an inaccessible
2448   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2449   //   necessitates this conversion is ill-formed. The result of the
2450   //   conversion is a pointer to the base class sub-object of the
2451   //   derived class object. The null pointer value is converted to
2452   //   the null pointer value of the destination type.
2453   //
2454   // Note that we do not check for ambiguity or inaccessibility
2455   // here. That is handled by CheckPointerConversion.
2456   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2457       ToPointeeType->isRecordType() &&
2458       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2459       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2460     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2461                                                        ToPointeeType,
2462                                                        ToType, Context);
2463     return true;
2464   }
2465 
2466   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2467       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2468     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2469                                                        ToPointeeType,
2470                                                        ToType, Context);
2471     return true;
2472   }
2473 
2474   return false;
2475 }
2476 
2477 /// Adopt the given qualifiers for the given type.
2478 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2479   Qualifiers TQs = T.getQualifiers();
2480 
2481   // Check whether qualifiers already match.
2482   if (TQs == Qs)
2483     return T;
2484 
2485   if (Qs.compatiblyIncludes(TQs))
2486     return Context.getQualifiedType(T, Qs);
2487 
2488   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2489 }
2490 
2491 /// isObjCPointerConversion - Determines whether this is an
2492 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2493 /// with the same arguments and return values.
2494 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2495                                    QualType& ConvertedType,
2496                                    bool &IncompatibleObjC) {
2497   if (!getLangOpts().ObjC)
2498     return false;
2499 
2500   // The set of qualifiers on the type we're converting from.
2501   Qualifiers FromQualifiers = FromType.getQualifiers();
2502 
2503   // First, we handle all conversions on ObjC object pointer types.
2504   const ObjCObjectPointerType* ToObjCPtr =
2505     ToType->getAs<ObjCObjectPointerType>();
2506   const ObjCObjectPointerType *FromObjCPtr =
2507     FromType->getAs<ObjCObjectPointerType>();
2508 
2509   if (ToObjCPtr && FromObjCPtr) {
2510     // If the pointee types are the same (ignoring qualifications),
2511     // then this is not a pointer conversion.
2512     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2513                                        FromObjCPtr->getPointeeType()))
2514       return false;
2515 
2516     // Conversion between Objective-C pointers.
2517     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2518       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2519       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2520       if (getLangOpts().CPlusPlus && LHS && RHS &&
2521           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2522                                                 FromObjCPtr->getPointeeType()))
2523         return false;
2524       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2525                                                    ToObjCPtr->getPointeeType(),
2526                                                          ToType, Context);
2527       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2528       return true;
2529     }
2530 
2531     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2532       // Okay: this is some kind of implicit downcast of Objective-C
2533       // interfaces, which is permitted. However, we're going to
2534       // complain about it.
2535       IncompatibleObjC = true;
2536       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537                                                    ToObjCPtr->getPointeeType(),
2538                                                          ToType, Context);
2539       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540       return true;
2541     }
2542   }
2543   // Beyond this point, both types need to be C pointers or block pointers.
2544   QualType ToPointeeType;
2545   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2546     ToPointeeType = ToCPtr->getPointeeType();
2547   else if (const BlockPointerType *ToBlockPtr =
2548             ToType->getAs<BlockPointerType>()) {
2549     // Objective C++: We're able to convert from a pointer to any object
2550     // to a block pointer type.
2551     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2552       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2553       return true;
2554     }
2555     ToPointeeType = ToBlockPtr->getPointeeType();
2556   }
2557   else if (FromType->getAs<BlockPointerType>() &&
2558            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2559     // Objective C++: We're able to convert from a block pointer type to a
2560     // pointer to any object.
2561     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562     return true;
2563   }
2564   else
2565     return false;
2566 
2567   QualType FromPointeeType;
2568   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2569     FromPointeeType = FromCPtr->getPointeeType();
2570   else if (const BlockPointerType *FromBlockPtr =
2571            FromType->getAs<BlockPointerType>())
2572     FromPointeeType = FromBlockPtr->getPointeeType();
2573   else
2574     return false;
2575 
2576   // If we have pointers to pointers, recursively check whether this
2577   // is an Objective-C conversion.
2578   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2579       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2580                               IncompatibleObjC)) {
2581     // We always complain about this conversion.
2582     IncompatibleObjC = true;
2583     ConvertedType = Context.getPointerType(ConvertedType);
2584     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2585     return true;
2586   }
2587   // Allow conversion of pointee being objective-c pointer to another one;
2588   // as in I* to id.
2589   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2590       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2591       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592                               IncompatibleObjC)) {
2593 
2594     ConvertedType = Context.getPointerType(ConvertedType);
2595     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596     return true;
2597   }
2598 
2599   // If we have pointers to functions or blocks, check whether the only
2600   // differences in the argument and result types are in Objective-C
2601   // pointer conversions. If so, we permit the conversion (but
2602   // complain about it).
2603   const FunctionProtoType *FromFunctionType
2604     = FromPointeeType->getAs<FunctionProtoType>();
2605   const FunctionProtoType *ToFunctionType
2606     = ToPointeeType->getAs<FunctionProtoType>();
2607   if (FromFunctionType && ToFunctionType) {
2608     // If the function types are exactly the same, this isn't an
2609     // Objective-C pointer conversion.
2610     if (Context.getCanonicalType(FromPointeeType)
2611           == Context.getCanonicalType(ToPointeeType))
2612       return false;
2613 
2614     // Perform the quick checks that will tell us whether these
2615     // function types are obviously different.
2616     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2617         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2618         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2619       return false;
2620 
2621     bool HasObjCConversion = false;
2622     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2623         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2624       // Okay, the types match exactly. Nothing to do.
2625     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2626                                        ToFunctionType->getReturnType(),
2627                                        ConvertedType, IncompatibleObjC)) {
2628       // Okay, we have an Objective-C pointer conversion.
2629       HasObjCConversion = true;
2630     } else {
2631       // Function types are too different. Abort.
2632       return false;
2633     }
2634 
2635     // Check argument types.
2636     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2637          ArgIdx != NumArgs; ++ArgIdx) {
2638       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2639       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2640       if (Context.getCanonicalType(FromArgType)
2641             == Context.getCanonicalType(ToArgType)) {
2642         // Okay, the types match exactly. Nothing to do.
2643       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2644                                          ConvertedType, IncompatibleObjC)) {
2645         // Okay, we have an Objective-C pointer conversion.
2646         HasObjCConversion = true;
2647       } else {
2648         // Argument types are too different. Abort.
2649         return false;
2650       }
2651     }
2652 
2653     if (HasObjCConversion) {
2654       // We had an Objective-C conversion. Allow this pointer
2655       // conversion, but complain about it.
2656       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2657       IncompatibleObjC = true;
2658       return true;
2659     }
2660   }
2661 
2662   return false;
2663 }
2664 
2665 /// Determine whether this is an Objective-C writeback conversion,
2666 /// used for parameter passing when performing automatic reference counting.
2667 ///
2668 /// \param FromType The type we're converting form.
2669 ///
2670 /// \param ToType The type we're converting to.
2671 ///
2672 /// \param ConvertedType The type that will be produced after applying
2673 /// this conversion.
2674 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2675                                      QualType &ConvertedType) {
2676   if (!getLangOpts().ObjCAutoRefCount ||
2677       Context.hasSameUnqualifiedType(FromType, ToType))
2678     return false;
2679 
2680   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2681   QualType ToPointee;
2682   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2683     ToPointee = ToPointer->getPointeeType();
2684   else
2685     return false;
2686 
2687   Qualifiers ToQuals = ToPointee.getQualifiers();
2688   if (!ToPointee->isObjCLifetimeType() ||
2689       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2690       !ToQuals.withoutObjCLifetime().empty())
2691     return false;
2692 
2693   // Argument must be a pointer to __strong to __weak.
2694   QualType FromPointee;
2695   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2696     FromPointee = FromPointer->getPointeeType();
2697   else
2698     return false;
2699 
2700   Qualifiers FromQuals = FromPointee.getQualifiers();
2701   if (!FromPointee->isObjCLifetimeType() ||
2702       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2703        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2704     return false;
2705 
2706   // Make sure that we have compatible qualifiers.
2707   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2708   if (!ToQuals.compatiblyIncludes(FromQuals))
2709     return false;
2710 
2711   // Remove qualifiers from the pointee type we're converting from; they
2712   // aren't used in the compatibility check belong, and we'll be adding back
2713   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2714   FromPointee = FromPointee.getUnqualifiedType();
2715 
2716   // The unqualified form of the pointee types must be compatible.
2717   ToPointee = ToPointee.getUnqualifiedType();
2718   bool IncompatibleObjC;
2719   if (Context.typesAreCompatible(FromPointee, ToPointee))
2720     FromPointee = ToPointee;
2721   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2722                                     IncompatibleObjC))
2723     return false;
2724 
2725   /// Construct the type we're converting to, which is a pointer to
2726   /// __autoreleasing pointee.
2727   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2728   ConvertedType = Context.getPointerType(FromPointee);
2729   return true;
2730 }
2731 
2732 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2733                                     QualType& ConvertedType) {
2734   QualType ToPointeeType;
2735   if (const BlockPointerType *ToBlockPtr =
2736         ToType->getAs<BlockPointerType>())
2737     ToPointeeType = ToBlockPtr->getPointeeType();
2738   else
2739     return false;
2740 
2741   QualType FromPointeeType;
2742   if (const BlockPointerType *FromBlockPtr =
2743       FromType->getAs<BlockPointerType>())
2744     FromPointeeType = FromBlockPtr->getPointeeType();
2745   else
2746     return false;
2747   // We have pointer to blocks, check whether the only
2748   // differences in the argument and result types are in Objective-C
2749   // pointer conversions. If so, we permit the conversion.
2750 
2751   const FunctionProtoType *FromFunctionType
2752     = FromPointeeType->getAs<FunctionProtoType>();
2753   const FunctionProtoType *ToFunctionType
2754     = ToPointeeType->getAs<FunctionProtoType>();
2755 
2756   if (!FromFunctionType || !ToFunctionType)
2757     return false;
2758 
2759   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2760     return true;
2761 
2762   // Perform the quick checks that will tell us whether these
2763   // function types are obviously different.
2764   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2765       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2766     return false;
2767 
2768   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2769   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2770   if (FromEInfo != ToEInfo)
2771     return false;
2772 
2773   bool IncompatibleObjC = false;
2774   if (Context.hasSameType(FromFunctionType->getReturnType(),
2775                           ToFunctionType->getReturnType())) {
2776     // Okay, the types match exactly. Nothing to do.
2777   } else {
2778     QualType RHS = FromFunctionType->getReturnType();
2779     QualType LHS = ToFunctionType->getReturnType();
2780     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2781         !RHS.hasQualifiers() && LHS.hasQualifiers())
2782        LHS = LHS.getUnqualifiedType();
2783 
2784      if (Context.hasSameType(RHS,LHS)) {
2785        // OK exact match.
2786      } else if (isObjCPointerConversion(RHS, LHS,
2787                                         ConvertedType, IncompatibleObjC)) {
2788      if (IncompatibleObjC)
2789        return false;
2790      // Okay, we have an Objective-C pointer conversion.
2791      }
2792      else
2793        return false;
2794    }
2795 
2796    // Check argument types.
2797    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2798         ArgIdx != NumArgs; ++ArgIdx) {
2799      IncompatibleObjC = false;
2800      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2801      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2802      if (Context.hasSameType(FromArgType, ToArgType)) {
2803        // Okay, the types match exactly. Nothing to do.
2804      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2805                                         ConvertedType, IncompatibleObjC)) {
2806        if (IncompatibleObjC)
2807          return false;
2808        // Okay, we have an Objective-C pointer conversion.
2809      } else
2810        // Argument types are too different. Abort.
2811        return false;
2812    }
2813 
2814    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2815    bool CanUseToFPT, CanUseFromFPT;
2816    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2817                                       CanUseToFPT, CanUseFromFPT,
2818                                       NewParamInfos))
2819      return false;
2820 
2821    ConvertedType = ToType;
2822    return true;
2823 }
2824 
2825 enum {
2826   ft_default,
2827   ft_different_class,
2828   ft_parameter_arity,
2829   ft_parameter_mismatch,
2830   ft_return_type,
2831   ft_qualifer_mismatch,
2832   ft_noexcept
2833 };
2834 
2835 /// Attempts to get the FunctionProtoType from a Type. Handles
2836 /// MemberFunctionPointers properly.
2837 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2838   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2839     return FPT;
2840 
2841   if (auto *MPT = FromType->getAs<MemberPointerType>())
2842     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2843 
2844   return nullptr;
2845 }
2846 
2847 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2848 /// function types.  Catches different number of parameter, mismatch in
2849 /// parameter types, and different return types.
2850 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2851                                       QualType FromType, QualType ToType) {
2852   // If either type is not valid, include no extra info.
2853   if (FromType.isNull() || ToType.isNull()) {
2854     PDiag << ft_default;
2855     return;
2856   }
2857 
2858   // Get the function type from the pointers.
2859   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2860     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2861                *ToMember = ToType->castAs<MemberPointerType>();
2862     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2863       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2864             << QualType(FromMember->getClass(), 0);
2865       return;
2866     }
2867     FromType = FromMember->getPointeeType();
2868     ToType = ToMember->getPointeeType();
2869   }
2870 
2871   if (FromType->isPointerType())
2872     FromType = FromType->getPointeeType();
2873   if (ToType->isPointerType())
2874     ToType = ToType->getPointeeType();
2875 
2876   // Remove references.
2877   FromType = FromType.getNonReferenceType();
2878   ToType = ToType.getNonReferenceType();
2879 
2880   // Don't print extra info for non-specialized template functions.
2881   if (FromType->isInstantiationDependentType() &&
2882       !FromType->getAs<TemplateSpecializationType>()) {
2883     PDiag << ft_default;
2884     return;
2885   }
2886 
2887   // No extra info for same types.
2888   if (Context.hasSameType(FromType, ToType)) {
2889     PDiag << ft_default;
2890     return;
2891   }
2892 
2893   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2894                           *ToFunction = tryGetFunctionProtoType(ToType);
2895 
2896   // Both types need to be function types.
2897   if (!FromFunction || !ToFunction) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2903     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2904           << FromFunction->getNumParams();
2905     return;
2906   }
2907 
2908   // Handle different parameter types.
2909   unsigned ArgPos;
2910   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2911     PDiag << ft_parameter_mismatch << ArgPos + 1
2912           << ToFunction->getParamType(ArgPos)
2913           << FromFunction->getParamType(ArgPos);
2914     return;
2915   }
2916 
2917   // Handle different return type.
2918   if (!Context.hasSameType(FromFunction->getReturnType(),
2919                            ToFunction->getReturnType())) {
2920     PDiag << ft_return_type << ToFunction->getReturnType()
2921           << FromFunction->getReturnType();
2922     return;
2923   }
2924 
2925   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2926     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2927           << FromFunction->getMethodQuals();
2928     return;
2929   }
2930 
2931   // Handle exception specification differences on canonical type (in C++17
2932   // onwards).
2933   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2934           ->isNothrow() !=
2935       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2936           ->isNothrow()) {
2937     PDiag << ft_noexcept;
2938     return;
2939   }
2940 
2941   // Unable to find a difference, so add no extra info.
2942   PDiag << ft_default;
2943 }
2944 
2945 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2946 /// for equality of their argument types. Caller has already checked that
2947 /// they have same number of arguments.  If the parameters are different,
2948 /// ArgPos will have the parameter index of the first different parameter.
2949 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2950                                       const FunctionProtoType *NewType,
2951                                       unsigned *ArgPos) {
2952   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2953                                               N = NewType->param_type_begin(),
2954                                               E = OldType->param_type_end();
2955        O && (O != E); ++O, ++N) {
2956     // Ignore address spaces in pointee type. This is to disallow overloading
2957     // on __ptr32/__ptr64 address spaces.
2958     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2959     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2960 
2961     if (!Context.hasSameType(Old, New)) {
2962       if (ArgPos)
2963         *ArgPos = O - OldType->param_type_begin();
2964       return false;
2965     }
2966   }
2967   return true;
2968 }
2969 
2970 /// CheckPointerConversion - Check the pointer conversion from the
2971 /// expression From to the type ToType. This routine checks for
2972 /// ambiguous or inaccessible derived-to-base pointer
2973 /// conversions for which IsPointerConversion has already returned
2974 /// true. It returns true and produces a diagnostic if there was an
2975 /// error, or returns false otherwise.
2976 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2977                                   CastKind &Kind,
2978                                   CXXCastPath& BasePath,
2979                                   bool IgnoreBaseAccess,
2980                                   bool Diagnose) {
2981   QualType FromType = From->getType();
2982   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2983 
2984   Kind = CK_BitCast;
2985 
2986   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2987       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2988           Expr::NPCK_ZeroExpression) {
2989     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2990       DiagRuntimeBehavior(From->getExprLoc(), From,
2991                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2992                             << ToType << From->getSourceRange());
2993     else if (!isUnevaluatedContext())
2994       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2995         << ToType << From->getSourceRange();
2996   }
2997   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2998     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2999       QualType FromPointeeType = FromPtrType->getPointeeType(),
3000                ToPointeeType   = ToPtrType->getPointeeType();
3001 
3002       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3003           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3004         // We must have a derived-to-base conversion. Check an
3005         // ambiguous or inaccessible conversion.
3006         unsigned InaccessibleID = 0;
3007         unsigned AmbigiousID = 0;
3008         if (Diagnose) {
3009           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3010           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3011         }
3012         if (CheckDerivedToBaseConversion(
3013                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3014                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3015                 &BasePath, IgnoreBaseAccess))
3016           return true;
3017 
3018         // The conversion was successful.
3019         Kind = CK_DerivedToBase;
3020       }
3021 
3022       if (Diagnose && !IsCStyleOrFunctionalCast &&
3023           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3024         assert(getLangOpts().MSVCCompat &&
3025                "this should only be possible with MSVCCompat!");
3026         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3027             << From->getSourceRange();
3028       }
3029     }
3030   } else if (const ObjCObjectPointerType *ToPtrType =
3031                ToType->getAs<ObjCObjectPointerType>()) {
3032     if (const ObjCObjectPointerType *FromPtrType =
3033           FromType->getAs<ObjCObjectPointerType>()) {
3034       // Objective-C++ conversions are always okay.
3035       // FIXME: We should have a different class of conversions for the
3036       // Objective-C++ implicit conversions.
3037       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3038         return false;
3039     } else if (FromType->isBlockPointerType()) {
3040       Kind = CK_BlockPointerToObjCPointerCast;
3041     } else {
3042       Kind = CK_CPointerToObjCPointerCast;
3043     }
3044   } else if (ToType->isBlockPointerType()) {
3045     if (!FromType->isBlockPointerType())
3046       Kind = CK_AnyPointerToBlockPointerCast;
3047   }
3048 
3049   // We shouldn't fall into this case unless it's valid for other
3050   // reasons.
3051   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3052     Kind = CK_NullToPointer;
3053 
3054   return false;
3055 }
3056 
3057 /// IsMemberPointerConversion - Determines whether the conversion of the
3058 /// expression From, which has the (possibly adjusted) type FromType, can be
3059 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3060 /// If so, returns true and places the converted type (that might differ from
3061 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3062 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3063                                      QualType ToType,
3064                                      bool InOverloadResolution,
3065                                      QualType &ConvertedType) {
3066   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3067   if (!ToTypePtr)
3068     return false;
3069 
3070   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3071   if (From->isNullPointerConstant(Context,
3072                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3073                                         : Expr::NPC_ValueDependentIsNull)) {
3074     ConvertedType = ToType;
3075     return true;
3076   }
3077 
3078   // Otherwise, both types have to be member pointers.
3079   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3080   if (!FromTypePtr)
3081     return false;
3082 
3083   // A pointer to member of B can be converted to a pointer to member of D,
3084   // where D is derived from B (C++ 4.11p2).
3085   QualType FromClass(FromTypePtr->getClass(), 0);
3086   QualType ToClass(ToTypePtr->getClass(), 0);
3087 
3088   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3089       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3090     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3091                                                  ToClass.getTypePtr());
3092     return true;
3093   }
3094 
3095   return false;
3096 }
3097 
3098 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3099 /// expression From to the type ToType. This routine checks for ambiguous or
3100 /// virtual or inaccessible base-to-derived member pointer conversions
3101 /// for which IsMemberPointerConversion has already returned true. It returns
3102 /// true and produces a diagnostic if there was an error, or returns false
3103 /// otherwise.
3104 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3105                                         CastKind &Kind,
3106                                         CXXCastPath &BasePath,
3107                                         bool IgnoreBaseAccess) {
3108   QualType FromType = From->getType();
3109   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3110   if (!FromPtrType) {
3111     // This must be a null pointer to member pointer conversion
3112     assert(From->isNullPointerConstant(Context,
3113                                        Expr::NPC_ValueDependentIsNull) &&
3114            "Expr must be null pointer constant!");
3115     Kind = CK_NullToMemberPointer;
3116     return false;
3117   }
3118 
3119   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3120   assert(ToPtrType && "No member pointer cast has a target type "
3121                       "that is not a member pointer.");
3122 
3123   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3124   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3125 
3126   // FIXME: What about dependent types?
3127   assert(FromClass->isRecordType() && "Pointer into non-class.");
3128   assert(ToClass->isRecordType() && "Pointer into non-class.");
3129 
3130   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131                      /*DetectVirtual=*/true);
3132   bool DerivationOkay =
3133       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3134   assert(DerivationOkay &&
3135          "Should not have been called if derivation isn't OK.");
3136   (void)DerivationOkay;
3137 
3138   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3139                                   getUnqualifiedType())) {
3140     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3141     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3142       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3143     return true;
3144   }
3145 
3146   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3147     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3148       << FromClass << ToClass << QualType(VBase, 0)
3149       << From->getSourceRange();
3150     return true;
3151   }
3152 
3153   if (!IgnoreBaseAccess)
3154     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3155                          Paths.front(),
3156                          diag::err_downcast_from_inaccessible_base);
3157 
3158   // Must be a base to derived member conversion.
3159   BuildBasePathArray(Paths, BasePath);
3160   Kind = CK_BaseToDerivedMemberPointer;
3161   return false;
3162 }
3163 
3164 /// Determine whether the lifetime conversion between the two given
3165 /// qualifiers sets is nontrivial.
3166 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3167                                                Qualifiers ToQuals) {
3168   // Converting anything to const __unsafe_unretained is trivial.
3169   if (ToQuals.hasConst() &&
3170       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3171     return false;
3172 
3173   return true;
3174 }
3175 
3176 /// Perform a single iteration of the loop for checking if a qualification
3177 /// conversion is valid.
3178 ///
3179 /// Specifically, check whether any change between the qualifiers of \p
3180 /// FromType and \p ToType is permissible, given knowledge about whether every
3181 /// outer layer is const-qualified.
3182 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3183                                           bool CStyle,
3184                                           bool &PreviousToQualsIncludeConst,
3185                                           bool &ObjCLifetimeConversion) {
3186   Qualifiers FromQuals = FromType.getQualifiers();
3187   Qualifiers ToQuals = ToType.getQualifiers();
3188 
3189   // Ignore __unaligned qualifier if this type is void.
3190   if (ToType.getUnqualifiedType()->isVoidType())
3191     FromQuals.removeUnaligned();
3192 
3193   // Objective-C ARC:
3194   //   Check Objective-C lifetime conversions.
3195   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3196     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3197       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3198         ObjCLifetimeConversion = true;
3199       FromQuals.removeObjCLifetime();
3200       ToQuals.removeObjCLifetime();
3201     } else {
3202       // Qualification conversions cannot cast between different
3203       // Objective-C lifetime qualifiers.
3204       return false;
3205     }
3206   }
3207 
3208   // Allow addition/removal of GC attributes but not changing GC attributes.
3209   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3210       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3211     FromQuals.removeObjCGCAttr();
3212     ToQuals.removeObjCGCAttr();
3213   }
3214 
3215   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3216   //      2,j, and similarly for volatile.
3217   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3218     return false;
3219 
3220   // For a C-style cast, just require the address spaces to overlap.
3221   // FIXME: Does "superset" also imply the representation of a pointer is the
3222   // same? We're assuming that it does here and in compatiblyIncludes.
3223   if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3224       !FromQuals.isAddressSpaceSupersetOf(ToQuals))
3225     return false;
3226 
3227   //   -- if the cv 1,j and cv 2,j are different, then const is in
3228   //      every cv for 0 < k < j.
3229   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3230       !PreviousToQualsIncludeConst)
3231     return false;
3232 
3233   // Keep track of whether all prior cv-qualifiers in the "to" type
3234   // include const.
3235   PreviousToQualsIncludeConst =
3236       PreviousToQualsIncludeConst && ToQuals.hasConst();
3237   return true;
3238 }
3239 
3240 /// IsQualificationConversion - Determines whether the conversion from
3241 /// an rvalue of type FromType to ToType is a qualification conversion
3242 /// (C++ 4.4).
3243 ///
3244 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3245 /// when the qualification conversion involves a change in the Objective-C
3246 /// object lifetime.
3247 bool
3248 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3249                                 bool CStyle, bool &ObjCLifetimeConversion) {
3250   FromType = Context.getCanonicalType(FromType);
3251   ToType = Context.getCanonicalType(ToType);
3252   ObjCLifetimeConversion = false;
3253 
3254   // If FromType and ToType are the same type, this is not a
3255   // qualification conversion.
3256   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3257     return false;
3258 
3259   // (C++ 4.4p4):
3260   //   A conversion can add cv-qualifiers at levels other than the first
3261   //   in multi-level pointers, subject to the following rules: [...]
3262   bool PreviousToQualsIncludeConst = true;
3263   bool UnwrappedAnyPointer = false;
3264   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3265     if (!isQualificationConversionStep(FromType, ToType, CStyle,
3266                                        PreviousToQualsIncludeConst,
3267                                        ObjCLifetimeConversion))
3268       return false;
3269     UnwrappedAnyPointer = true;
3270   }
3271 
3272   // We are left with FromType and ToType being the pointee types
3273   // after unwrapping the original FromType and ToType the same number
3274   // of times. If we unwrapped any pointers, and if FromType and
3275   // ToType have the same unqualified type (since we checked
3276   // qualifiers above), then this is a qualification conversion.
3277   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3278 }
3279 
3280 /// - Determine whether this is a conversion from a scalar type to an
3281 /// atomic type.
3282 ///
3283 /// If successful, updates \c SCS's second and third steps in the conversion
3284 /// sequence to finish the conversion.
3285 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3286                                 bool InOverloadResolution,
3287                                 StandardConversionSequence &SCS,
3288                                 bool CStyle) {
3289   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3290   if (!ToAtomic)
3291     return false;
3292 
3293   StandardConversionSequence InnerSCS;
3294   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3295                             InOverloadResolution, InnerSCS,
3296                             CStyle, /*AllowObjCWritebackConversion=*/false))
3297     return false;
3298 
3299   SCS.Second = InnerSCS.Second;
3300   SCS.setToType(1, InnerSCS.getToType(1));
3301   SCS.Third = InnerSCS.Third;
3302   SCS.QualificationIncludesObjCLifetime
3303     = InnerSCS.QualificationIncludesObjCLifetime;
3304   SCS.setToType(2, InnerSCS.getToType(2));
3305   return true;
3306 }
3307 
3308 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3309                                               CXXConstructorDecl *Constructor,
3310                                               QualType Type) {
3311   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3312   if (CtorType->getNumParams() > 0) {
3313     QualType FirstArg = CtorType->getParamType(0);
3314     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3315       return true;
3316   }
3317   return false;
3318 }
3319 
3320 static OverloadingResult
3321 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3322                                        CXXRecordDecl *To,
3323                                        UserDefinedConversionSequence &User,
3324                                        OverloadCandidateSet &CandidateSet,
3325                                        bool AllowExplicit) {
3326   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3327   for (auto *D : S.LookupConstructors(To)) {
3328     auto Info = getConstructorInfo(D);
3329     if (!Info)
3330       continue;
3331 
3332     bool Usable = !Info.Constructor->isInvalidDecl() &&
3333                   S.isInitListConstructor(Info.Constructor);
3334     if (Usable) {
3335       // If the first argument is (a reference to) the target type,
3336       // suppress conversions.
3337       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3338           S.Context, Info.Constructor, ToType);
3339       if (Info.ConstructorTmpl)
3340         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3341                                        /*ExplicitArgs*/ nullptr, From,
3342                                        CandidateSet, SuppressUserConversions,
3343                                        /*PartialOverloading*/ false,
3344                                        AllowExplicit);
3345       else
3346         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3347                                CandidateSet, SuppressUserConversions,
3348                                /*PartialOverloading*/ false, AllowExplicit);
3349     }
3350   }
3351 
3352   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3353 
3354   OverloadCandidateSet::iterator Best;
3355   switch (auto Result =
3356               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3357   case OR_Deleted:
3358   case OR_Success: {
3359     // Record the standard conversion we used and the conversion function.
3360     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3361     QualType ThisType = Constructor->getThisType();
3362     // Initializer lists don't have conversions as such.
3363     User.Before.setAsIdentityConversion();
3364     User.HadMultipleCandidates = HadMultipleCandidates;
3365     User.ConversionFunction = Constructor;
3366     User.FoundConversionFunction = Best->FoundDecl;
3367     User.After.setAsIdentityConversion();
3368     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3369     User.After.setAllToTypes(ToType);
3370     return Result;
3371   }
3372 
3373   case OR_No_Viable_Function:
3374     return OR_No_Viable_Function;
3375   case OR_Ambiguous:
3376     return OR_Ambiguous;
3377   }
3378 
3379   llvm_unreachable("Invalid OverloadResult!");
3380 }
3381 
3382 /// Determines whether there is a user-defined conversion sequence
3383 /// (C++ [over.ics.user]) that converts expression From to the type
3384 /// ToType. If such a conversion exists, User will contain the
3385 /// user-defined conversion sequence that performs such a conversion
3386 /// and this routine will return true. Otherwise, this routine returns
3387 /// false and User is unspecified.
3388 ///
3389 /// \param AllowExplicit  true if the conversion should consider C++0x
3390 /// "explicit" conversion functions as well as non-explicit conversion
3391 /// functions (C++0x [class.conv.fct]p2).
3392 ///
3393 /// \param AllowObjCConversionOnExplicit true if the conversion should
3394 /// allow an extra Objective-C pointer conversion on uses of explicit
3395 /// constructors. Requires \c AllowExplicit to also be set.
3396 static OverloadingResult
3397 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3398                         UserDefinedConversionSequence &User,
3399                         OverloadCandidateSet &CandidateSet,
3400                         AllowedExplicit AllowExplicit,
3401                         bool AllowObjCConversionOnExplicit) {
3402   assert(AllowExplicit != AllowedExplicit::None ||
3403          !AllowObjCConversionOnExplicit);
3404   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3405 
3406   // Whether we will only visit constructors.
3407   bool ConstructorsOnly = false;
3408 
3409   // If the type we are conversion to is a class type, enumerate its
3410   // constructors.
3411   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3412     // C++ [over.match.ctor]p1:
3413     //   When objects of class type are direct-initialized (8.5), or
3414     //   copy-initialized from an expression of the same or a
3415     //   derived class type (8.5), overload resolution selects the
3416     //   constructor. [...] For copy-initialization, the candidate
3417     //   functions are all the converting constructors (12.3.1) of
3418     //   that class. The argument list is the expression-list within
3419     //   the parentheses of the initializer.
3420     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3421         (From->getType()->getAs<RecordType>() &&
3422          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3423       ConstructorsOnly = true;
3424 
3425     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3426       // We're not going to find any constructors.
3427     } else if (CXXRecordDecl *ToRecordDecl
3428                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3429 
3430       Expr **Args = &From;
3431       unsigned NumArgs = 1;
3432       bool ListInitializing = false;
3433       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3434         // But first, see if there is an init-list-constructor that will work.
3435         OverloadingResult Result = IsInitializerListConstructorConversion(
3436             S, From, ToType, ToRecordDecl, User, CandidateSet,
3437             AllowExplicit == AllowedExplicit::All);
3438         if (Result != OR_No_Viable_Function)
3439           return Result;
3440         // Never mind.
3441         CandidateSet.clear(
3442             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3443 
3444         // If we're list-initializing, we pass the individual elements as
3445         // arguments, not the entire list.
3446         Args = InitList->getInits();
3447         NumArgs = InitList->getNumInits();
3448         ListInitializing = true;
3449       }
3450 
3451       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3452         auto Info = getConstructorInfo(D);
3453         if (!Info)
3454           continue;
3455 
3456         bool Usable = !Info.Constructor->isInvalidDecl();
3457         if (!ListInitializing)
3458           Usable = Usable && Info.Constructor->isConvertingConstructor(
3459                                  /*AllowExplicit*/ true);
3460         if (Usable) {
3461           bool SuppressUserConversions = !ConstructorsOnly;
3462           if (SuppressUserConversions && ListInitializing) {
3463             SuppressUserConversions = false;
3464             if (NumArgs == 1) {
3465               // If the first argument is (a reference to) the target type,
3466               // suppress conversions.
3467               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3468                   S.Context, Info.Constructor, ToType);
3469             }
3470           }
3471           if (Info.ConstructorTmpl)
3472             S.AddTemplateOverloadCandidate(
3473                 Info.ConstructorTmpl, Info.FoundDecl,
3474                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3475                 CandidateSet, SuppressUserConversions,
3476                 /*PartialOverloading*/ false,
3477                 AllowExplicit == AllowedExplicit::All);
3478           else
3479             // Allow one user-defined conversion when user specifies a
3480             // From->ToType conversion via an static cast (c-style, etc).
3481             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3482                                    llvm::makeArrayRef(Args, NumArgs),
3483                                    CandidateSet, SuppressUserConversions,
3484                                    /*PartialOverloading*/ false,
3485                                    AllowExplicit == AllowedExplicit::All);
3486         }
3487       }
3488     }
3489   }
3490 
3491   // Enumerate conversion functions, if we're allowed to.
3492   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3493   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3494     // No conversion functions from incomplete types.
3495   } else if (const RecordType *FromRecordType =
3496                  From->getType()->getAs<RecordType>()) {
3497     if (CXXRecordDecl *FromRecordDecl
3498          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3499       // Add all of the conversion functions as candidates.
3500       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3501       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3502         DeclAccessPair FoundDecl = I.getPair();
3503         NamedDecl *D = FoundDecl.getDecl();
3504         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3505         if (isa<UsingShadowDecl>(D))
3506           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3507 
3508         CXXConversionDecl *Conv;
3509         FunctionTemplateDecl *ConvTemplate;
3510         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3511           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3512         else
3513           Conv = cast<CXXConversionDecl>(D);
3514 
3515         if (ConvTemplate)
3516           S.AddTemplateConversionCandidate(
3517               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3518               CandidateSet, AllowObjCConversionOnExplicit,
3519               AllowExplicit != AllowedExplicit::None);
3520         else
3521           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3522                                    CandidateSet, AllowObjCConversionOnExplicit,
3523                                    AllowExplicit != AllowedExplicit::None);
3524       }
3525     }
3526   }
3527 
3528   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3529 
3530   OverloadCandidateSet::iterator Best;
3531   switch (auto Result =
3532               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3533   case OR_Success:
3534   case OR_Deleted:
3535     // Record the standard conversion we used and the conversion function.
3536     if (CXXConstructorDecl *Constructor
3537           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3538       // C++ [over.ics.user]p1:
3539       //   If the user-defined conversion is specified by a
3540       //   constructor (12.3.1), the initial standard conversion
3541       //   sequence converts the source type to the type required by
3542       //   the argument of the constructor.
3543       //
3544       QualType ThisType = Constructor->getThisType();
3545       if (isa<InitListExpr>(From)) {
3546         // Initializer lists don't have conversions as such.
3547         User.Before.setAsIdentityConversion();
3548       } else {
3549         if (Best->Conversions[0].isEllipsis())
3550           User.EllipsisConversion = true;
3551         else {
3552           User.Before = Best->Conversions[0].Standard;
3553           User.EllipsisConversion = false;
3554         }
3555       }
3556       User.HadMultipleCandidates = HadMultipleCandidates;
3557       User.ConversionFunction = Constructor;
3558       User.FoundConversionFunction = Best->FoundDecl;
3559       User.After.setAsIdentityConversion();
3560       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3561       User.After.setAllToTypes(ToType);
3562       return Result;
3563     }
3564     if (CXXConversionDecl *Conversion
3565                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3566       // C++ [over.ics.user]p1:
3567       //
3568       //   [...] If the user-defined conversion is specified by a
3569       //   conversion function (12.3.2), the initial standard
3570       //   conversion sequence converts the source type to the
3571       //   implicit object parameter of the conversion function.
3572       User.Before = Best->Conversions[0].Standard;
3573       User.HadMultipleCandidates = HadMultipleCandidates;
3574       User.ConversionFunction = Conversion;
3575       User.FoundConversionFunction = Best->FoundDecl;
3576       User.EllipsisConversion = false;
3577 
3578       // C++ [over.ics.user]p2:
3579       //   The second standard conversion sequence converts the
3580       //   result of the user-defined conversion to the target type
3581       //   for the sequence. Since an implicit conversion sequence
3582       //   is an initialization, the special rules for
3583       //   initialization by user-defined conversion apply when
3584       //   selecting the best user-defined conversion for a
3585       //   user-defined conversion sequence (see 13.3.3 and
3586       //   13.3.3.1).
3587       User.After = Best->FinalConversion;
3588       return Result;
3589     }
3590     llvm_unreachable("Not a constructor or conversion function?");
3591 
3592   case OR_No_Viable_Function:
3593     return OR_No_Viable_Function;
3594 
3595   case OR_Ambiguous:
3596     return OR_Ambiguous;
3597   }
3598 
3599   llvm_unreachable("Invalid OverloadResult!");
3600 }
3601 
3602 bool
3603 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3604   ImplicitConversionSequence ICS;
3605   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3606                                     OverloadCandidateSet::CSK_Normal);
3607   OverloadingResult OvResult =
3608     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3609                             CandidateSet, AllowedExplicit::None, false);
3610 
3611   if (!(OvResult == OR_Ambiguous ||
3612         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3613     return false;
3614 
3615   auto Cands = CandidateSet.CompleteCandidates(
3616       *this,
3617       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3618       From);
3619   if (OvResult == OR_Ambiguous)
3620     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3621         << From->getType() << ToType << From->getSourceRange();
3622   else { // OR_No_Viable_Function && !CandidateSet.empty()
3623     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3624                              diag::err_typecheck_nonviable_condition_incomplete,
3625                              From->getType(), From->getSourceRange()))
3626       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3627           << false << From->getType() << From->getSourceRange() << ToType;
3628   }
3629 
3630   CandidateSet.NoteCandidates(
3631                               *this, From, Cands);
3632   return true;
3633 }
3634 
3635 /// Compare the user-defined conversion functions or constructors
3636 /// of two user-defined conversion sequences to determine whether any ordering
3637 /// is possible.
3638 static ImplicitConversionSequence::CompareKind
3639 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3640                            FunctionDecl *Function2) {
3641   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3642     return ImplicitConversionSequence::Indistinguishable;
3643 
3644   // Objective-C++:
3645   //   If both conversion functions are implicitly-declared conversions from
3646   //   a lambda closure type to a function pointer and a block pointer,
3647   //   respectively, always prefer the conversion to a function pointer,
3648   //   because the function pointer is more lightweight and is more likely
3649   //   to keep code working.
3650   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3651   if (!Conv1)
3652     return ImplicitConversionSequence::Indistinguishable;
3653 
3654   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3655   if (!Conv2)
3656     return ImplicitConversionSequence::Indistinguishable;
3657 
3658   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3659     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3660     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3661     if (Block1 != Block2)
3662       return Block1 ? ImplicitConversionSequence::Worse
3663                     : ImplicitConversionSequence::Better;
3664   }
3665 
3666   return ImplicitConversionSequence::Indistinguishable;
3667 }
3668 
3669 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3670     const ImplicitConversionSequence &ICS) {
3671   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3672          (ICS.isUserDefined() &&
3673           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3674 }
3675 
3676 /// CompareImplicitConversionSequences - Compare two implicit
3677 /// conversion sequences to determine whether one is better than the
3678 /// other or if they are indistinguishable (C++ 13.3.3.2).
3679 static ImplicitConversionSequence::CompareKind
3680 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3681                                    const ImplicitConversionSequence& ICS1,
3682                                    const ImplicitConversionSequence& ICS2)
3683 {
3684   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3685   // conversion sequences (as defined in 13.3.3.1)
3686   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3687   //      conversion sequence than a user-defined conversion sequence or
3688   //      an ellipsis conversion sequence, and
3689   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3690   //      conversion sequence than an ellipsis conversion sequence
3691   //      (13.3.3.1.3).
3692   //
3693   // C++0x [over.best.ics]p10:
3694   //   For the purpose of ranking implicit conversion sequences as
3695   //   described in 13.3.3.2, the ambiguous conversion sequence is
3696   //   treated as a user-defined sequence that is indistinguishable
3697   //   from any other user-defined conversion sequence.
3698 
3699   // String literal to 'char *' conversion has been deprecated in C++03. It has
3700   // been removed from C++11. We still accept this conversion, if it happens at
3701   // the best viable function. Otherwise, this conversion is considered worse
3702   // than ellipsis conversion. Consider this as an extension; this is not in the
3703   // standard. For example:
3704   //
3705   // int &f(...);    // #1
3706   // void f(char*);  // #2
3707   // void g() { int &r = f("foo"); }
3708   //
3709   // In C++03, we pick #2 as the best viable function.
3710   // In C++11, we pick #1 as the best viable function, because ellipsis
3711   // conversion is better than string-literal to char* conversion (since there
3712   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3713   // convert arguments, #2 would be the best viable function in C++11.
3714   // If the best viable function has this conversion, a warning will be issued
3715   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3716 
3717   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3718       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3719       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3720     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3721                ? ImplicitConversionSequence::Worse
3722                : ImplicitConversionSequence::Better;
3723 
3724   if (ICS1.getKindRank() < ICS2.getKindRank())
3725     return ImplicitConversionSequence::Better;
3726   if (ICS2.getKindRank() < ICS1.getKindRank())
3727     return ImplicitConversionSequence::Worse;
3728 
3729   // The following checks require both conversion sequences to be of
3730   // the same kind.
3731   if (ICS1.getKind() != ICS2.getKind())
3732     return ImplicitConversionSequence::Indistinguishable;
3733 
3734   ImplicitConversionSequence::CompareKind Result =
3735       ImplicitConversionSequence::Indistinguishable;
3736 
3737   // Two implicit conversion sequences of the same form are
3738   // indistinguishable conversion sequences unless one of the
3739   // following rules apply: (C++ 13.3.3.2p3):
3740 
3741   // List-initialization sequence L1 is a better conversion sequence than
3742   // list-initialization sequence L2 if:
3743   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3744   //   if not that,
3745   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3746   //   and N1 is smaller than N2.,
3747   // even if one of the other rules in this paragraph would otherwise apply.
3748   if (!ICS1.isBad()) {
3749     if (ICS1.isStdInitializerListElement() &&
3750         !ICS2.isStdInitializerListElement())
3751       return ImplicitConversionSequence::Better;
3752     if (!ICS1.isStdInitializerListElement() &&
3753         ICS2.isStdInitializerListElement())
3754       return ImplicitConversionSequence::Worse;
3755   }
3756 
3757   if (ICS1.isStandard())
3758     // Standard conversion sequence S1 is a better conversion sequence than
3759     // standard conversion sequence S2 if [...]
3760     Result = CompareStandardConversionSequences(S, Loc,
3761                                                 ICS1.Standard, ICS2.Standard);
3762   else if (ICS1.isUserDefined()) {
3763     // User-defined conversion sequence U1 is a better conversion
3764     // sequence than another user-defined conversion sequence U2 if
3765     // they contain the same user-defined conversion function or
3766     // constructor and if the second standard conversion sequence of
3767     // U1 is better than the second standard conversion sequence of
3768     // U2 (C++ 13.3.3.2p3).
3769     if (ICS1.UserDefined.ConversionFunction ==
3770           ICS2.UserDefined.ConversionFunction)
3771       Result = CompareStandardConversionSequences(S, Loc,
3772                                                   ICS1.UserDefined.After,
3773                                                   ICS2.UserDefined.After);
3774     else
3775       Result = compareConversionFunctions(S,
3776                                           ICS1.UserDefined.ConversionFunction,
3777                                           ICS2.UserDefined.ConversionFunction);
3778   }
3779 
3780   return Result;
3781 }
3782 
3783 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3784 // determine if one is a proper subset of the other.
3785 static ImplicitConversionSequence::CompareKind
3786 compareStandardConversionSubsets(ASTContext &Context,
3787                                  const StandardConversionSequence& SCS1,
3788                                  const StandardConversionSequence& SCS2) {
3789   ImplicitConversionSequence::CompareKind Result
3790     = ImplicitConversionSequence::Indistinguishable;
3791 
3792   // the identity conversion sequence is considered to be a subsequence of
3793   // any non-identity conversion sequence
3794   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3795     return ImplicitConversionSequence::Better;
3796   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3797     return ImplicitConversionSequence::Worse;
3798 
3799   if (SCS1.Second != SCS2.Second) {
3800     if (SCS1.Second == ICK_Identity)
3801       Result = ImplicitConversionSequence::Better;
3802     else if (SCS2.Second == ICK_Identity)
3803       Result = ImplicitConversionSequence::Worse;
3804     else
3805       return ImplicitConversionSequence::Indistinguishable;
3806   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3807     return ImplicitConversionSequence::Indistinguishable;
3808 
3809   if (SCS1.Third == SCS2.Third) {
3810     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3811                              : ImplicitConversionSequence::Indistinguishable;
3812   }
3813 
3814   if (SCS1.Third == ICK_Identity)
3815     return Result == ImplicitConversionSequence::Worse
3816              ? ImplicitConversionSequence::Indistinguishable
3817              : ImplicitConversionSequence::Better;
3818 
3819   if (SCS2.Third == ICK_Identity)
3820     return Result == ImplicitConversionSequence::Better
3821              ? ImplicitConversionSequence::Indistinguishable
3822              : ImplicitConversionSequence::Worse;
3823 
3824   return ImplicitConversionSequence::Indistinguishable;
3825 }
3826 
3827 /// Determine whether one of the given reference bindings is better
3828 /// than the other based on what kind of bindings they are.
3829 static bool
3830 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3831                              const StandardConversionSequence &SCS2) {
3832   // C++0x [over.ics.rank]p3b4:
3833   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3834   //      implicit object parameter of a non-static member function declared
3835   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3836   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3837   //      lvalue reference to a function lvalue and S2 binds an rvalue
3838   //      reference*.
3839   //
3840   // FIXME: Rvalue references. We're going rogue with the above edits,
3841   // because the semantics in the current C++0x working paper (N3225 at the
3842   // time of this writing) break the standard definition of std::forward
3843   // and std::reference_wrapper when dealing with references to functions.
3844   // Proposed wording changes submitted to CWG for consideration.
3845   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3846       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3847     return false;
3848 
3849   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3850           SCS2.IsLvalueReference) ||
3851          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3852           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3853 }
3854 
3855 enum class FixedEnumPromotion {
3856   None,
3857   ToUnderlyingType,
3858   ToPromotedUnderlyingType
3859 };
3860 
3861 /// Returns kind of fixed enum promotion the \a SCS uses.
3862 static FixedEnumPromotion
3863 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3864 
3865   if (SCS.Second != ICK_Integral_Promotion)
3866     return FixedEnumPromotion::None;
3867 
3868   QualType FromType = SCS.getFromType();
3869   if (!FromType->isEnumeralType())
3870     return FixedEnumPromotion::None;
3871 
3872   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3873   if (!Enum->isFixed())
3874     return FixedEnumPromotion::None;
3875 
3876   QualType UnderlyingType = Enum->getIntegerType();
3877   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3878     return FixedEnumPromotion::ToUnderlyingType;
3879 
3880   return FixedEnumPromotion::ToPromotedUnderlyingType;
3881 }
3882 
3883 /// CompareStandardConversionSequences - Compare two standard
3884 /// conversion sequences to determine whether one is better than the
3885 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3886 static ImplicitConversionSequence::CompareKind
3887 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3888                                    const StandardConversionSequence& SCS1,
3889                                    const StandardConversionSequence& SCS2)
3890 {
3891   // Standard conversion sequence S1 is a better conversion sequence
3892   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3893 
3894   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3895   //     sequences in the canonical form defined by 13.3.3.1.1,
3896   //     excluding any Lvalue Transformation; the identity conversion
3897   //     sequence is considered to be a subsequence of any
3898   //     non-identity conversion sequence) or, if not that,
3899   if (ImplicitConversionSequence::CompareKind CK
3900         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3901     return CK;
3902 
3903   //  -- the rank of S1 is better than the rank of S2 (by the rules
3904   //     defined below), or, if not that,
3905   ImplicitConversionRank Rank1 = SCS1.getRank();
3906   ImplicitConversionRank Rank2 = SCS2.getRank();
3907   if (Rank1 < Rank2)
3908     return ImplicitConversionSequence::Better;
3909   else if (Rank2 < Rank1)
3910     return ImplicitConversionSequence::Worse;
3911 
3912   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3913   // are indistinguishable unless one of the following rules
3914   // applies:
3915 
3916   //   A conversion that is not a conversion of a pointer, or
3917   //   pointer to member, to bool is better than another conversion
3918   //   that is such a conversion.
3919   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3920     return SCS2.isPointerConversionToBool()
3921              ? ImplicitConversionSequence::Better
3922              : ImplicitConversionSequence::Worse;
3923 
3924   // C++14 [over.ics.rank]p4b2:
3925   // This is retroactively applied to C++11 by CWG 1601.
3926   //
3927   //   A conversion that promotes an enumeration whose underlying type is fixed
3928   //   to its underlying type is better than one that promotes to the promoted
3929   //   underlying type, if the two are different.
3930   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3931   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3932   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3933       FEP1 != FEP2)
3934     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3935                ? ImplicitConversionSequence::Better
3936                : ImplicitConversionSequence::Worse;
3937 
3938   // C++ [over.ics.rank]p4b2:
3939   //
3940   //   If class B is derived directly or indirectly from class A,
3941   //   conversion of B* to A* is better than conversion of B* to
3942   //   void*, and conversion of A* to void* is better than conversion
3943   //   of B* to void*.
3944   bool SCS1ConvertsToVoid
3945     = SCS1.isPointerConversionToVoidPointer(S.Context);
3946   bool SCS2ConvertsToVoid
3947     = SCS2.isPointerConversionToVoidPointer(S.Context);
3948   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3949     // Exactly one of the conversion sequences is a conversion to
3950     // a void pointer; it's the worse conversion.
3951     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3952                               : ImplicitConversionSequence::Worse;
3953   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3954     // Neither conversion sequence converts to a void pointer; compare
3955     // their derived-to-base conversions.
3956     if (ImplicitConversionSequence::CompareKind DerivedCK
3957           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3958       return DerivedCK;
3959   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3960              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3961     // Both conversion sequences are conversions to void
3962     // pointers. Compare the source types to determine if there's an
3963     // inheritance relationship in their sources.
3964     QualType FromType1 = SCS1.getFromType();
3965     QualType FromType2 = SCS2.getFromType();
3966 
3967     // Adjust the types we're converting from via the array-to-pointer
3968     // conversion, if we need to.
3969     if (SCS1.First == ICK_Array_To_Pointer)
3970       FromType1 = S.Context.getArrayDecayedType(FromType1);
3971     if (SCS2.First == ICK_Array_To_Pointer)
3972       FromType2 = S.Context.getArrayDecayedType(FromType2);
3973 
3974     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3975     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3976 
3977     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3978       return ImplicitConversionSequence::Better;
3979     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3980       return ImplicitConversionSequence::Worse;
3981 
3982     // Objective-C++: If one interface is more specific than the
3983     // other, it is the better one.
3984     const ObjCObjectPointerType* FromObjCPtr1
3985       = FromType1->getAs<ObjCObjectPointerType>();
3986     const ObjCObjectPointerType* FromObjCPtr2
3987       = FromType2->getAs<ObjCObjectPointerType>();
3988     if (FromObjCPtr1 && FromObjCPtr2) {
3989       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3990                                                           FromObjCPtr2);
3991       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3992                                                            FromObjCPtr1);
3993       if (AssignLeft != AssignRight) {
3994         return AssignLeft? ImplicitConversionSequence::Better
3995                          : ImplicitConversionSequence::Worse;
3996       }
3997     }
3998   }
3999 
4000   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4001     // Check for a better reference binding based on the kind of bindings.
4002     if (isBetterReferenceBindingKind(SCS1, SCS2))
4003       return ImplicitConversionSequence::Better;
4004     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4005       return ImplicitConversionSequence::Worse;
4006   }
4007 
4008   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4009   // bullet 3).
4010   if (ImplicitConversionSequence::CompareKind QualCK
4011         = CompareQualificationConversions(S, SCS1, SCS2))
4012     return QualCK;
4013 
4014   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4015     // C++ [over.ics.rank]p3b4:
4016     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4017     //      which the references refer are the same type except for
4018     //      top-level cv-qualifiers, and the type to which the reference
4019     //      initialized by S2 refers is more cv-qualified than the type
4020     //      to which the reference initialized by S1 refers.
4021     QualType T1 = SCS1.getToType(2);
4022     QualType T2 = SCS2.getToType(2);
4023     T1 = S.Context.getCanonicalType(T1);
4024     T2 = S.Context.getCanonicalType(T2);
4025     Qualifiers T1Quals, T2Quals;
4026     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4027     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4028     if (UnqualT1 == UnqualT2) {
4029       // Objective-C++ ARC: If the references refer to objects with different
4030       // lifetimes, prefer bindings that don't change lifetime.
4031       if (SCS1.ObjCLifetimeConversionBinding !=
4032                                           SCS2.ObjCLifetimeConversionBinding) {
4033         return SCS1.ObjCLifetimeConversionBinding
4034                                            ? ImplicitConversionSequence::Worse
4035                                            : ImplicitConversionSequence::Better;
4036       }
4037 
4038       // If the type is an array type, promote the element qualifiers to the
4039       // type for comparison.
4040       if (isa<ArrayType>(T1) && T1Quals)
4041         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4042       if (isa<ArrayType>(T2) && T2Quals)
4043         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4044       if (T2.isMoreQualifiedThan(T1))
4045         return ImplicitConversionSequence::Better;
4046       if (T1.isMoreQualifiedThan(T2))
4047         return ImplicitConversionSequence::Worse;
4048     }
4049   }
4050 
4051   // In Microsoft mode, prefer an integral conversion to a
4052   // floating-to-integral conversion if the integral conversion
4053   // is between types of the same size.
4054   // For example:
4055   // void f(float);
4056   // void f(int);
4057   // int main {
4058   //    long a;
4059   //    f(a);
4060   // }
4061   // Here, MSVC will call f(int) instead of generating a compile error
4062   // as clang will do in standard mode.
4063   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4064       SCS2.Second == ICK_Floating_Integral &&
4065       S.Context.getTypeSize(SCS1.getFromType()) ==
4066           S.Context.getTypeSize(SCS1.getToType(2)))
4067     return ImplicitConversionSequence::Better;
4068 
4069   // Prefer a compatible vector conversion over a lax vector conversion
4070   // For example:
4071   //
4072   // typedef float __v4sf __attribute__((__vector_size__(16)));
4073   // void f(vector float);
4074   // void f(vector signed int);
4075   // int main() {
4076   //   __v4sf a;
4077   //   f(a);
4078   // }
4079   // Here, we'd like to choose f(vector float) and not
4080   // report an ambiguous call error
4081   if (SCS1.Second == ICK_Vector_Conversion &&
4082       SCS2.Second == ICK_Vector_Conversion) {
4083     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4084         SCS1.getFromType(), SCS1.getToType(2));
4085     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4086         SCS2.getFromType(), SCS2.getToType(2));
4087 
4088     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4089       return SCS1IsCompatibleVectorConversion
4090                  ? ImplicitConversionSequence::Better
4091                  : ImplicitConversionSequence::Worse;
4092   }
4093 
4094   return ImplicitConversionSequence::Indistinguishable;
4095 }
4096 
4097 /// CompareQualificationConversions - Compares two standard conversion
4098 /// sequences to determine whether they can be ranked based on their
4099 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4100 static ImplicitConversionSequence::CompareKind
4101 CompareQualificationConversions(Sema &S,
4102                                 const StandardConversionSequence& SCS1,
4103                                 const StandardConversionSequence& SCS2) {
4104   // C++ 13.3.3.2p3:
4105   //  -- S1 and S2 differ only in their qualification conversion and
4106   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4107   //     cv-qualification signature of type T1 is a proper subset of
4108   //     the cv-qualification signature of type T2, and S1 is not the
4109   //     deprecated string literal array-to-pointer conversion (4.2).
4110   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4111       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4112     return ImplicitConversionSequence::Indistinguishable;
4113 
4114   // FIXME: the example in the standard doesn't use a qualification
4115   // conversion (!)
4116   QualType T1 = SCS1.getToType(2);
4117   QualType T2 = SCS2.getToType(2);
4118   T1 = S.Context.getCanonicalType(T1);
4119   T2 = S.Context.getCanonicalType(T2);
4120   assert(!T1->isReferenceType() && !T2->isReferenceType());
4121   Qualifiers T1Quals, T2Quals;
4122   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4123   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4124 
4125   // If the types are the same, we won't learn anything by unwrapping
4126   // them.
4127   if (UnqualT1 == UnqualT2)
4128     return ImplicitConversionSequence::Indistinguishable;
4129 
4130   ImplicitConversionSequence::CompareKind Result
4131     = ImplicitConversionSequence::Indistinguishable;
4132 
4133   // Objective-C++ ARC:
4134   //   Prefer qualification conversions not involving a change in lifetime
4135   //   to qualification conversions that do not change lifetime.
4136   if (SCS1.QualificationIncludesObjCLifetime !=
4137                                       SCS2.QualificationIncludesObjCLifetime) {
4138     Result = SCS1.QualificationIncludesObjCLifetime
4139                ? ImplicitConversionSequence::Worse
4140                : ImplicitConversionSequence::Better;
4141   }
4142 
4143   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4144     // Within each iteration of the loop, we check the qualifiers to
4145     // determine if this still looks like a qualification
4146     // conversion. Then, if all is well, we unwrap one more level of
4147     // pointers or pointers-to-members and do it all again
4148     // until there are no more pointers or pointers-to-members left
4149     // to unwrap. This essentially mimics what
4150     // IsQualificationConversion does, but here we're checking for a
4151     // strict subset of qualifiers.
4152     if (T1.getQualifiers().withoutObjCLifetime() ==
4153         T2.getQualifiers().withoutObjCLifetime())
4154       // The qualifiers are the same, so this doesn't tell us anything
4155       // about how the sequences rank.
4156       // ObjC ownership quals are omitted above as they interfere with
4157       // the ARC overload rule.
4158       ;
4159     else if (T2.isMoreQualifiedThan(T1)) {
4160       // T1 has fewer qualifiers, so it could be the better sequence.
4161       if (Result == ImplicitConversionSequence::Worse)
4162         // Neither has qualifiers that are a subset of the other's
4163         // qualifiers.
4164         return ImplicitConversionSequence::Indistinguishable;
4165 
4166       Result = ImplicitConversionSequence::Better;
4167     } else if (T1.isMoreQualifiedThan(T2)) {
4168       // T2 has fewer qualifiers, so it could be the better sequence.
4169       if (Result == ImplicitConversionSequence::Better)
4170         // Neither has qualifiers that are a subset of the other's
4171         // qualifiers.
4172         return ImplicitConversionSequence::Indistinguishable;
4173 
4174       Result = ImplicitConversionSequence::Worse;
4175     } else {
4176       // Qualifiers are disjoint.
4177       return ImplicitConversionSequence::Indistinguishable;
4178     }
4179 
4180     // If the types after this point are equivalent, we're done.
4181     if (S.Context.hasSameUnqualifiedType(T1, T2))
4182       break;
4183   }
4184 
4185   // Check that the winning standard conversion sequence isn't using
4186   // the deprecated string literal array to pointer conversion.
4187   switch (Result) {
4188   case ImplicitConversionSequence::Better:
4189     if (SCS1.DeprecatedStringLiteralToCharPtr)
4190       Result = ImplicitConversionSequence::Indistinguishable;
4191     break;
4192 
4193   case ImplicitConversionSequence::Indistinguishable:
4194     break;
4195 
4196   case ImplicitConversionSequence::Worse:
4197     if (SCS2.DeprecatedStringLiteralToCharPtr)
4198       Result = ImplicitConversionSequence::Indistinguishable;
4199     break;
4200   }
4201 
4202   return Result;
4203 }
4204 
4205 /// CompareDerivedToBaseConversions - Compares two standard conversion
4206 /// sequences to determine whether they can be ranked based on their
4207 /// various kinds of derived-to-base conversions (C++
4208 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4209 /// conversions between Objective-C interface types.
4210 static ImplicitConversionSequence::CompareKind
4211 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4212                                 const StandardConversionSequence& SCS1,
4213                                 const StandardConversionSequence& SCS2) {
4214   QualType FromType1 = SCS1.getFromType();
4215   QualType ToType1 = SCS1.getToType(1);
4216   QualType FromType2 = SCS2.getFromType();
4217   QualType ToType2 = SCS2.getToType(1);
4218 
4219   // Adjust the types we're converting from via the array-to-pointer
4220   // conversion, if we need to.
4221   if (SCS1.First == ICK_Array_To_Pointer)
4222     FromType1 = S.Context.getArrayDecayedType(FromType1);
4223   if (SCS2.First == ICK_Array_To_Pointer)
4224     FromType2 = S.Context.getArrayDecayedType(FromType2);
4225 
4226   // Canonicalize all of the types.
4227   FromType1 = S.Context.getCanonicalType(FromType1);
4228   ToType1 = S.Context.getCanonicalType(ToType1);
4229   FromType2 = S.Context.getCanonicalType(FromType2);
4230   ToType2 = S.Context.getCanonicalType(ToType2);
4231 
4232   // C++ [over.ics.rank]p4b3:
4233   //
4234   //   If class B is derived directly or indirectly from class A and
4235   //   class C is derived directly or indirectly from B,
4236   //
4237   // Compare based on pointer conversions.
4238   if (SCS1.Second == ICK_Pointer_Conversion &&
4239       SCS2.Second == ICK_Pointer_Conversion &&
4240       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4241       FromType1->isPointerType() && FromType2->isPointerType() &&
4242       ToType1->isPointerType() && ToType2->isPointerType()) {
4243     QualType FromPointee1 =
4244         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4245     QualType ToPointee1 =
4246         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4247     QualType FromPointee2 =
4248         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4249     QualType ToPointee2 =
4250         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4251 
4252     //   -- conversion of C* to B* is better than conversion of C* to A*,
4253     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4254       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4255         return ImplicitConversionSequence::Better;
4256       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4257         return ImplicitConversionSequence::Worse;
4258     }
4259 
4260     //   -- conversion of B* to A* is better than conversion of C* to A*,
4261     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4262       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4263         return ImplicitConversionSequence::Better;
4264       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4265         return ImplicitConversionSequence::Worse;
4266     }
4267   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4268              SCS2.Second == ICK_Pointer_Conversion) {
4269     const ObjCObjectPointerType *FromPtr1
4270       = FromType1->getAs<ObjCObjectPointerType>();
4271     const ObjCObjectPointerType *FromPtr2
4272       = FromType2->getAs<ObjCObjectPointerType>();
4273     const ObjCObjectPointerType *ToPtr1
4274       = ToType1->getAs<ObjCObjectPointerType>();
4275     const ObjCObjectPointerType *ToPtr2
4276       = ToType2->getAs<ObjCObjectPointerType>();
4277 
4278     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4279       // Apply the same conversion ranking rules for Objective-C pointer types
4280       // that we do for C++ pointers to class types. However, we employ the
4281       // Objective-C pseudo-subtyping relationship used for assignment of
4282       // Objective-C pointer types.
4283       bool FromAssignLeft
4284         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4285       bool FromAssignRight
4286         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4287       bool ToAssignLeft
4288         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4289       bool ToAssignRight
4290         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4291 
4292       // A conversion to an a non-id object pointer type or qualified 'id'
4293       // type is better than a conversion to 'id'.
4294       if (ToPtr1->isObjCIdType() &&
4295           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4296         return ImplicitConversionSequence::Worse;
4297       if (ToPtr2->isObjCIdType() &&
4298           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4299         return ImplicitConversionSequence::Better;
4300 
4301       // A conversion to a non-id object pointer type is better than a
4302       // conversion to a qualified 'id' type
4303       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4304         return ImplicitConversionSequence::Worse;
4305       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4306         return ImplicitConversionSequence::Better;
4307 
4308       // A conversion to an a non-Class object pointer type or qualified 'Class'
4309       // type is better than a conversion to 'Class'.
4310       if (ToPtr1->isObjCClassType() &&
4311           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4312         return ImplicitConversionSequence::Worse;
4313       if (ToPtr2->isObjCClassType() &&
4314           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4315         return ImplicitConversionSequence::Better;
4316 
4317       // A conversion to a non-Class object pointer type is better than a
4318       // conversion to a qualified 'Class' type.
4319       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4320         return ImplicitConversionSequence::Worse;
4321       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4322         return ImplicitConversionSequence::Better;
4323 
4324       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4325       if (S.Context.hasSameType(FromType1, FromType2) &&
4326           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4327           (ToAssignLeft != ToAssignRight)) {
4328         if (FromPtr1->isSpecialized()) {
4329           // "conversion of B<A> * to B * is better than conversion of B * to
4330           // C *.
4331           bool IsFirstSame =
4332               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4333           bool IsSecondSame =
4334               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4335           if (IsFirstSame) {
4336             if (!IsSecondSame)
4337               return ImplicitConversionSequence::Better;
4338           } else if (IsSecondSame)
4339             return ImplicitConversionSequence::Worse;
4340         }
4341         return ToAssignLeft? ImplicitConversionSequence::Worse
4342                            : ImplicitConversionSequence::Better;
4343       }
4344 
4345       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4346       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4347           (FromAssignLeft != FromAssignRight))
4348         return FromAssignLeft? ImplicitConversionSequence::Better
4349         : ImplicitConversionSequence::Worse;
4350     }
4351   }
4352 
4353   // Ranking of member-pointer types.
4354   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4355       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4356       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4357     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4358     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4359     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4360     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4361     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4362     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4363     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4364     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4365     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4366     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4367     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4368     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4369     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4370     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4371       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4372         return ImplicitConversionSequence::Worse;
4373       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4374         return ImplicitConversionSequence::Better;
4375     }
4376     // conversion of B::* to C::* is better than conversion of A::* to C::*
4377     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4378       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4379         return ImplicitConversionSequence::Better;
4380       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4381         return ImplicitConversionSequence::Worse;
4382     }
4383   }
4384 
4385   if (SCS1.Second == ICK_Derived_To_Base) {
4386     //   -- conversion of C to B is better than conversion of C to A,
4387     //   -- binding of an expression of type C to a reference of type
4388     //      B& is better than binding an expression of type C to a
4389     //      reference of type A&,
4390     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4391         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4392       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4393         return ImplicitConversionSequence::Better;
4394       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4395         return ImplicitConversionSequence::Worse;
4396     }
4397 
4398     //   -- conversion of B to A is better than conversion of C to A.
4399     //   -- binding of an expression of type B to a reference of type
4400     //      A& is better than binding an expression of type C to a
4401     //      reference of type A&,
4402     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4403         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4404       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4405         return ImplicitConversionSequence::Better;
4406       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4407         return ImplicitConversionSequence::Worse;
4408     }
4409   }
4410 
4411   return ImplicitConversionSequence::Indistinguishable;
4412 }
4413 
4414 /// Determine whether the given type is valid, e.g., it is not an invalid
4415 /// C++ class.
4416 static bool isTypeValid(QualType T) {
4417   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4418     return !Record->isInvalidDecl();
4419 
4420   return true;
4421 }
4422 
4423 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4424   if (!T.getQualifiers().hasUnaligned())
4425     return T;
4426 
4427   Qualifiers Q;
4428   T = Ctx.getUnqualifiedArrayType(T, Q);
4429   Q.removeUnaligned();
4430   return Ctx.getQualifiedType(T, Q);
4431 }
4432 
4433 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4434 /// determine whether they are reference-compatible,
4435 /// reference-related, or incompatible, for use in C++ initialization by
4436 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4437 /// type, and the first type (T1) is the pointee type of the reference
4438 /// type being initialized.
4439 Sema::ReferenceCompareResult
4440 Sema::CompareReferenceRelationship(SourceLocation Loc,
4441                                    QualType OrigT1, QualType OrigT2,
4442                                    ReferenceConversions *ConvOut) {
4443   assert(!OrigT1->isReferenceType() &&
4444     "T1 must be the pointee type of the reference type");
4445   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4446 
4447   QualType T1 = Context.getCanonicalType(OrigT1);
4448   QualType T2 = Context.getCanonicalType(OrigT2);
4449   Qualifiers T1Quals, T2Quals;
4450   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4451   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4452 
4453   ReferenceConversions ConvTmp;
4454   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4455   Conv = ReferenceConversions();
4456 
4457   // C++2a [dcl.init.ref]p4:
4458   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4459   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4460   //   T1 is a base class of T2.
4461   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4462   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4463   //   "pointer to cv1 T1" via a standard conversion sequence.
4464 
4465   // Check for standard conversions we can apply to pointers: derived-to-base
4466   // conversions, ObjC pointer conversions, and function pointer conversions.
4467   // (Qualification conversions are checked last.)
4468   QualType ConvertedT2;
4469   if (UnqualT1 == UnqualT2) {
4470     // Nothing to do.
4471   } else if (isCompleteType(Loc, OrigT2) &&
4472              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4473              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4474     Conv |= ReferenceConversions::DerivedToBase;
4475   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4476            UnqualT2->isObjCObjectOrInterfaceType() &&
4477            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4478     Conv |= ReferenceConversions::ObjC;
4479   else if (UnqualT2->isFunctionType() &&
4480            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4481     Conv |= ReferenceConversions::Function;
4482     // No need to check qualifiers; function types don't have them.
4483     return Ref_Compatible;
4484   }
4485   bool ConvertedReferent = Conv != 0;
4486 
4487   // We can have a qualification conversion. Compute whether the types are
4488   // similar at the same time.
4489   bool PreviousToQualsIncludeConst = true;
4490   bool TopLevel = true;
4491   do {
4492     if (T1 == T2)
4493       break;
4494 
4495     // We will need a qualification conversion.
4496     Conv |= ReferenceConversions::Qualification;
4497 
4498     // Track whether we performed a qualification conversion anywhere other
4499     // than the top level. This matters for ranking reference bindings in
4500     // overload resolution.
4501     if (!TopLevel)
4502       Conv |= ReferenceConversions::NestedQualification;
4503 
4504     // MS compiler ignores __unaligned qualifier for references; do the same.
4505     T1 = withoutUnaligned(Context, T1);
4506     T2 = withoutUnaligned(Context, T2);
4507 
4508     // If we find a qualifier mismatch, the types are not reference-compatible,
4509     // but are still be reference-related if they're similar.
4510     bool ObjCLifetimeConversion = false;
4511     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false,
4512                                        PreviousToQualsIncludeConst,
4513                                        ObjCLifetimeConversion))
4514       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4515                  ? Ref_Related
4516                  : Ref_Incompatible;
4517 
4518     // FIXME: Should we track this for any level other than the first?
4519     if (ObjCLifetimeConversion)
4520       Conv |= ReferenceConversions::ObjCLifetime;
4521 
4522     TopLevel = false;
4523   } while (Context.UnwrapSimilarTypes(T1, T2));
4524 
4525   // At this point, if the types are reference-related, we must either have the
4526   // same inner type (ignoring qualifiers), or must have already worked out how
4527   // to convert the referent.
4528   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4529              ? Ref_Compatible
4530              : Ref_Incompatible;
4531 }
4532 
4533 /// Look for a user-defined conversion to a value reference-compatible
4534 ///        with DeclType. Return true if something definite is found.
4535 static bool
4536 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4537                          QualType DeclType, SourceLocation DeclLoc,
4538                          Expr *Init, QualType T2, bool AllowRvalues,
4539                          bool AllowExplicit) {
4540   assert(T2->isRecordType() && "Can only find conversions of record types.");
4541   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4542 
4543   OverloadCandidateSet CandidateSet(
4544       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4545   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4546   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4547     NamedDecl *D = *I;
4548     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4549     if (isa<UsingShadowDecl>(D))
4550       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4551 
4552     FunctionTemplateDecl *ConvTemplate
4553       = dyn_cast<FunctionTemplateDecl>(D);
4554     CXXConversionDecl *Conv;
4555     if (ConvTemplate)
4556       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4557     else
4558       Conv = cast<CXXConversionDecl>(D);
4559 
4560     if (AllowRvalues) {
4561       // If we are initializing an rvalue reference, don't permit conversion
4562       // functions that return lvalues.
4563       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4564         const ReferenceType *RefType
4565           = Conv->getConversionType()->getAs<LValueReferenceType>();
4566         if (RefType && !RefType->getPointeeType()->isFunctionType())
4567           continue;
4568       }
4569 
4570       if (!ConvTemplate &&
4571           S.CompareReferenceRelationship(
4572               DeclLoc,
4573               Conv->getConversionType()
4574                   .getNonReferenceType()
4575                   .getUnqualifiedType(),
4576               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4577               Sema::Ref_Incompatible)
4578         continue;
4579     } else {
4580       // If the conversion function doesn't return a reference type,
4581       // it can't be considered for this conversion. An rvalue reference
4582       // is only acceptable if its referencee is a function type.
4583 
4584       const ReferenceType *RefType =
4585         Conv->getConversionType()->getAs<ReferenceType>();
4586       if (!RefType ||
4587           (!RefType->isLValueReferenceType() &&
4588            !RefType->getPointeeType()->isFunctionType()))
4589         continue;
4590     }
4591 
4592     if (ConvTemplate)
4593       S.AddTemplateConversionCandidate(
4594           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4595           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4596     else
4597       S.AddConversionCandidate(
4598           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4599           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4600   }
4601 
4602   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4603 
4604   OverloadCandidateSet::iterator Best;
4605   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4606   case OR_Success:
4607     // C++ [over.ics.ref]p1:
4608     //
4609     //   [...] If the parameter binds directly to the result of
4610     //   applying a conversion function to the argument
4611     //   expression, the implicit conversion sequence is a
4612     //   user-defined conversion sequence (13.3.3.1.2), with the
4613     //   second standard conversion sequence either an identity
4614     //   conversion or, if the conversion function returns an
4615     //   entity of a type that is a derived class of the parameter
4616     //   type, a derived-to-base Conversion.
4617     if (!Best->FinalConversion.DirectBinding)
4618       return false;
4619 
4620     ICS.setUserDefined();
4621     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4622     ICS.UserDefined.After = Best->FinalConversion;
4623     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4624     ICS.UserDefined.ConversionFunction = Best->Function;
4625     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4626     ICS.UserDefined.EllipsisConversion = false;
4627     assert(ICS.UserDefined.After.ReferenceBinding &&
4628            ICS.UserDefined.After.DirectBinding &&
4629            "Expected a direct reference binding!");
4630     return true;
4631 
4632   case OR_Ambiguous:
4633     ICS.setAmbiguous();
4634     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4635          Cand != CandidateSet.end(); ++Cand)
4636       if (Cand->Best)
4637         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4638     return true;
4639 
4640   case OR_No_Viable_Function:
4641   case OR_Deleted:
4642     // There was no suitable conversion, or we found a deleted
4643     // conversion; continue with other checks.
4644     return false;
4645   }
4646 
4647   llvm_unreachable("Invalid OverloadResult!");
4648 }
4649 
4650 /// Compute an implicit conversion sequence for reference
4651 /// initialization.
4652 static ImplicitConversionSequence
4653 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4654                  SourceLocation DeclLoc,
4655                  bool SuppressUserConversions,
4656                  bool AllowExplicit) {
4657   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4658 
4659   // Most paths end in a failed conversion.
4660   ImplicitConversionSequence ICS;
4661   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4662 
4663   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4664   QualType T2 = Init->getType();
4665 
4666   // If the initializer is the address of an overloaded function, try
4667   // to resolve the overloaded function. If all goes well, T2 is the
4668   // type of the resulting function.
4669   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4670     DeclAccessPair Found;
4671     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4672                                                                 false, Found))
4673       T2 = Fn->getType();
4674   }
4675 
4676   // Compute some basic properties of the types and the initializer.
4677   bool isRValRef = DeclType->isRValueReferenceType();
4678   Expr::Classification InitCategory = Init->Classify(S.Context);
4679 
4680   Sema::ReferenceConversions RefConv;
4681   Sema::ReferenceCompareResult RefRelationship =
4682       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4683 
4684   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4685     ICS.setStandard();
4686     ICS.Standard.First = ICK_Identity;
4687     // FIXME: A reference binding can be a function conversion too. We should
4688     // consider that when ordering reference-to-function bindings.
4689     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4690                               ? ICK_Derived_To_Base
4691                               : (RefConv & Sema::ReferenceConversions::ObjC)
4692                                     ? ICK_Compatible_Conversion
4693                                     : ICK_Identity;
4694     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4695     // a reference binding that performs a non-top-level qualification
4696     // conversion as a qualification conversion, not as an identity conversion.
4697     ICS.Standard.Third = (RefConv &
4698                               Sema::ReferenceConversions::NestedQualification)
4699                              ? ICK_Qualification
4700                              : ICK_Identity;
4701     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4702     ICS.Standard.setToType(0, T2);
4703     ICS.Standard.setToType(1, T1);
4704     ICS.Standard.setToType(2, T1);
4705     ICS.Standard.ReferenceBinding = true;
4706     ICS.Standard.DirectBinding = BindsDirectly;
4707     ICS.Standard.IsLvalueReference = !isRValRef;
4708     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4709     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4710     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4711     ICS.Standard.ObjCLifetimeConversionBinding =
4712         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4713     ICS.Standard.CopyConstructor = nullptr;
4714     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4715   };
4716 
4717   // C++0x [dcl.init.ref]p5:
4718   //   A reference to type "cv1 T1" is initialized by an expression
4719   //   of type "cv2 T2" as follows:
4720 
4721   //     -- If reference is an lvalue reference and the initializer expression
4722   if (!isRValRef) {
4723     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4724     //        reference-compatible with "cv2 T2," or
4725     //
4726     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4727     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4728       // C++ [over.ics.ref]p1:
4729       //   When a parameter of reference type binds directly (8.5.3)
4730       //   to an argument expression, the implicit conversion sequence
4731       //   is the identity conversion, unless the argument expression
4732       //   has a type that is a derived class of the parameter type,
4733       //   in which case the implicit conversion sequence is a
4734       //   derived-to-base Conversion (13.3.3.1).
4735       SetAsReferenceBinding(/*BindsDirectly=*/true);
4736 
4737       // Nothing more to do: the inaccessibility/ambiguity check for
4738       // derived-to-base conversions is suppressed when we're
4739       // computing the implicit conversion sequence (C++
4740       // [over.best.ics]p2).
4741       return ICS;
4742     }
4743 
4744     //       -- has a class type (i.e., T2 is a class type), where T1 is
4745     //          not reference-related to T2, and can be implicitly
4746     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4747     //          is reference-compatible with "cv3 T3" 92) (this
4748     //          conversion is selected by enumerating the applicable
4749     //          conversion functions (13.3.1.6) and choosing the best
4750     //          one through overload resolution (13.3)),
4751     if (!SuppressUserConversions && T2->isRecordType() &&
4752         S.isCompleteType(DeclLoc, T2) &&
4753         RefRelationship == Sema::Ref_Incompatible) {
4754       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4755                                    Init, T2, /*AllowRvalues=*/false,
4756                                    AllowExplicit))
4757         return ICS;
4758     }
4759   }
4760 
4761   //     -- Otherwise, the reference shall be an lvalue reference to a
4762   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4763   //        shall be an rvalue reference.
4764   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4765     return ICS;
4766 
4767   //       -- If the initializer expression
4768   //
4769   //            -- is an xvalue, class prvalue, array prvalue or function
4770   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4771   if (RefRelationship == Sema::Ref_Compatible &&
4772       (InitCategory.isXValue() ||
4773        (InitCategory.isPRValue() &&
4774           (T2->isRecordType() || T2->isArrayType())) ||
4775        (InitCategory.isLValue() && T2->isFunctionType()))) {
4776     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4777     // binding unless we're binding to a class prvalue.
4778     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4779     // allow the use of rvalue references in C++98/03 for the benefit of
4780     // standard library implementors; therefore, we need the xvalue check here.
4781     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4782                           !(InitCategory.isPRValue() || T2->isRecordType()));
4783     return ICS;
4784   }
4785 
4786   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4787   //               reference-related to T2, and can be implicitly converted to
4788   //               an xvalue, class prvalue, or function lvalue of type
4789   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4790   //               "cv3 T3",
4791   //
4792   //          then the reference is bound to the value of the initializer
4793   //          expression in the first case and to the result of the conversion
4794   //          in the second case (or, in either case, to an appropriate base
4795   //          class subobject).
4796   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4797       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4798       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4799                                Init, T2, /*AllowRvalues=*/true,
4800                                AllowExplicit)) {
4801     // In the second case, if the reference is an rvalue reference
4802     // and the second standard conversion sequence of the
4803     // user-defined conversion sequence includes an lvalue-to-rvalue
4804     // conversion, the program is ill-formed.
4805     if (ICS.isUserDefined() && isRValRef &&
4806         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4807       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4808 
4809     return ICS;
4810   }
4811 
4812   // A temporary of function type cannot be created; don't even try.
4813   if (T1->isFunctionType())
4814     return ICS;
4815 
4816   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4817   //          initialized from the initializer expression using the
4818   //          rules for a non-reference copy initialization (8.5). The
4819   //          reference is then bound to the temporary. If T1 is
4820   //          reference-related to T2, cv1 must be the same
4821   //          cv-qualification as, or greater cv-qualification than,
4822   //          cv2; otherwise, the program is ill-formed.
4823   if (RefRelationship == Sema::Ref_Related) {
4824     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4825     // we would be reference-compatible or reference-compatible with
4826     // added qualification. But that wasn't the case, so the reference
4827     // initialization fails.
4828     //
4829     // Note that we only want to check address spaces and cvr-qualifiers here.
4830     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4831     Qualifiers T1Quals = T1.getQualifiers();
4832     Qualifiers T2Quals = T2.getQualifiers();
4833     T1Quals.removeObjCGCAttr();
4834     T1Quals.removeObjCLifetime();
4835     T2Quals.removeObjCGCAttr();
4836     T2Quals.removeObjCLifetime();
4837     // MS compiler ignores __unaligned qualifier for references; do the same.
4838     T1Quals.removeUnaligned();
4839     T2Quals.removeUnaligned();
4840     if (!T1Quals.compatiblyIncludes(T2Quals))
4841       return ICS;
4842   }
4843 
4844   // If at least one of the types is a class type, the types are not
4845   // related, and we aren't allowed any user conversions, the
4846   // reference binding fails. This case is important for breaking
4847   // recursion, since TryImplicitConversion below will attempt to
4848   // create a temporary through the use of a copy constructor.
4849   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4850       (T1->isRecordType() || T2->isRecordType()))
4851     return ICS;
4852 
4853   // If T1 is reference-related to T2 and the reference is an rvalue
4854   // reference, the initializer expression shall not be an lvalue.
4855   if (RefRelationship >= Sema::Ref_Related &&
4856       isRValRef && Init->Classify(S.Context).isLValue())
4857     return ICS;
4858 
4859   // C++ [over.ics.ref]p2:
4860   //   When a parameter of reference type is not bound directly to
4861   //   an argument expression, the conversion sequence is the one
4862   //   required to convert the argument expression to the
4863   //   underlying type of the reference according to
4864   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4865   //   to copy-initializing a temporary of the underlying type with
4866   //   the argument expression. Any difference in top-level
4867   //   cv-qualification is subsumed by the initialization itself
4868   //   and does not constitute a conversion.
4869   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4870                               AllowedExplicit::None,
4871                               /*InOverloadResolution=*/false,
4872                               /*CStyle=*/false,
4873                               /*AllowObjCWritebackConversion=*/false,
4874                               /*AllowObjCConversionOnExplicit=*/false);
4875 
4876   // Of course, that's still a reference binding.
4877   if (ICS.isStandard()) {
4878     ICS.Standard.ReferenceBinding = true;
4879     ICS.Standard.IsLvalueReference = !isRValRef;
4880     ICS.Standard.BindsToFunctionLvalue = false;
4881     ICS.Standard.BindsToRvalue = true;
4882     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4883     ICS.Standard.ObjCLifetimeConversionBinding = false;
4884   } else if (ICS.isUserDefined()) {
4885     const ReferenceType *LValRefType =
4886         ICS.UserDefined.ConversionFunction->getReturnType()
4887             ->getAs<LValueReferenceType>();
4888 
4889     // C++ [over.ics.ref]p3:
4890     //   Except for an implicit object parameter, for which see 13.3.1, a
4891     //   standard conversion sequence cannot be formed if it requires [...]
4892     //   binding an rvalue reference to an lvalue other than a function
4893     //   lvalue.
4894     // Note that the function case is not possible here.
4895     if (DeclType->isRValueReferenceType() && LValRefType) {
4896       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4897       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4898       // reference to an rvalue!
4899       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4900       return ICS;
4901     }
4902 
4903     ICS.UserDefined.After.ReferenceBinding = true;
4904     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4905     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4906     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4907     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4908     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4909   }
4910 
4911   return ICS;
4912 }
4913 
4914 static ImplicitConversionSequence
4915 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4916                       bool SuppressUserConversions,
4917                       bool InOverloadResolution,
4918                       bool AllowObjCWritebackConversion,
4919                       bool AllowExplicit = false);
4920 
4921 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4922 /// initializer list From.
4923 static ImplicitConversionSequence
4924 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4925                   bool SuppressUserConversions,
4926                   bool InOverloadResolution,
4927                   bool AllowObjCWritebackConversion) {
4928   // C++11 [over.ics.list]p1:
4929   //   When an argument is an initializer list, it is not an expression and
4930   //   special rules apply for converting it to a parameter type.
4931 
4932   ImplicitConversionSequence Result;
4933   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4934 
4935   // We need a complete type for what follows. Incomplete types can never be
4936   // initialized from init lists.
4937   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4938     return Result;
4939 
4940   // Per DR1467:
4941   //   If the parameter type is a class X and the initializer list has a single
4942   //   element of type cv U, where U is X or a class derived from X, the
4943   //   implicit conversion sequence is the one required to convert the element
4944   //   to the parameter type.
4945   //
4946   //   Otherwise, if the parameter type is a character array [... ]
4947   //   and the initializer list has a single element that is an
4948   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4949   //   implicit conversion sequence is the identity conversion.
4950   if (From->getNumInits() == 1) {
4951     if (ToType->isRecordType()) {
4952       QualType InitType = From->getInit(0)->getType();
4953       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4954           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4955         return TryCopyInitialization(S, From->getInit(0), ToType,
4956                                      SuppressUserConversions,
4957                                      InOverloadResolution,
4958                                      AllowObjCWritebackConversion);
4959     }
4960     // FIXME: Check the other conditions here: array of character type,
4961     // initializer is a string literal.
4962     if (ToType->isArrayType()) {
4963       InitializedEntity Entity =
4964         InitializedEntity::InitializeParameter(S.Context, ToType,
4965                                                /*Consumed=*/false);
4966       if (S.CanPerformCopyInitialization(Entity, From)) {
4967         Result.setStandard();
4968         Result.Standard.setAsIdentityConversion();
4969         Result.Standard.setFromType(ToType);
4970         Result.Standard.setAllToTypes(ToType);
4971         return Result;
4972       }
4973     }
4974   }
4975 
4976   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4977   // C++11 [over.ics.list]p2:
4978   //   If the parameter type is std::initializer_list<X> or "array of X" and
4979   //   all the elements can be implicitly converted to X, the implicit
4980   //   conversion sequence is the worst conversion necessary to convert an
4981   //   element of the list to X.
4982   //
4983   // C++14 [over.ics.list]p3:
4984   //   Otherwise, if the parameter type is "array of N X", if the initializer
4985   //   list has exactly N elements or if it has fewer than N elements and X is
4986   //   default-constructible, and if all the elements of the initializer list
4987   //   can be implicitly converted to X, the implicit conversion sequence is
4988   //   the worst conversion necessary to convert an element of the list to X.
4989   //
4990   // FIXME: We're missing a lot of these checks.
4991   bool toStdInitializerList = false;
4992   QualType X;
4993   if (ToType->isArrayType())
4994     X = S.Context.getAsArrayType(ToType)->getElementType();
4995   else
4996     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4997   if (!X.isNull()) {
4998     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4999       Expr *Init = From->getInit(i);
5000       ImplicitConversionSequence ICS =
5001           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5002                                 InOverloadResolution,
5003                                 AllowObjCWritebackConversion);
5004       // If a single element isn't convertible, fail.
5005       if (ICS.isBad()) {
5006         Result = ICS;
5007         break;
5008       }
5009       // Otherwise, look for the worst conversion.
5010       if (Result.isBad() || CompareImplicitConversionSequences(
5011                                 S, From->getBeginLoc(), ICS, Result) ==
5012                                 ImplicitConversionSequence::Worse)
5013         Result = ICS;
5014     }
5015 
5016     // For an empty list, we won't have computed any conversion sequence.
5017     // Introduce the identity conversion sequence.
5018     if (From->getNumInits() == 0) {
5019       Result.setStandard();
5020       Result.Standard.setAsIdentityConversion();
5021       Result.Standard.setFromType(ToType);
5022       Result.Standard.setAllToTypes(ToType);
5023     }
5024 
5025     Result.setStdInitializerListElement(toStdInitializerList);
5026     return Result;
5027   }
5028 
5029   // C++14 [over.ics.list]p4:
5030   // C++11 [over.ics.list]p3:
5031   //   Otherwise, if the parameter is a non-aggregate class X and overload
5032   //   resolution chooses a single best constructor [...] the implicit
5033   //   conversion sequence is a user-defined conversion sequence. If multiple
5034   //   constructors are viable but none is better than the others, the
5035   //   implicit conversion sequence is a user-defined conversion sequence.
5036   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5037     // This function can deal with initializer lists.
5038     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5039                                     AllowedExplicit::None,
5040                                     InOverloadResolution, /*CStyle=*/false,
5041                                     AllowObjCWritebackConversion,
5042                                     /*AllowObjCConversionOnExplicit=*/false);
5043   }
5044 
5045   // C++14 [over.ics.list]p5:
5046   // C++11 [over.ics.list]p4:
5047   //   Otherwise, if the parameter has an aggregate type which can be
5048   //   initialized from the initializer list [...] the implicit conversion
5049   //   sequence is a user-defined conversion sequence.
5050   if (ToType->isAggregateType()) {
5051     // Type is an aggregate, argument is an init list. At this point it comes
5052     // down to checking whether the initialization works.
5053     // FIXME: Find out whether this parameter is consumed or not.
5054     InitializedEntity Entity =
5055         InitializedEntity::InitializeParameter(S.Context, ToType,
5056                                                /*Consumed=*/false);
5057     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5058                                                                  From)) {
5059       Result.setUserDefined();
5060       Result.UserDefined.Before.setAsIdentityConversion();
5061       // Initializer lists don't have a type.
5062       Result.UserDefined.Before.setFromType(QualType());
5063       Result.UserDefined.Before.setAllToTypes(QualType());
5064 
5065       Result.UserDefined.After.setAsIdentityConversion();
5066       Result.UserDefined.After.setFromType(ToType);
5067       Result.UserDefined.After.setAllToTypes(ToType);
5068       Result.UserDefined.ConversionFunction = nullptr;
5069     }
5070     return Result;
5071   }
5072 
5073   // C++14 [over.ics.list]p6:
5074   // C++11 [over.ics.list]p5:
5075   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5076   if (ToType->isReferenceType()) {
5077     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5078     // mention initializer lists in any way. So we go by what list-
5079     // initialization would do and try to extrapolate from that.
5080 
5081     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5082 
5083     // If the initializer list has a single element that is reference-related
5084     // to the parameter type, we initialize the reference from that.
5085     if (From->getNumInits() == 1) {
5086       Expr *Init = From->getInit(0);
5087 
5088       QualType T2 = Init->getType();
5089 
5090       // If the initializer is the address of an overloaded function, try
5091       // to resolve the overloaded function. If all goes well, T2 is the
5092       // type of the resulting function.
5093       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5094         DeclAccessPair Found;
5095         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5096                                    Init, ToType, false, Found))
5097           T2 = Fn->getType();
5098       }
5099 
5100       // Compute some basic properties of the types and the initializer.
5101       Sema::ReferenceCompareResult RefRelationship =
5102           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5103 
5104       if (RefRelationship >= Sema::Ref_Related) {
5105         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5106                                 SuppressUserConversions,
5107                                 /*AllowExplicit=*/false);
5108       }
5109     }
5110 
5111     // Otherwise, we bind the reference to a temporary created from the
5112     // initializer list.
5113     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5114                                InOverloadResolution,
5115                                AllowObjCWritebackConversion);
5116     if (Result.isFailure())
5117       return Result;
5118     assert(!Result.isEllipsis() &&
5119            "Sub-initialization cannot result in ellipsis conversion.");
5120 
5121     // Can we even bind to a temporary?
5122     if (ToType->isRValueReferenceType() ||
5123         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5124       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5125                                             Result.UserDefined.After;
5126       SCS.ReferenceBinding = true;
5127       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5128       SCS.BindsToRvalue = true;
5129       SCS.BindsToFunctionLvalue = false;
5130       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5131       SCS.ObjCLifetimeConversionBinding = false;
5132     } else
5133       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5134                     From, ToType);
5135     return Result;
5136   }
5137 
5138   // C++14 [over.ics.list]p7:
5139   // C++11 [over.ics.list]p6:
5140   //   Otherwise, if the parameter type is not a class:
5141   if (!ToType->isRecordType()) {
5142     //    - if the initializer list has one element that is not itself an
5143     //      initializer list, the implicit conversion sequence is the one
5144     //      required to convert the element to the parameter type.
5145     unsigned NumInits = From->getNumInits();
5146     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5147       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5148                                      SuppressUserConversions,
5149                                      InOverloadResolution,
5150                                      AllowObjCWritebackConversion);
5151     //    - if the initializer list has no elements, the implicit conversion
5152     //      sequence is the identity conversion.
5153     else if (NumInits == 0) {
5154       Result.setStandard();
5155       Result.Standard.setAsIdentityConversion();
5156       Result.Standard.setFromType(ToType);
5157       Result.Standard.setAllToTypes(ToType);
5158     }
5159     return Result;
5160   }
5161 
5162   // C++14 [over.ics.list]p8:
5163   // C++11 [over.ics.list]p7:
5164   //   In all cases other than those enumerated above, no conversion is possible
5165   return Result;
5166 }
5167 
5168 /// TryCopyInitialization - Try to copy-initialize a value of type
5169 /// ToType from the expression From. Return the implicit conversion
5170 /// sequence required to pass this argument, which may be a bad
5171 /// conversion sequence (meaning that the argument cannot be passed to
5172 /// a parameter of this type). If @p SuppressUserConversions, then we
5173 /// do not permit any user-defined conversion sequences.
5174 static ImplicitConversionSequence
5175 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5176                       bool SuppressUserConversions,
5177                       bool InOverloadResolution,
5178                       bool AllowObjCWritebackConversion,
5179                       bool AllowExplicit) {
5180   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5181     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5182                              InOverloadResolution,AllowObjCWritebackConversion);
5183 
5184   if (ToType->isReferenceType())
5185     return TryReferenceInit(S, From, ToType,
5186                             /*FIXME:*/ From->getBeginLoc(),
5187                             SuppressUserConversions, AllowExplicit);
5188 
5189   return TryImplicitConversion(S, From, ToType,
5190                                SuppressUserConversions,
5191                                AllowedExplicit::None,
5192                                InOverloadResolution,
5193                                /*CStyle=*/false,
5194                                AllowObjCWritebackConversion,
5195                                /*AllowObjCConversionOnExplicit=*/false);
5196 }
5197 
5198 static bool TryCopyInitialization(const CanQualType FromQTy,
5199                                   const CanQualType ToQTy,
5200                                   Sema &S,
5201                                   SourceLocation Loc,
5202                                   ExprValueKind FromVK) {
5203   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5204   ImplicitConversionSequence ICS =
5205     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5206 
5207   return !ICS.isBad();
5208 }
5209 
5210 /// TryObjectArgumentInitialization - Try to initialize the object
5211 /// parameter of the given member function (@c Method) from the
5212 /// expression @p From.
5213 static ImplicitConversionSequence
5214 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5215                                 Expr::Classification FromClassification,
5216                                 CXXMethodDecl *Method,
5217                                 CXXRecordDecl *ActingContext) {
5218   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5219   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5220   //                 const volatile object.
5221   Qualifiers Quals = Method->getMethodQualifiers();
5222   if (isa<CXXDestructorDecl>(Method)) {
5223     Quals.addConst();
5224     Quals.addVolatile();
5225   }
5226 
5227   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5228 
5229   // Set up the conversion sequence as a "bad" conversion, to allow us
5230   // to exit early.
5231   ImplicitConversionSequence ICS;
5232 
5233   // We need to have an object of class type.
5234   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5235     FromType = PT->getPointeeType();
5236 
5237     // When we had a pointer, it's implicitly dereferenced, so we
5238     // better have an lvalue.
5239     assert(FromClassification.isLValue());
5240   }
5241 
5242   assert(FromType->isRecordType());
5243 
5244   // C++0x [over.match.funcs]p4:
5245   //   For non-static member functions, the type of the implicit object
5246   //   parameter is
5247   //
5248   //     - "lvalue reference to cv X" for functions declared without a
5249   //        ref-qualifier or with the & ref-qualifier
5250   //     - "rvalue reference to cv X" for functions declared with the &&
5251   //        ref-qualifier
5252   //
5253   // where X is the class of which the function is a member and cv is the
5254   // cv-qualification on the member function declaration.
5255   //
5256   // However, when finding an implicit conversion sequence for the argument, we
5257   // are not allowed to perform user-defined conversions
5258   // (C++ [over.match.funcs]p5). We perform a simplified version of
5259   // reference binding here, that allows class rvalues to bind to
5260   // non-constant references.
5261 
5262   // First check the qualifiers.
5263   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5264   if (ImplicitParamType.getCVRQualifiers()
5265                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5266       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5267     ICS.setBad(BadConversionSequence::bad_qualifiers,
5268                FromType, ImplicitParamType);
5269     return ICS;
5270   }
5271 
5272   if (FromTypeCanon.hasAddressSpace()) {
5273     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5274     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5275     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5276       ICS.setBad(BadConversionSequence::bad_qualifiers,
5277                  FromType, ImplicitParamType);
5278       return ICS;
5279     }
5280   }
5281 
5282   // Check that we have either the same type or a derived type. It
5283   // affects the conversion rank.
5284   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5285   ImplicitConversionKind SecondKind;
5286   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5287     SecondKind = ICK_Identity;
5288   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5289     SecondKind = ICK_Derived_To_Base;
5290   else {
5291     ICS.setBad(BadConversionSequence::unrelated_class,
5292                FromType, ImplicitParamType);
5293     return ICS;
5294   }
5295 
5296   // Check the ref-qualifier.
5297   switch (Method->getRefQualifier()) {
5298   case RQ_None:
5299     // Do nothing; we don't care about lvalueness or rvalueness.
5300     break;
5301 
5302   case RQ_LValue:
5303     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5304       // non-const lvalue reference cannot bind to an rvalue
5305       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5306                  ImplicitParamType);
5307       return ICS;
5308     }
5309     break;
5310 
5311   case RQ_RValue:
5312     if (!FromClassification.isRValue()) {
5313       // rvalue reference cannot bind to an lvalue
5314       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5315                  ImplicitParamType);
5316       return ICS;
5317     }
5318     break;
5319   }
5320 
5321   // Success. Mark this as a reference binding.
5322   ICS.setStandard();
5323   ICS.Standard.setAsIdentityConversion();
5324   ICS.Standard.Second = SecondKind;
5325   ICS.Standard.setFromType(FromType);
5326   ICS.Standard.setAllToTypes(ImplicitParamType);
5327   ICS.Standard.ReferenceBinding = true;
5328   ICS.Standard.DirectBinding = true;
5329   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5330   ICS.Standard.BindsToFunctionLvalue = false;
5331   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5332   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5333     = (Method->getRefQualifier() == RQ_None);
5334   return ICS;
5335 }
5336 
5337 /// PerformObjectArgumentInitialization - Perform initialization of
5338 /// the implicit object parameter for the given Method with the given
5339 /// expression.
5340 ExprResult
5341 Sema::PerformObjectArgumentInitialization(Expr *From,
5342                                           NestedNameSpecifier *Qualifier,
5343                                           NamedDecl *FoundDecl,
5344                                           CXXMethodDecl *Method) {
5345   QualType FromRecordType, DestType;
5346   QualType ImplicitParamRecordType  =
5347     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5348 
5349   Expr::Classification FromClassification;
5350   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5351     FromRecordType = PT->getPointeeType();
5352     DestType = Method->getThisType();
5353     FromClassification = Expr::Classification::makeSimpleLValue();
5354   } else {
5355     FromRecordType = From->getType();
5356     DestType = ImplicitParamRecordType;
5357     FromClassification = From->Classify(Context);
5358 
5359     // When performing member access on an rvalue, materialize a temporary.
5360     if (From->isRValue()) {
5361       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5362                                             Method->getRefQualifier() !=
5363                                                 RefQualifierKind::RQ_RValue);
5364     }
5365   }
5366 
5367   // Note that we always use the true parent context when performing
5368   // the actual argument initialization.
5369   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5370       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5371       Method->getParent());
5372   if (ICS.isBad()) {
5373     switch (ICS.Bad.Kind) {
5374     case BadConversionSequence::bad_qualifiers: {
5375       Qualifiers FromQs = FromRecordType.getQualifiers();
5376       Qualifiers ToQs = DestType.getQualifiers();
5377       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5378       if (CVR) {
5379         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5380             << Method->getDeclName() << FromRecordType << (CVR - 1)
5381             << From->getSourceRange();
5382         Diag(Method->getLocation(), diag::note_previous_decl)
5383           << Method->getDeclName();
5384         return ExprError();
5385       }
5386       break;
5387     }
5388 
5389     case BadConversionSequence::lvalue_ref_to_rvalue:
5390     case BadConversionSequence::rvalue_ref_to_lvalue: {
5391       bool IsRValueQualified =
5392         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5393       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5394           << Method->getDeclName() << FromClassification.isRValue()
5395           << IsRValueQualified;
5396       Diag(Method->getLocation(), diag::note_previous_decl)
5397         << Method->getDeclName();
5398       return ExprError();
5399     }
5400 
5401     case BadConversionSequence::no_conversion:
5402     case BadConversionSequence::unrelated_class:
5403       break;
5404     }
5405 
5406     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5407            << ImplicitParamRecordType << FromRecordType
5408            << From->getSourceRange();
5409   }
5410 
5411   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5412     ExprResult FromRes =
5413       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5414     if (FromRes.isInvalid())
5415       return ExprError();
5416     From = FromRes.get();
5417   }
5418 
5419   if (!Context.hasSameType(From->getType(), DestType)) {
5420     CastKind CK;
5421     QualType PteeTy = DestType->getPointeeType();
5422     LangAS DestAS =
5423         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5424     if (FromRecordType.getAddressSpace() != DestAS)
5425       CK = CK_AddressSpaceConversion;
5426     else
5427       CK = CK_NoOp;
5428     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5429   }
5430   return From;
5431 }
5432 
5433 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5434 /// expression From to bool (C++0x [conv]p3).
5435 static ImplicitConversionSequence
5436 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5437   return TryImplicitConversion(S, From, S.Context.BoolTy,
5438                                /*SuppressUserConversions=*/false,
5439                                AllowedExplicit::Conversions,
5440                                /*InOverloadResolution=*/false,
5441                                /*CStyle=*/false,
5442                                /*AllowObjCWritebackConversion=*/false,
5443                                /*AllowObjCConversionOnExplicit=*/false);
5444 }
5445 
5446 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5447 /// of the expression From to bool (C++0x [conv]p3).
5448 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5449   if (checkPlaceholderForOverload(*this, From))
5450     return ExprError();
5451 
5452   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5453   if (!ICS.isBad())
5454     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5455 
5456   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5457     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5458            << From->getType() << From->getSourceRange();
5459   return ExprError();
5460 }
5461 
5462 /// Check that the specified conversion is permitted in a converted constant
5463 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5464 /// is acceptable.
5465 static bool CheckConvertedConstantConversions(Sema &S,
5466                                               StandardConversionSequence &SCS) {
5467   // Since we know that the target type is an integral or unscoped enumeration
5468   // type, most conversion kinds are impossible. All possible First and Third
5469   // conversions are fine.
5470   switch (SCS.Second) {
5471   case ICK_Identity:
5472   case ICK_Function_Conversion:
5473   case ICK_Integral_Promotion:
5474   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5475   case ICK_Zero_Queue_Conversion:
5476     return true;
5477 
5478   case ICK_Boolean_Conversion:
5479     // Conversion from an integral or unscoped enumeration type to bool is
5480     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5481     // conversion, so we allow it in a converted constant expression.
5482     //
5483     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5484     // a lot of popular code. We should at least add a warning for this
5485     // (non-conforming) extension.
5486     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5487            SCS.getToType(2)->isBooleanType();
5488 
5489   case ICK_Pointer_Conversion:
5490   case ICK_Pointer_Member:
5491     // C++1z: null pointer conversions and null member pointer conversions are
5492     // only permitted if the source type is std::nullptr_t.
5493     return SCS.getFromType()->isNullPtrType();
5494 
5495   case ICK_Floating_Promotion:
5496   case ICK_Complex_Promotion:
5497   case ICK_Floating_Conversion:
5498   case ICK_Complex_Conversion:
5499   case ICK_Floating_Integral:
5500   case ICK_Compatible_Conversion:
5501   case ICK_Derived_To_Base:
5502   case ICK_Vector_Conversion:
5503   case ICK_Vector_Splat:
5504   case ICK_Complex_Real:
5505   case ICK_Block_Pointer_Conversion:
5506   case ICK_TransparentUnionConversion:
5507   case ICK_Writeback_Conversion:
5508   case ICK_Zero_Event_Conversion:
5509   case ICK_C_Only_Conversion:
5510   case ICK_Incompatible_Pointer_Conversion:
5511     return false;
5512 
5513   case ICK_Lvalue_To_Rvalue:
5514   case ICK_Array_To_Pointer:
5515   case ICK_Function_To_Pointer:
5516     llvm_unreachable("found a first conversion kind in Second");
5517 
5518   case ICK_Qualification:
5519     llvm_unreachable("found a third conversion kind in Second");
5520 
5521   case ICK_Num_Conversion_Kinds:
5522     break;
5523   }
5524 
5525   llvm_unreachable("unknown conversion kind");
5526 }
5527 
5528 /// CheckConvertedConstantExpression - Check that the expression From is a
5529 /// converted constant expression of type T, perform the conversion and produce
5530 /// the converted expression, per C++11 [expr.const]p3.
5531 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5532                                                    QualType T, APValue &Value,
5533                                                    Sema::CCEKind CCE,
5534                                                    bool RequireInt) {
5535   assert(S.getLangOpts().CPlusPlus11 &&
5536          "converted constant expression outside C++11");
5537 
5538   if (checkPlaceholderForOverload(S, From))
5539     return ExprError();
5540 
5541   // C++1z [expr.const]p3:
5542   //  A converted constant expression of type T is an expression,
5543   //  implicitly converted to type T, where the converted
5544   //  expression is a constant expression and the implicit conversion
5545   //  sequence contains only [... list of conversions ...].
5546   // C++1z [stmt.if]p2:
5547   //  If the if statement is of the form if constexpr, the value of the
5548   //  condition shall be a contextually converted constant expression of type
5549   //  bool.
5550   ImplicitConversionSequence ICS =
5551       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5552           ? TryContextuallyConvertToBool(S, From)
5553           : TryCopyInitialization(S, From, T,
5554                                   /*SuppressUserConversions=*/false,
5555                                   /*InOverloadResolution=*/false,
5556                                   /*AllowObjCWritebackConversion=*/false,
5557                                   /*AllowExplicit=*/false);
5558   StandardConversionSequence *SCS = nullptr;
5559   switch (ICS.getKind()) {
5560   case ImplicitConversionSequence::StandardConversion:
5561     SCS = &ICS.Standard;
5562     break;
5563   case ImplicitConversionSequence::UserDefinedConversion:
5564     // We are converting to a non-class type, so the Before sequence
5565     // must be trivial.
5566     SCS = &ICS.UserDefined.After;
5567     break;
5568   case ImplicitConversionSequence::AmbiguousConversion:
5569   case ImplicitConversionSequence::BadConversion:
5570     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5571       return S.Diag(From->getBeginLoc(),
5572                     diag::err_typecheck_converted_constant_expression)
5573              << From->getType() << From->getSourceRange() << T;
5574     return ExprError();
5575 
5576   case ImplicitConversionSequence::EllipsisConversion:
5577     llvm_unreachable("ellipsis conversion in converted constant expression");
5578   }
5579 
5580   // Check that we would only use permitted conversions.
5581   if (!CheckConvertedConstantConversions(S, *SCS)) {
5582     return S.Diag(From->getBeginLoc(),
5583                   diag::err_typecheck_converted_constant_expression_disallowed)
5584            << From->getType() << From->getSourceRange() << T;
5585   }
5586   // [...] and where the reference binding (if any) binds directly.
5587   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5588     return S.Diag(From->getBeginLoc(),
5589                   diag::err_typecheck_converted_constant_expression_indirect)
5590            << From->getType() << From->getSourceRange() << T;
5591   }
5592 
5593   ExprResult Result =
5594       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5595   if (Result.isInvalid())
5596     return Result;
5597 
5598   // C++2a [intro.execution]p5:
5599   //   A full-expression is [...] a constant-expression [...]
5600   Result =
5601       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5602                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5603   if (Result.isInvalid())
5604     return Result;
5605 
5606   // Check for a narrowing implicit conversion.
5607   APValue PreNarrowingValue;
5608   QualType PreNarrowingType;
5609   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5610                                 PreNarrowingType)) {
5611   case NK_Dependent_Narrowing:
5612     // Implicit conversion to a narrower type, but the expression is
5613     // value-dependent so we can't tell whether it's actually narrowing.
5614   case NK_Variable_Narrowing:
5615     // Implicit conversion to a narrower type, and the value is not a constant
5616     // expression. We'll diagnose this in a moment.
5617   case NK_Not_Narrowing:
5618     break;
5619 
5620   case NK_Constant_Narrowing:
5621     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5622         << CCE << /*Constant*/ 1
5623         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5624     break;
5625 
5626   case NK_Type_Narrowing:
5627     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5628         << CCE << /*Constant*/ 0 << From->getType() << T;
5629     break;
5630   }
5631 
5632   if (Result.get()->isValueDependent()) {
5633     Value = APValue();
5634     return Result;
5635   }
5636 
5637   // Check the expression is a constant expression.
5638   SmallVector<PartialDiagnosticAt, 8> Notes;
5639   Expr::EvalResult Eval;
5640   Eval.Diag = &Notes;
5641   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5642                                    ? Expr::EvaluateForMangling
5643                                    : Expr::EvaluateForCodeGen;
5644 
5645   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5646       (RequireInt && !Eval.Val.isInt())) {
5647     // The expression can't be folded, so we can't keep it at this position in
5648     // the AST.
5649     Result = ExprError();
5650   } else {
5651     Value = Eval.Val;
5652 
5653     if (Notes.empty()) {
5654       // It's a constant expression.
5655       return ConstantExpr::Create(S.Context, Result.get(), Value);
5656     }
5657   }
5658 
5659   // It's not a constant expression. Produce an appropriate diagnostic.
5660   if (Notes.size() == 1 &&
5661       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5662     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5663   else {
5664     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5665         << CCE << From->getSourceRange();
5666     for (unsigned I = 0; I < Notes.size(); ++I)
5667       S.Diag(Notes[I].first, Notes[I].second);
5668   }
5669   return ExprError();
5670 }
5671 
5672 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5673                                                   APValue &Value, CCEKind CCE) {
5674   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5675 }
5676 
5677 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5678                                                   llvm::APSInt &Value,
5679                                                   CCEKind CCE) {
5680   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5681 
5682   APValue V;
5683   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5684   if (!R.isInvalid() && !R.get()->isValueDependent())
5685     Value = V.getInt();
5686   return R;
5687 }
5688 
5689 
5690 /// dropPointerConversions - If the given standard conversion sequence
5691 /// involves any pointer conversions, remove them.  This may change
5692 /// the result type of the conversion sequence.
5693 static void dropPointerConversion(StandardConversionSequence &SCS) {
5694   if (SCS.Second == ICK_Pointer_Conversion) {
5695     SCS.Second = ICK_Identity;
5696     SCS.Third = ICK_Identity;
5697     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5698   }
5699 }
5700 
5701 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5702 /// convert the expression From to an Objective-C pointer type.
5703 static ImplicitConversionSequence
5704 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5705   // Do an implicit conversion to 'id'.
5706   QualType Ty = S.Context.getObjCIdType();
5707   ImplicitConversionSequence ICS
5708     = TryImplicitConversion(S, From, Ty,
5709                             // FIXME: Are these flags correct?
5710                             /*SuppressUserConversions=*/false,
5711                             AllowedExplicit::Conversions,
5712                             /*InOverloadResolution=*/false,
5713                             /*CStyle=*/false,
5714                             /*AllowObjCWritebackConversion=*/false,
5715                             /*AllowObjCConversionOnExplicit=*/true);
5716 
5717   // Strip off any final conversions to 'id'.
5718   switch (ICS.getKind()) {
5719   case ImplicitConversionSequence::BadConversion:
5720   case ImplicitConversionSequence::AmbiguousConversion:
5721   case ImplicitConversionSequence::EllipsisConversion:
5722     break;
5723 
5724   case ImplicitConversionSequence::UserDefinedConversion:
5725     dropPointerConversion(ICS.UserDefined.After);
5726     break;
5727 
5728   case ImplicitConversionSequence::StandardConversion:
5729     dropPointerConversion(ICS.Standard);
5730     break;
5731   }
5732 
5733   return ICS;
5734 }
5735 
5736 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5737 /// conversion of the expression From to an Objective-C pointer type.
5738 /// Returns a valid but null ExprResult if no conversion sequence exists.
5739 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5740   if (checkPlaceholderForOverload(*this, From))
5741     return ExprError();
5742 
5743   QualType Ty = Context.getObjCIdType();
5744   ImplicitConversionSequence ICS =
5745     TryContextuallyConvertToObjCPointer(*this, From);
5746   if (!ICS.isBad())
5747     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5748   return ExprResult();
5749 }
5750 
5751 /// Determine whether the provided type is an integral type, or an enumeration
5752 /// type of a permitted flavor.
5753 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5754   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5755                                  : T->isIntegralOrUnscopedEnumerationType();
5756 }
5757 
5758 static ExprResult
5759 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5760                             Sema::ContextualImplicitConverter &Converter,
5761                             QualType T, UnresolvedSetImpl &ViableConversions) {
5762 
5763   if (Converter.Suppress)
5764     return ExprError();
5765 
5766   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5767   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5768     CXXConversionDecl *Conv =
5769         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5770     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5771     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5772   }
5773   return From;
5774 }
5775 
5776 static bool
5777 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5778                            Sema::ContextualImplicitConverter &Converter,
5779                            QualType T, bool HadMultipleCandidates,
5780                            UnresolvedSetImpl &ExplicitConversions) {
5781   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5782     DeclAccessPair Found = ExplicitConversions[0];
5783     CXXConversionDecl *Conversion =
5784         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5785 
5786     // The user probably meant to invoke the given explicit
5787     // conversion; use it.
5788     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5789     std::string TypeStr;
5790     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5791 
5792     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5793         << FixItHint::CreateInsertion(From->getBeginLoc(),
5794                                       "static_cast<" + TypeStr + ">(")
5795         << FixItHint::CreateInsertion(
5796                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5797     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5798 
5799     // If we aren't in a SFINAE context, build a call to the
5800     // explicit conversion function.
5801     if (SemaRef.isSFINAEContext())
5802       return true;
5803 
5804     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5805     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5806                                                        HadMultipleCandidates);
5807     if (Result.isInvalid())
5808       return true;
5809     // Record usage of conversion in an implicit cast.
5810     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5811                                     CK_UserDefinedConversion, Result.get(),
5812                                     nullptr, Result.get()->getValueKind());
5813   }
5814   return false;
5815 }
5816 
5817 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5818                              Sema::ContextualImplicitConverter &Converter,
5819                              QualType T, bool HadMultipleCandidates,
5820                              DeclAccessPair &Found) {
5821   CXXConversionDecl *Conversion =
5822       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5823   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5824 
5825   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5826   if (!Converter.SuppressConversion) {
5827     if (SemaRef.isSFINAEContext())
5828       return true;
5829 
5830     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5831         << From->getSourceRange();
5832   }
5833 
5834   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5835                                                      HadMultipleCandidates);
5836   if (Result.isInvalid())
5837     return true;
5838   // Record usage of conversion in an implicit cast.
5839   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5840                                   CK_UserDefinedConversion, Result.get(),
5841                                   nullptr, Result.get()->getValueKind());
5842   return false;
5843 }
5844 
5845 static ExprResult finishContextualImplicitConversion(
5846     Sema &SemaRef, SourceLocation Loc, Expr *From,
5847     Sema::ContextualImplicitConverter &Converter) {
5848   if (!Converter.match(From->getType()) && !Converter.Suppress)
5849     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5850         << From->getSourceRange();
5851 
5852   return SemaRef.DefaultLvalueConversion(From);
5853 }
5854 
5855 static void
5856 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5857                                   UnresolvedSetImpl &ViableConversions,
5858                                   OverloadCandidateSet &CandidateSet) {
5859   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5860     DeclAccessPair FoundDecl = ViableConversions[I];
5861     NamedDecl *D = FoundDecl.getDecl();
5862     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5863     if (isa<UsingShadowDecl>(D))
5864       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5865 
5866     CXXConversionDecl *Conv;
5867     FunctionTemplateDecl *ConvTemplate;
5868     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5869       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5870     else
5871       Conv = cast<CXXConversionDecl>(D);
5872 
5873     if (ConvTemplate)
5874       SemaRef.AddTemplateConversionCandidate(
5875           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5876           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5877     else
5878       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5879                                      ToType, CandidateSet,
5880                                      /*AllowObjCConversionOnExplicit=*/false,
5881                                      /*AllowExplicit*/ true);
5882   }
5883 }
5884 
5885 /// Attempt to convert the given expression to a type which is accepted
5886 /// by the given converter.
5887 ///
5888 /// This routine will attempt to convert an expression of class type to a
5889 /// type accepted by the specified converter. In C++11 and before, the class
5890 /// must have a single non-explicit conversion function converting to a matching
5891 /// type. In C++1y, there can be multiple such conversion functions, but only
5892 /// one target type.
5893 ///
5894 /// \param Loc The source location of the construct that requires the
5895 /// conversion.
5896 ///
5897 /// \param From The expression we're converting from.
5898 ///
5899 /// \param Converter Used to control and diagnose the conversion process.
5900 ///
5901 /// \returns The expression, converted to an integral or enumeration type if
5902 /// successful.
5903 ExprResult Sema::PerformContextualImplicitConversion(
5904     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5905   // We can't perform any more checking for type-dependent expressions.
5906   if (From->isTypeDependent())
5907     return From;
5908 
5909   // Process placeholders immediately.
5910   if (From->hasPlaceholderType()) {
5911     ExprResult result = CheckPlaceholderExpr(From);
5912     if (result.isInvalid())
5913       return result;
5914     From = result.get();
5915   }
5916 
5917   // If the expression already has a matching type, we're golden.
5918   QualType T = From->getType();
5919   if (Converter.match(T))
5920     return DefaultLvalueConversion(From);
5921 
5922   // FIXME: Check for missing '()' if T is a function type?
5923 
5924   // We can only perform contextual implicit conversions on objects of class
5925   // type.
5926   const RecordType *RecordTy = T->getAs<RecordType>();
5927   if (!RecordTy || !getLangOpts().CPlusPlus) {
5928     if (!Converter.Suppress)
5929       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5930     return From;
5931   }
5932 
5933   // We must have a complete class type.
5934   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5935     ContextualImplicitConverter &Converter;
5936     Expr *From;
5937 
5938     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5939         : Converter(Converter), From(From) {}
5940 
5941     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5942       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5943     }
5944   } IncompleteDiagnoser(Converter, From);
5945 
5946   if (Converter.Suppress ? !isCompleteType(Loc, T)
5947                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5948     return From;
5949 
5950   // Look for a conversion to an integral or enumeration type.
5951   UnresolvedSet<4>
5952       ViableConversions; // These are *potentially* viable in C++1y.
5953   UnresolvedSet<4> ExplicitConversions;
5954   const auto &Conversions =
5955       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5956 
5957   bool HadMultipleCandidates =
5958       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5959 
5960   // To check that there is only one target type, in C++1y:
5961   QualType ToType;
5962   bool HasUniqueTargetType = true;
5963 
5964   // Collect explicit or viable (potentially in C++1y) conversions.
5965   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5966     NamedDecl *D = (*I)->getUnderlyingDecl();
5967     CXXConversionDecl *Conversion;
5968     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5969     if (ConvTemplate) {
5970       if (getLangOpts().CPlusPlus14)
5971         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5972       else
5973         continue; // C++11 does not consider conversion operator templates(?).
5974     } else
5975       Conversion = cast<CXXConversionDecl>(D);
5976 
5977     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5978            "Conversion operator templates are considered potentially "
5979            "viable in C++1y");
5980 
5981     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5982     if (Converter.match(CurToType) || ConvTemplate) {
5983 
5984       if (Conversion->isExplicit()) {
5985         // FIXME: For C++1y, do we need this restriction?
5986         // cf. diagnoseNoViableConversion()
5987         if (!ConvTemplate)
5988           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5989       } else {
5990         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5991           if (ToType.isNull())
5992             ToType = CurToType.getUnqualifiedType();
5993           else if (HasUniqueTargetType &&
5994                    (CurToType.getUnqualifiedType() != ToType))
5995             HasUniqueTargetType = false;
5996         }
5997         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5998       }
5999     }
6000   }
6001 
6002   if (getLangOpts().CPlusPlus14) {
6003     // C++1y [conv]p6:
6004     // ... An expression e of class type E appearing in such a context
6005     // is said to be contextually implicitly converted to a specified
6006     // type T and is well-formed if and only if e can be implicitly
6007     // converted to a type T that is determined as follows: E is searched
6008     // for conversion functions whose return type is cv T or reference to
6009     // cv T such that T is allowed by the context. There shall be
6010     // exactly one such T.
6011 
6012     // If no unique T is found:
6013     if (ToType.isNull()) {
6014       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6015                                      HadMultipleCandidates,
6016                                      ExplicitConversions))
6017         return ExprError();
6018       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6019     }
6020 
6021     // If more than one unique Ts are found:
6022     if (!HasUniqueTargetType)
6023       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6024                                          ViableConversions);
6025 
6026     // If one unique T is found:
6027     // First, build a candidate set from the previously recorded
6028     // potentially viable conversions.
6029     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6030     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6031                                       CandidateSet);
6032 
6033     // Then, perform overload resolution over the candidate set.
6034     OverloadCandidateSet::iterator Best;
6035     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6036     case OR_Success: {
6037       // Apply this conversion.
6038       DeclAccessPair Found =
6039           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6040       if (recordConversion(*this, Loc, From, Converter, T,
6041                            HadMultipleCandidates, Found))
6042         return ExprError();
6043       break;
6044     }
6045     case OR_Ambiguous:
6046       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6047                                          ViableConversions);
6048     case OR_No_Viable_Function:
6049       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6050                                      HadMultipleCandidates,
6051                                      ExplicitConversions))
6052         return ExprError();
6053       LLVM_FALLTHROUGH;
6054     case OR_Deleted:
6055       // We'll complain below about a non-integral condition type.
6056       break;
6057     }
6058   } else {
6059     switch (ViableConversions.size()) {
6060     case 0: {
6061       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6062                                      HadMultipleCandidates,
6063                                      ExplicitConversions))
6064         return ExprError();
6065 
6066       // We'll complain below about a non-integral condition type.
6067       break;
6068     }
6069     case 1: {
6070       // Apply this conversion.
6071       DeclAccessPair Found = ViableConversions[0];
6072       if (recordConversion(*this, Loc, From, Converter, T,
6073                            HadMultipleCandidates, Found))
6074         return ExprError();
6075       break;
6076     }
6077     default:
6078       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6079                                          ViableConversions);
6080     }
6081   }
6082 
6083   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6084 }
6085 
6086 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6087 /// an acceptable non-member overloaded operator for a call whose
6088 /// arguments have types T1 (and, if non-empty, T2). This routine
6089 /// implements the check in C++ [over.match.oper]p3b2 concerning
6090 /// enumeration types.
6091 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6092                                                    FunctionDecl *Fn,
6093                                                    ArrayRef<Expr *> Args) {
6094   QualType T1 = Args[0]->getType();
6095   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6096 
6097   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6098     return true;
6099 
6100   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6101     return true;
6102 
6103   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6104   if (Proto->getNumParams() < 1)
6105     return false;
6106 
6107   if (T1->isEnumeralType()) {
6108     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6109     if (Context.hasSameUnqualifiedType(T1, ArgType))
6110       return true;
6111   }
6112 
6113   if (Proto->getNumParams() < 2)
6114     return false;
6115 
6116   if (!T2.isNull() && T2->isEnumeralType()) {
6117     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6118     if (Context.hasSameUnqualifiedType(T2, ArgType))
6119       return true;
6120   }
6121 
6122   return false;
6123 }
6124 
6125 /// AddOverloadCandidate - Adds the given function to the set of
6126 /// candidate functions, using the given function call arguments.  If
6127 /// @p SuppressUserConversions, then don't allow user-defined
6128 /// conversions via constructors or conversion operators.
6129 ///
6130 /// \param PartialOverloading true if we are performing "partial" overloading
6131 /// based on an incomplete set of function arguments. This feature is used by
6132 /// code completion.
6133 void Sema::AddOverloadCandidate(
6134     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6135     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6136     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6137     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6138     OverloadCandidateParamOrder PO) {
6139   const FunctionProtoType *Proto
6140     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6141   assert(Proto && "Functions without a prototype cannot be overloaded");
6142   assert(!Function->getDescribedFunctionTemplate() &&
6143          "Use AddTemplateOverloadCandidate for function templates");
6144 
6145   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6146     if (!isa<CXXConstructorDecl>(Method)) {
6147       // If we get here, it's because we're calling a member function
6148       // that is named without a member access expression (e.g.,
6149       // "this->f") that was either written explicitly or created
6150       // implicitly. This can happen with a qualified call to a member
6151       // function, e.g., X::f(). We use an empty type for the implied
6152       // object argument (C++ [over.call.func]p3), and the acting context
6153       // is irrelevant.
6154       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6155                          Expr::Classification::makeSimpleLValue(), Args,
6156                          CandidateSet, SuppressUserConversions,
6157                          PartialOverloading, EarlyConversions, PO);
6158       return;
6159     }
6160     // We treat a constructor like a non-member function, since its object
6161     // argument doesn't participate in overload resolution.
6162   }
6163 
6164   if (!CandidateSet.isNewCandidate(Function, PO))
6165     return;
6166 
6167   // C++11 [class.copy]p11: [DR1402]
6168   //   A defaulted move constructor that is defined as deleted is ignored by
6169   //   overload resolution.
6170   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6171   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6172       Constructor->isMoveConstructor())
6173     return;
6174 
6175   // Overload resolution is always an unevaluated context.
6176   EnterExpressionEvaluationContext Unevaluated(
6177       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6178 
6179   // C++ [over.match.oper]p3:
6180   //   if no operand has a class type, only those non-member functions in the
6181   //   lookup set that have a first parameter of type T1 or "reference to
6182   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6183   //   is a right operand) a second parameter of type T2 or "reference to
6184   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6185   //   candidate functions.
6186   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6187       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6188     return;
6189 
6190   // Add this candidate
6191   OverloadCandidate &Candidate =
6192       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6193   Candidate.FoundDecl = FoundDecl;
6194   Candidate.Function = Function;
6195   Candidate.Viable = true;
6196   Candidate.RewriteKind =
6197       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6198   Candidate.IsSurrogate = false;
6199   Candidate.IsADLCandidate = IsADLCandidate;
6200   Candidate.IgnoreObjectArgument = false;
6201   Candidate.ExplicitCallArguments = Args.size();
6202 
6203   // Explicit functions are not actually candidates at all if we're not
6204   // allowing them in this context, but keep them around so we can point
6205   // to them in diagnostics.
6206   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6207     Candidate.Viable = false;
6208     Candidate.FailureKind = ovl_fail_explicit;
6209     return;
6210   }
6211 
6212   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6213       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6214     Candidate.Viable = false;
6215     Candidate.FailureKind = ovl_non_default_multiversion_function;
6216     return;
6217   }
6218 
6219   if (Constructor) {
6220     // C++ [class.copy]p3:
6221     //   A member function template is never instantiated to perform the copy
6222     //   of a class object to an object of its class type.
6223     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6224     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6225         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6226          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6227                        ClassType))) {
6228       Candidate.Viable = false;
6229       Candidate.FailureKind = ovl_fail_illegal_constructor;
6230       return;
6231     }
6232 
6233     // C++ [over.match.funcs]p8: (proposed DR resolution)
6234     //   A constructor inherited from class type C that has a first parameter
6235     //   of type "reference to P" (including such a constructor instantiated
6236     //   from a template) is excluded from the set of candidate functions when
6237     //   constructing an object of type cv D if the argument list has exactly
6238     //   one argument and D is reference-related to P and P is reference-related
6239     //   to C.
6240     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6241     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6242         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6243       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6244       QualType C = Context.getRecordType(Constructor->getParent());
6245       QualType D = Context.getRecordType(Shadow->getParent());
6246       SourceLocation Loc = Args.front()->getExprLoc();
6247       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6248           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6249         Candidate.Viable = false;
6250         Candidate.FailureKind = ovl_fail_inhctor_slice;
6251         return;
6252       }
6253     }
6254 
6255     // Check that the constructor is capable of constructing an object in the
6256     // destination address space.
6257     if (!Qualifiers::isAddressSpaceSupersetOf(
6258             Constructor->getMethodQualifiers().getAddressSpace(),
6259             CandidateSet.getDestAS())) {
6260       Candidate.Viable = false;
6261       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6262     }
6263   }
6264 
6265   unsigned NumParams = Proto->getNumParams();
6266 
6267   // (C++ 13.3.2p2): A candidate function having fewer than m
6268   // parameters is viable only if it has an ellipsis in its parameter
6269   // list (8.3.5).
6270   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6271       !Proto->isVariadic()) {
6272     Candidate.Viable = false;
6273     Candidate.FailureKind = ovl_fail_too_many_arguments;
6274     return;
6275   }
6276 
6277   // (C++ 13.3.2p2): A candidate function having more than m parameters
6278   // is viable only if the (m+1)st parameter has a default argument
6279   // (8.3.6). For the purposes of overload resolution, the
6280   // parameter list is truncated on the right, so that there are
6281   // exactly m parameters.
6282   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6283   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6284     // Not enough arguments.
6285     Candidate.Viable = false;
6286     Candidate.FailureKind = ovl_fail_too_few_arguments;
6287     return;
6288   }
6289 
6290   // (CUDA B.1): Check for invalid calls between targets.
6291   if (getLangOpts().CUDA)
6292     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6293       // Skip the check for callers that are implicit members, because in this
6294       // case we may not yet know what the member's target is; the target is
6295       // inferred for the member automatically, based on the bases and fields of
6296       // the class.
6297       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6298         Candidate.Viable = false;
6299         Candidate.FailureKind = ovl_fail_bad_target;
6300         return;
6301       }
6302 
6303   if (Function->getTrailingRequiresClause()) {
6304     ConstraintSatisfaction Satisfaction;
6305     if (CheckFunctionConstraints(Function, Satisfaction) ||
6306         !Satisfaction.IsSatisfied) {
6307       Candidate.Viable = false;
6308       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6309       return;
6310     }
6311   }
6312 
6313   // Determine the implicit conversion sequences for each of the
6314   // arguments.
6315   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6316     unsigned ConvIdx =
6317         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6318     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6319       // We already formed a conversion sequence for this parameter during
6320       // template argument deduction.
6321     } else if (ArgIdx < NumParams) {
6322       // (C++ 13.3.2p3): for F to be a viable function, there shall
6323       // exist for each argument an implicit conversion sequence
6324       // (13.3.3.1) that converts that argument to the corresponding
6325       // parameter of F.
6326       QualType ParamType = Proto->getParamType(ArgIdx);
6327       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6328           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6329           /*InOverloadResolution=*/true,
6330           /*AllowObjCWritebackConversion=*/
6331           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6332       if (Candidate.Conversions[ConvIdx].isBad()) {
6333         Candidate.Viable = false;
6334         Candidate.FailureKind = ovl_fail_bad_conversion;
6335         return;
6336       }
6337     } else {
6338       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6339       // argument for which there is no corresponding parameter is
6340       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6341       Candidate.Conversions[ConvIdx].setEllipsis();
6342     }
6343   }
6344 
6345   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6346     Candidate.Viable = false;
6347     Candidate.FailureKind = ovl_fail_enable_if;
6348     Candidate.DeductionFailure.Data = FailedAttr;
6349     return;
6350   }
6351 
6352   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6353     Candidate.Viable = false;
6354     Candidate.FailureKind = ovl_fail_ext_disabled;
6355     return;
6356   }
6357 }
6358 
6359 ObjCMethodDecl *
6360 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6361                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6362   if (Methods.size() <= 1)
6363     return nullptr;
6364 
6365   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6366     bool Match = true;
6367     ObjCMethodDecl *Method = Methods[b];
6368     unsigned NumNamedArgs = Sel.getNumArgs();
6369     // Method might have more arguments than selector indicates. This is due
6370     // to addition of c-style arguments in method.
6371     if (Method->param_size() > NumNamedArgs)
6372       NumNamedArgs = Method->param_size();
6373     if (Args.size() < NumNamedArgs)
6374       continue;
6375 
6376     for (unsigned i = 0; i < NumNamedArgs; i++) {
6377       // We can't do any type-checking on a type-dependent argument.
6378       if (Args[i]->isTypeDependent()) {
6379         Match = false;
6380         break;
6381       }
6382 
6383       ParmVarDecl *param = Method->parameters()[i];
6384       Expr *argExpr = Args[i];
6385       assert(argExpr && "SelectBestMethod(): missing expression");
6386 
6387       // Strip the unbridged-cast placeholder expression off unless it's
6388       // a consumed argument.
6389       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6390           !param->hasAttr<CFConsumedAttr>())
6391         argExpr = stripARCUnbridgedCast(argExpr);
6392 
6393       // If the parameter is __unknown_anytype, move on to the next method.
6394       if (param->getType() == Context.UnknownAnyTy) {
6395         Match = false;
6396         break;
6397       }
6398 
6399       ImplicitConversionSequence ConversionState
6400         = TryCopyInitialization(*this, argExpr, param->getType(),
6401                                 /*SuppressUserConversions*/false,
6402                                 /*InOverloadResolution=*/true,
6403                                 /*AllowObjCWritebackConversion=*/
6404                                 getLangOpts().ObjCAutoRefCount,
6405                                 /*AllowExplicit*/false);
6406       // This function looks for a reasonably-exact match, so we consider
6407       // incompatible pointer conversions to be a failure here.
6408       if (ConversionState.isBad() ||
6409           (ConversionState.isStandard() &&
6410            ConversionState.Standard.Second ==
6411                ICK_Incompatible_Pointer_Conversion)) {
6412         Match = false;
6413         break;
6414       }
6415     }
6416     // Promote additional arguments to variadic methods.
6417     if (Match && Method->isVariadic()) {
6418       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6419         if (Args[i]->isTypeDependent()) {
6420           Match = false;
6421           break;
6422         }
6423         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6424                                                           nullptr);
6425         if (Arg.isInvalid()) {
6426           Match = false;
6427           break;
6428         }
6429       }
6430     } else {
6431       // Check for extra arguments to non-variadic methods.
6432       if (Args.size() != NumNamedArgs)
6433         Match = false;
6434       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6435         // Special case when selectors have no argument. In this case, select
6436         // one with the most general result type of 'id'.
6437         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6438           QualType ReturnT = Methods[b]->getReturnType();
6439           if (ReturnT->isObjCIdType())
6440             return Methods[b];
6441         }
6442       }
6443     }
6444 
6445     if (Match)
6446       return Method;
6447   }
6448   return nullptr;
6449 }
6450 
6451 static bool
6452 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6453                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6454                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6455                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6456   if (ThisArg) {
6457     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6458     assert(!isa<CXXConstructorDecl>(Method) &&
6459            "Shouldn't have `this` for ctors!");
6460     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6461     ExprResult R = S.PerformObjectArgumentInitialization(
6462         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6463     if (R.isInvalid())
6464       return false;
6465     ConvertedThis = R.get();
6466   } else {
6467     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6468       (void)MD;
6469       assert((MissingImplicitThis || MD->isStatic() ||
6470               isa<CXXConstructorDecl>(MD)) &&
6471              "Expected `this` for non-ctor instance methods");
6472     }
6473     ConvertedThis = nullptr;
6474   }
6475 
6476   // Ignore any variadic arguments. Converting them is pointless, since the
6477   // user can't refer to them in the function condition.
6478   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6479 
6480   // Convert the arguments.
6481   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6482     ExprResult R;
6483     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6484                                         S.Context, Function->getParamDecl(I)),
6485                                     SourceLocation(), Args[I]);
6486 
6487     if (R.isInvalid())
6488       return false;
6489 
6490     ConvertedArgs.push_back(R.get());
6491   }
6492 
6493   if (Trap.hasErrorOccurred())
6494     return false;
6495 
6496   // Push default arguments if needed.
6497   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6498     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6499       ParmVarDecl *P = Function->getParamDecl(i);
6500       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6501                          ? P->getUninstantiatedDefaultArg()
6502                          : P->getDefaultArg();
6503       // This can only happen in code completion, i.e. when PartialOverloading
6504       // is true.
6505       if (!DefArg)
6506         return false;
6507       ExprResult R =
6508           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6509                                           S.Context, Function->getParamDecl(i)),
6510                                       SourceLocation(), DefArg);
6511       if (R.isInvalid())
6512         return false;
6513       ConvertedArgs.push_back(R.get());
6514     }
6515 
6516     if (Trap.hasErrorOccurred())
6517       return false;
6518   }
6519   return true;
6520 }
6521 
6522 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6523                                   bool MissingImplicitThis) {
6524   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6525   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6526     return nullptr;
6527 
6528   SFINAETrap Trap(*this);
6529   SmallVector<Expr *, 16> ConvertedArgs;
6530   // FIXME: We should look into making enable_if late-parsed.
6531   Expr *DiscardedThis;
6532   if (!convertArgsForAvailabilityChecks(
6533           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6534           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6535     return *EnableIfAttrs.begin();
6536 
6537   for (auto *EIA : EnableIfAttrs) {
6538     APValue Result;
6539     // FIXME: This doesn't consider value-dependent cases, because doing so is
6540     // very difficult. Ideally, we should handle them more gracefully.
6541     if (EIA->getCond()->isValueDependent() ||
6542         !EIA->getCond()->EvaluateWithSubstitution(
6543             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6544       return EIA;
6545 
6546     if (!Result.isInt() || !Result.getInt().getBoolValue())
6547       return EIA;
6548   }
6549   return nullptr;
6550 }
6551 
6552 template <typename CheckFn>
6553 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6554                                         bool ArgDependent, SourceLocation Loc,
6555                                         CheckFn &&IsSuccessful) {
6556   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6557   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6558     if (ArgDependent == DIA->getArgDependent())
6559       Attrs.push_back(DIA);
6560   }
6561 
6562   // Common case: No diagnose_if attributes, so we can quit early.
6563   if (Attrs.empty())
6564     return false;
6565 
6566   auto WarningBegin = std::stable_partition(
6567       Attrs.begin(), Attrs.end(),
6568       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6569 
6570   // Note that diagnose_if attributes are late-parsed, so they appear in the
6571   // correct order (unlike enable_if attributes).
6572   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6573                                IsSuccessful);
6574   if (ErrAttr != WarningBegin) {
6575     const DiagnoseIfAttr *DIA = *ErrAttr;
6576     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6577     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6578         << DIA->getParent() << DIA->getCond()->getSourceRange();
6579     return true;
6580   }
6581 
6582   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6583     if (IsSuccessful(DIA)) {
6584       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6585       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6586           << DIA->getParent() << DIA->getCond()->getSourceRange();
6587     }
6588 
6589   return false;
6590 }
6591 
6592 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6593                                                const Expr *ThisArg,
6594                                                ArrayRef<const Expr *> Args,
6595                                                SourceLocation Loc) {
6596   return diagnoseDiagnoseIfAttrsWith(
6597       *this, Function, /*ArgDependent=*/true, Loc,
6598       [&](const DiagnoseIfAttr *DIA) {
6599         APValue Result;
6600         // It's sane to use the same Args for any redecl of this function, since
6601         // EvaluateWithSubstitution only cares about the position of each
6602         // argument in the arg list, not the ParmVarDecl* it maps to.
6603         if (!DIA->getCond()->EvaluateWithSubstitution(
6604                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6605           return false;
6606         return Result.isInt() && Result.getInt().getBoolValue();
6607       });
6608 }
6609 
6610 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6611                                                  SourceLocation Loc) {
6612   return diagnoseDiagnoseIfAttrsWith(
6613       *this, ND, /*ArgDependent=*/false, Loc,
6614       [&](const DiagnoseIfAttr *DIA) {
6615         bool Result;
6616         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6617                Result;
6618       });
6619 }
6620 
6621 /// Add all of the function declarations in the given function set to
6622 /// the overload candidate set.
6623 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6624                                  ArrayRef<Expr *> Args,
6625                                  OverloadCandidateSet &CandidateSet,
6626                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6627                                  bool SuppressUserConversions,
6628                                  bool PartialOverloading,
6629                                  bool FirstArgumentIsBase) {
6630   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6631     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6632     ArrayRef<Expr *> FunctionArgs = Args;
6633 
6634     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6635     FunctionDecl *FD =
6636         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6637 
6638     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6639       QualType ObjectType;
6640       Expr::Classification ObjectClassification;
6641       if (Args.size() > 0) {
6642         if (Expr *E = Args[0]) {
6643           // Use the explicit base to restrict the lookup:
6644           ObjectType = E->getType();
6645           // Pointers in the object arguments are implicitly dereferenced, so we
6646           // always classify them as l-values.
6647           if (!ObjectType.isNull() && ObjectType->isPointerType())
6648             ObjectClassification = Expr::Classification::makeSimpleLValue();
6649           else
6650             ObjectClassification = E->Classify(Context);
6651         } // .. else there is an implicit base.
6652         FunctionArgs = Args.slice(1);
6653       }
6654       if (FunTmpl) {
6655         AddMethodTemplateCandidate(
6656             FunTmpl, F.getPair(),
6657             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6658             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6659             FunctionArgs, CandidateSet, SuppressUserConversions,
6660             PartialOverloading);
6661       } else {
6662         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6663                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6664                            ObjectClassification, FunctionArgs, CandidateSet,
6665                            SuppressUserConversions, PartialOverloading);
6666       }
6667     } else {
6668       // This branch handles both standalone functions and static methods.
6669 
6670       // Slice the first argument (which is the base) when we access
6671       // static method as non-static.
6672       if (Args.size() > 0 &&
6673           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6674                         !isa<CXXConstructorDecl>(FD)))) {
6675         assert(cast<CXXMethodDecl>(FD)->isStatic());
6676         FunctionArgs = Args.slice(1);
6677       }
6678       if (FunTmpl) {
6679         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6680                                      ExplicitTemplateArgs, FunctionArgs,
6681                                      CandidateSet, SuppressUserConversions,
6682                                      PartialOverloading);
6683       } else {
6684         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6685                              SuppressUserConversions, PartialOverloading);
6686       }
6687     }
6688   }
6689 }
6690 
6691 /// AddMethodCandidate - Adds a named decl (which is some kind of
6692 /// method) as a method candidate to the given overload set.
6693 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6694                               Expr::Classification ObjectClassification,
6695                               ArrayRef<Expr *> Args,
6696                               OverloadCandidateSet &CandidateSet,
6697                               bool SuppressUserConversions,
6698                               OverloadCandidateParamOrder PO) {
6699   NamedDecl *Decl = FoundDecl.getDecl();
6700   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6701 
6702   if (isa<UsingShadowDecl>(Decl))
6703     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6704 
6705   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6706     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6707            "Expected a member function template");
6708     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6709                                /*ExplicitArgs*/ nullptr, ObjectType,
6710                                ObjectClassification, Args, CandidateSet,
6711                                SuppressUserConversions, false, PO);
6712   } else {
6713     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6714                        ObjectType, ObjectClassification, Args, CandidateSet,
6715                        SuppressUserConversions, false, None, PO);
6716   }
6717 }
6718 
6719 /// AddMethodCandidate - Adds the given C++ member function to the set
6720 /// of candidate functions, using the given function call arguments
6721 /// and the object argument (@c Object). For example, in a call
6722 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6723 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6724 /// allow user-defined conversions via constructors or conversion
6725 /// operators.
6726 void
6727 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6728                          CXXRecordDecl *ActingContext, QualType ObjectType,
6729                          Expr::Classification ObjectClassification,
6730                          ArrayRef<Expr *> Args,
6731                          OverloadCandidateSet &CandidateSet,
6732                          bool SuppressUserConversions,
6733                          bool PartialOverloading,
6734                          ConversionSequenceList EarlyConversions,
6735                          OverloadCandidateParamOrder PO) {
6736   const FunctionProtoType *Proto
6737     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6738   assert(Proto && "Methods without a prototype cannot be overloaded");
6739   assert(!isa<CXXConstructorDecl>(Method) &&
6740          "Use AddOverloadCandidate for constructors");
6741 
6742   if (!CandidateSet.isNewCandidate(Method, PO))
6743     return;
6744 
6745   // C++11 [class.copy]p23: [DR1402]
6746   //   A defaulted move assignment operator that is defined as deleted is
6747   //   ignored by overload resolution.
6748   if (Method->isDefaulted() && Method->isDeleted() &&
6749       Method->isMoveAssignmentOperator())
6750     return;
6751 
6752   // Overload resolution is always an unevaluated context.
6753   EnterExpressionEvaluationContext Unevaluated(
6754       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6755 
6756   // Add this candidate
6757   OverloadCandidate &Candidate =
6758       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6759   Candidate.FoundDecl = FoundDecl;
6760   Candidate.Function = Method;
6761   Candidate.RewriteKind =
6762       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6763   Candidate.IsSurrogate = false;
6764   Candidate.IgnoreObjectArgument = false;
6765   Candidate.ExplicitCallArguments = Args.size();
6766 
6767   unsigned NumParams = Proto->getNumParams();
6768 
6769   // (C++ 13.3.2p2): A candidate function having fewer than m
6770   // parameters is viable only if it has an ellipsis in its parameter
6771   // list (8.3.5).
6772   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6773       !Proto->isVariadic()) {
6774     Candidate.Viable = false;
6775     Candidate.FailureKind = ovl_fail_too_many_arguments;
6776     return;
6777   }
6778 
6779   // (C++ 13.3.2p2): A candidate function having more than m parameters
6780   // is viable only if the (m+1)st parameter has a default argument
6781   // (8.3.6). For the purposes of overload resolution, the
6782   // parameter list is truncated on the right, so that there are
6783   // exactly m parameters.
6784   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6785   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6786     // Not enough arguments.
6787     Candidate.Viable = false;
6788     Candidate.FailureKind = ovl_fail_too_few_arguments;
6789     return;
6790   }
6791 
6792   Candidate.Viable = true;
6793 
6794   if (Method->isStatic() || ObjectType.isNull())
6795     // The implicit object argument is ignored.
6796     Candidate.IgnoreObjectArgument = true;
6797   else {
6798     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6799     // Determine the implicit conversion sequence for the object
6800     // parameter.
6801     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6802         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6803         Method, ActingContext);
6804     if (Candidate.Conversions[ConvIdx].isBad()) {
6805       Candidate.Viable = false;
6806       Candidate.FailureKind = ovl_fail_bad_conversion;
6807       return;
6808     }
6809   }
6810 
6811   // (CUDA B.1): Check for invalid calls between targets.
6812   if (getLangOpts().CUDA)
6813     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6814       if (!IsAllowedCUDACall(Caller, Method)) {
6815         Candidate.Viable = false;
6816         Candidate.FailureKind = ovl_fail_bad_target;
6817         return;
6818       }
6819 
6820   if (Method->getTrailingRequiresClause()) {
6821     ConstraintSatisfaction Satisfaction;
6822     if (CheckFunctionConstraints(Method, Satisfaction) ||
6823         !Satisfaction.IsSatisfied) {
6824       Candidate.Viable = false;
6825       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6826       return;
6827     }
6828   }
6829 
6830   // Determine the implicit conversion sequences for each of the
6831   // arguments.
6832   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6833     unsigned ConvIdx =
6834         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6835     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6836       // We already formed a conversion sequence for this parameter during
6837       // template argument deduction.
6838     } else if (ArgIdx < NumParams) {
6839       // (C++ 13.3.2p3): for F to be a viable function, there shall
6840       // exist for each argument an implicit conversion sequence
6841       // (13.3.3.1) that converts that argument to the corresponding
6842       // parameter of F.
6843       QualType ParamType = Proto->getParamType(ArgIdx);
6844       Candidate.Conversions[ConvIdx]
6845         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6846                                 SuppressUserConversions,
6847                                 /*InOverloadResolution=*/true,
6848                                 /*AllowObjCWritebackConversion=*/
6849                                   getLangOpts().ObjCAutoRefCount);
6850       if (Candidate.Conversions[ConvIdx].isBad()) {
6851         Candidate.Viable = false;
6852         Candidate.FailureKind = ovl_fail_bad_conversion;
6853         return;
6854       }
6855     } else {
6856       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6857       // argument for which there is no corresponding parameter is
6858       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6859       Candidate.Conversions[ConvIdx].setEllipsis();
6860     }
6861   }
6862 
6863   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6864     Candidate.Viable = false;
6865     Candidate.FailureKind = ovl_fail_enable_if;
6866     Candidate.DeductionFailure.Data = FailedAttr;
6867     return;
6868   }
6869 
6870   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6871       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6872     Candidate.Viable = false;
6873     Candidate.FailureKind = ovl_non_default_multiversion_function;
6874   }
6875 }
6876 
6877 /// Add a C++ member function template as a candidate to the candidate
6878 /// set, using template argument deduction to produce an appropriate member
6879 /// function template specialization.
6880 void Sema::AddMethodTemplateCandidate(
6881     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6882     CXXRecordDecl *ActingContext,
6883     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6884     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6885     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6886     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6887   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6888     return;
6889 
6890   // C++ [over.match.funcs]p7:
6891   //   In each case where a candidate is a function template, candidate
6892   //   function template specializations are generated using template argument
6893   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6894   //   candidate functions in the usual way.113) A given name can refer to one
6895   //   or more function templates and also to a set of overloaded non-template
6896   //   functions. In such a case, the candidate functions generated from each
6897   //   function template are combined with the set of non-template candidate
6898   //   functions.
6899   TemplateDeductionInfo Info(CandidateSet.getLocation());
6900   FunctionDecl *Specialization = nullptr;
6901   ConversionSequenceList Conversions;
6902   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6903           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6904           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6905             return CheckNonDependentConversions(
6906                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6907                 SuppressUserConversions, ActingContext, ObjectType,
6908                 ObjectClassification, PO);
6909           })) {
6910     OverloadCandidate &Candidate =
6911         CandidateSet.addCandidate(Conversions.size(), Conversions);
6912     Candidate.FoundDecl = FoundDecl;
6913     Candidate.Function = MethodTmpl->getTemplatedDecl();
6914     Candidate.Viable = false;
6915     Candidate.RewriteKind =
6916       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6917     Candidate.IsSurrogate = false;
6918     Candidate.IgnoreObjectArgument =
6919         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6920         ObjectType.isNull();
6921     Candidate.ExplicitCallArguments = Args.size();
6922     if (Result == TDK_NonDependentConversionFailure)
6923       Candidate.FailureKind = ovl_fail_bad_conversion;
6924     else {
6925       Candidate.FailureKind = ovl_fail_bad_deduction;
6926       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6927                                                             Info);
6928     }
6929     return;
6930   }
6931 
6932   // Add the function template specialization produced by template argument
6933   // deduction as a candidate.
6934   assert(Specialization && "Missing member function template specialization?");
6935   assert(isa<CXXMethodDecl>(Specialization) &&
6936          "Specialization is not a member function?");
6937   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6938                      ActingContext, ObjectType, ObjectClassification, Args,
6939                      CandidateSet, SuppressUserConversions, PartialOverloading,
6940                      Conversions, PO);
6941 }
6942 
6943 /// Determine whether a given function template has a simple explicit specifier
6944 /// or a non-value-dependent explicit-specification that evaluates to true.
6945 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6946   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6947 }
6948 
6949 /// Add a C++ function template specialization as a candidate
6950 /// in the candidate set, using template argument deduction to produce
6951 /// an appropriate function template specialization.
6952 void Sema::AddTemplateOverloadCandidate(
6953     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6954     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6955     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6956     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6957     OverloadCandidateParamOrder PO) {
6958   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6959     return;
6960 
6961   // If the function template has a non-dependent explicit specification,
6962   // exclude it now if appropriate; we are not permitted to perform deduction
6963   // and substitution in this case.
6964   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6965     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6966     Candidate.FoundDecl = FoundDecl;
6967     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6968     Candidate.Viable = false;
6969     Candidate.FailureKind = ovl_fail_explicit;
6970     return;
6971   }
6972 
6973   // C++ [over.match.funcs]p7:
6974   //   In each case where a candidate is a function template, candidate
6975   //   function template specializations are generated using template argument
6976   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6977   //   candidate functions in the usual way.113) A given name can refer to one
6978   //   or more function templates and also to a set of overloaded non-template
6979   //   functions. In such a case, the candidate functions generated from each
6980   //   function template are combined with the set of non-template candidate
6981   //   functions.
6982   TemplateDeductionInfo Info(CandidateSet.getLocation());
6983   FunctionDecl *Specialization = nullptr;
6984   ConversionSequenceList Conversions;
6985   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6986           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6987           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6988             return CheckNonDependentConversions(
6989                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6990                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6991           })) {
6992     OverloadCandidate &Candidate =
6993         CandidateSet.addCandidate(Conversions.size(), Conversions);
6994     Candidate.FoundDecl = FoundDecl;
6995     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6996     Candidate.Viable = false;
6997     Candidate.RewriteKind =
6998       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6999     Candidate.IsSurrogate = false;
7000     Candidate.IsADLCandidate = IsADLCandidate;
7001     // Ignore the object argument if there is one, since we don't have an object
7002     // type.
7003     Candidate.IgnoreObjectArgument =
7004         isa<CXXMethodDecl>(Candidate.Function) &&
7005         !isa<CXXConstructorDecl>(Candidate.Function);
7006     Candidate.ExplicitCallArguments = Args.size();
7007     if (Result == TDK_NonDependentConversionFailure)
7008       Candidate.FailureKind = ovl_fail_bad_conversion;
7009     else {
7010       Candidate.FailureKind = ovl_fail_bad_deduction;
7011       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7012                                                             Info);
7013     }
7014     return;
7015   }
7016 
7017   // Add the function template specialization produced by template argument
7018   // deduction as a candidate.
7019   assert(Specialization && "Missing function template specialization?");
7020   AddOverloadCandidate(
7021       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7022       PartialOverloading, AllowExplicit,
7023       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7024 }
7025 
7026 /// Check that implicit conversion sequences can be formed for each argument
7027 /// whose corresponding parameter has a non-dependent type, per DR1391's
7028 /// [temp.deduct.call]p10.
7029 bool Sema::CheckNonDependentConversions(
7030     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7031     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7032     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7033     CXXRecordDecl *ActingContext, QualType ObjectType,
7034     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7035   // FIXME: The cases in which we allow explicit conversions for constructor
7036   // arguments never consider calling a constructor template. It's not clear
7037   // that is correct.
7038   const bool AllowExplicit = false;
7039 
7040   auto *FD = FunctionTemplate->getTemplatedDecl();
7041   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7042   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7043   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7044 
7045   Conversions =
7046       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7047 
7048   // Overload resolution is always an unevaluated context.
7049   EnterExpressionEvaluationContext Unevaluated(
7050       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7051 
7052   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7053   // require that, but this check should never result in a hard error, and
7054   // overload resolution is permitted to sidestep instantiations.
7055   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7056       !ObjectType.isNull()) {
7057     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7058     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7059         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7060         Method, ActingContext);
7061     if (Conversions[ConvIdx].isBad())
7062       return true;
7063   }
7064 
7065   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7066        ++I) {
7067     QualType ParamType = ParamTypes[I];
7068     if (!ParamType->isDependentType()) {
7069       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7070                              ? 0
7071                              : (ThisConversions + I);
7072       Conversions[ConvIdx]
7073         = TryCopyInitialization(*this, Args[I], ParamType,
7074                                 SuppressUserConversions,
7075                                 /*InOverloadResolution=*/true,
7076                                 /*AllowObjCWritebackConversion=*/
7077                                   getLangOpts().ObjCAutoRefCount,
7078                                 AllowExplicit);
7079       if (Conversions[ConvIdx].isBad())
7080         return true;
7081     }
7082   }
7083 
7084   return false;
7085 }
7086 
7087 /// Determine whether this is an allowable conversion from the result
7088 /// of an explicit conversion operator to the expected type, per C++
7089 /// [over.match.conv]p1 and [over.match.ref]p1.
7090 ///
7091 /// \param ConvType The return type of the conversion function.
7092 ///
7093 /// \param ToType The type we are converting to.
7094 ///
7095 /// \param AllowObjCPointerConversion Allow a conversion from one
7096 /// Objective-C pointer to another.
7097 ///
7098 /// \returns true if the conversion is allowable, false otherwise.
7099 static bool isAllowableExplicitConversion(Sema &S,
7100                                           QualType ConvType, QualType ToType,
7101                                           bool AllowObjCPointerConversion) {
7102   QualType ToNonRefType = ToType.getNonReferenceType();
7103 
7104   // Easy case: the types are the same.
7105   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7106     return true;
7107 
7108   // Allow qualification conversions.
7109   bool ObjCLifetimeConversion;
7110   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7111                                   ObjCLifetimeConversion))
7112     return true;
7113 
7114   // If we're not allowed to consider Objective-C pointer conversions,
7115   // we're done.
7116   if (!AllowObjCPointerConversion)
7117     return false;
7118 
7119   // Is this an Objective-C pointer conversion?
7120   bool IncompatibleObjC = false;
7121   QualType ConvertedType;
7122   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7123                                    IncompatibleObjC);
7124 }
7125 
7126 /// AddConversionCandidate - Add a C++ conversion function as a
7127 /// candidate in the candidate set (C++ [over.match.conv],
7128 /// C++ [over.match.copy]). From is the expression we're converting from,
7129 /// and ToType is the type that we're eventually trying to convert to
7130 /// (which may or may not be the same type as the type that the
7131 /// conversion function produces).
7132 void Sema::AddConversionCandidate(
7133     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7134     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7135     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7136     bool AllowExplicit, bool AllowResultConversion) {
7137   assert(!Conversion->getDescribedFunctionTemplate() &&
7138          "Conversion function templates use AddTemplateConversionCandidate");
7139   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7140   if (!CandidateSet.isNewCandidate(Conversion))
7141     return;
7142 
7143   // If the conversion function has an undeduced return type, trigger its
7144   // deduction now.
7145   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7146     if (DeduceReturnType(Conversion, From->getExprLoc()))
7147       return;
7148     ConvType = Conversion->getConversionType().getNonReferenceType();
7149   }
7150 
7151   // If we don't allow any conversion of the result type, ignore conversion
7152   // functions that don't convert to exactly (possibly cv-qualified) T.
7153   if (!AllowResultConversion &&
7154       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7155     return;
7156 
7157   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7158   // operator is only a candidate if its return type is the target type or
7159   // can be converted to the target type with a qualification conversion.
7160   //
7161   // FIXME: Include such functions in the candidate list and explain why we
7162   // can't select them.
7163   if (Conversion->isExplicit() &&
7164       !isAllowableExplicitConversion(*this, ConvType, ToType,
7165                                      AllowObjCConversionOnExplicit))
7166     return;
7167 
7168   // Overload resolution is always an unevaluated context.
7169   EnterExpressionEvaluationContext Unevaluated(
7170       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7171 
7172   // Add this candidate
7173   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7174   Candidate.FoundDecl = FoundDecl;
7175   Candidate.Function = Conversion;
7176   Candidate.IsSurrogate = false;
7177   Candidate.IgnoreObjectArgument = false;
7178   Candidate.FinalConversion.setAsIdentityConversion();
7179   Candidate.FinalConversion.setFromType(ConvType);
7180   Candidate.FinalConversion.setAllToTypes(ToType);
7181   Candidate.Viable = true;
7182   Candidate.ExplicitCallArguments = 1;
7183 
7184   // Explicit functions are not actually candidates at all if we're not
7185   // allowing them in this context, but keep them around so we can point
7186   // to them in diagnostics.
7187   if (!AllowExplicit && Conversion->isExplicit()) {
7188     Candidate.Viable = false;
7189     Candidate.FailureKind = ovl_fail_explicit;
7190     return;
7191   }
7192 
7193   // C++ [over.match.funcs]p4:
7194   //   For conversion functions, the function is considered to be a member of
7195   //   the class of the implicit implied object argument for the purpose of
7196   //   defining the type of the implicit object parameter.
7197   //
7198   // Determine the implicit conversion sequence for the implicit
7199   // object parameter.
7200   QualType ImplicitParamType = From->getType();
7201   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7202     ImplicitParamType = FromPtrType->getPointeeType();
7203   CXXRecordDecl *ConversionContext
7204     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7205 
7206   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7207       *this, CandidateSet.getLocation(), From->getType(),
7208       From->Classify(Context), Conversion, ConversionContext);
7209 
7210   if (Candidate.Conversions[0].isBad()) {
7211     Candidate.Viable = false;
7212     Candidate.FailureKind = ovl_fail_bad_conversion;
7213     return;
7214   }
7215 
7216   if (Conversion->getTrailingRequiresClause()) {
7217     ConstraintSatisfaction Satisfaction;
7218     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7219         !Satisfaction.IsSatisfied) {
7220       Candidate.Viable = false;
7221       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7222       return;
7223     }
7224   }
7225 
7226   // We won't go through a user-defined type conversion function to convert a
7227   // derived to base as such conversions are given Conversion Rank. They only
7228   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7229   QualType FromCanon
7230     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7231   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7232   if (FromCanon == ToCanon ||
7233       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7234     Candidate.Viable = false;
7235     Candidate.FailureKind = ovl_fail_trivial_conversion;
7236     return;
7237   }
7238 
7239   // To determine what the conversion from the result of calling the
7240   // conversion function to the type we're eventually trying to
7241   // convert to (ToType), we need to synthesize a call to the
7242   // conversion function and attempt copy initialization from it. This
7243   // makes sure that we get the right semantics with respect to
7244   // lvalues/rvalues and the type. Fortunately, we can allocate this
7245   // call on the stack and we don't need its arguments to be
7246   // well-formed.
7247   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7248                             VK_LValue, From->getBeginLoc());
7249   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7250                                 Context.getPointerType(Conversion->getType()),
7251                                 CK_FunctionToPointerDecay,
7252                                 &ConversionRef, VK_RValue);
7253 
7254   QualType ConversionType = Conversion->getConversionType();
7255   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7256     Candidate.Viable = false;
7257     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7258     return;
7259   }
7260 
7261   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7262 
7263   // Note that it is safe to allocate CallExpr on the stack here because
7264   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7265   // allocator).
7266   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7267 
7268   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7269   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7270       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7271 
7272   ImplicitConversionSequence ICS =
7273       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7274                             /*SuppressUserConversions=*/true,
7275                             /*InOverloadResolution=*/false,
7276                             /*AllowObjCWritebackConversion=*/false);
7277 
7278   switch (ICS.getKind()) {
7279   case ImplicitConversionSequence::StandardConversion:
7280     Candidate.FinalConversion = ICS.Standard;
7281 
7282     // C++ [over.ics.user]p3:
7283     //   If the user-defined conversion is specified by a specialization of a
7284     //   conversion function template, the second standard conversion sequence
7285     //   shall have exact match rank.
7286     if (Conversion->getPrimaryTemplate() &&
7287         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7288       Candidate.Viable = false;
7289       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7290       return;
7291     }
7292 
7293     // C++0x [dcl.init.ref]p5:
7294     //    In the second case, if the reference is an rvalue reference and
7295     //    the second standard conversion sequence of the user-defined
7296     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7297     //    program is ill-formed.
7298     if (ToType->isRValueReferenceType() &&
7299         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7300       Candidate.Viable = false;
7301       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7302       return;
7303     }
7304     break;
7305 
7306   case ImplicitConversionSequence::BadConversion:
7307     Candidate.Viable = false;
7308     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7309     return;
7310 
7311   default:
7312     llvm_unreachable(
7313            "Can only end up with a standard conversion sequence or failure");
7314   }
7315 
7316   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7317     Candidate.Viable = false;
7318     Candidate.FailureKind = ovl_fail_enable_if;
7319     Candidate.DeductionFailure.Data = FailedAttr;
7320     return;
7321   }
7322 
7323   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7324       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7325     Candidate.Viable = false;
7326     Candidate.FailureKind = ovl_non_default_multiversion_function;
7327   }
7328 }
7329 
7330 /// Adds a conversion function template specialization
7331 /// candidate to the overload set, using template argument deduction
7332 /// to deduce the template arguments of the conversion function
7333 /// template from the type that we are converting to (C++
7334 /// [temp.deduct.conv]).
7335 void Sema::AddTemplateConversionCandidate(
7336     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7337     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7338     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7339     bool AllowExplicit, bool AllowResultConversion) {
7340   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7341          "Only conversion function templates permitted here");
7342 
7343   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7344     return;
7345 
7346   // If the function template has a non-dependent explicit specification,
7347   // exclude it now if appropriate; we are not permitted to perform deduction
7348   // and substitution in this case.
7349   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7350     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7351     Candidate.FoundDecl = FoundDecl;
7352     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7353     Candidate.Viable = false;
7354     Candidate.FailureKind = ovl_fail_explicit;
7355     return;
7356   }
7357 
7358   TemplateDeductionInfo Info(CandidateSet.getLocation());
7359   CXXConversionDecl *Specialization = nullptr;
7360   if (TemplateDeductionResult Result
7361         = DeduceTemplateArguments(FunctionTemplate, ToType,
7362                                   Specialization, Info)) {
7363     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7364     Candidate.FoundDecl = FoundDecl;
7365     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7366     Candidate.Viable = false;
7367     Candidate.FailureKind = ovl_fail_bad_deduction;
7368     Candidate.IsSurrogate = false;
7369     Candidate.IgnoreObjectArgument = false;
7370     Candidate.ExplicitCallArguments = 1;
7371     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7372                                                           Info);
7373     return;
7374   }
7375 
7376   // Add the conversion function template specialization produced by
7377   // template argument deduction as a candidate.
7378   assert(Specialization && "Missing function template specialization?");
7379   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7380                          CandidateSet, AllowObjCConversionOnExplicit,
7381                          AllowExplicit, AllowResultConversion);
7382 }
7383 
7384 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7385 /// converts the given @c Object to a function pointer via the
7386 /// conversion function @c Conversion, and then attempts to call it
7387 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7388 /// the type of function that we'll eventually be calling.
7389 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7390                                  DeclAccessPair FoundDecl,
7391                                  CXXRecordDecl *ActingContext,
7392                                  const FunctionProtoType *Proto,
7393                                  Expr *Object,
7394                                  ArrayRef<Expr *> Args,
7395                                  OverloadCandidateSet& CandidateSet) {
7396   if (!CandidateSet.isNewCandidate(Conversion))
7397     return;
7398 
7399   // Overload resolution is always an unevaluated context.
7400   EnterExpressionEvaluationContext Unevaluated(
7401       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7402 
7403   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7404   Candidate.FoundDecl = FoundDecl;
7405   Candidate.Function = nullptr;
7406   Candidate.Surrogate = Conversion;
7407   Candidate.Viable = true;
7408   Candidate.IsSurrogate = true;
7409   Candidate.IgnoreObjectArgument = false;
7410   Candidate.ExplicitCallArguments = Args.size();
7411 
7412   // Determine the implicit conversion sequence for the implicit
7413   // object parameter.
7414   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7415       *this, CandidateSet.getLocation(), Object->getType(),
7416       Object->Classify(Context), Conversion, ActingContext);
7417   if (ObjectInit.isBad()) {
7418     Candidate.Viable = false;
7419     Candidate.FailureKind = ovl_fail_bad_conversion;
7420     Candidate.Conversions[0] = ObjectInit;
7421     return;
7422   }
7423 
7424   // The first conversion is actually a user-defined conversion whose
7425   // first conversion is ObjectInit's standard conversion (which is
7426   // effectively a reference binding). Record it as such.
7427   Candidate.Conversions[0].setUserDefined();
7428   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7429   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7430   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7431   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7432   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7433   Candidate.Conversions[0].UserDefined.After
7434     = Candidate.Conversions[0].UserDefined.Before;
7435   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7436 
7437   // Find the
7438   unsigned NumParams = Proto->getNumParams();
7439 
7440   // (C++ 13.3.2p2): A candidate function having fewer than m
7441   // parameters is viable only if it has an ellipsis in its parameter
7442   // list (8.3.5).
7443   if (Args.size() > NumParams && !Proto->isVariadic()) {
7444     Candidate.Viable = false;
7445     Candidate.FailureKind = ovl_fail_too_many_arguments;
7446     return;
7447   }
7448 
7449   // Function types don't have any default arguments, so just check if
7450   // we have enough arguments.
7451   if (Args.size() < NumParams) {
7452     // Not enough arguments.
7453     Candidate.Viable = false;
7454     Candidate.FailureKind = ovl_fail_too_few_arguments;
7455     return;
7456   }
7457 
7458   // Determine the implicit conversion sequences for each of the
7459   // arguments.
7460   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7461     if (ArgIdx < NumParams) {
7462       // (C++ 13.3.2p3): for F to be a viable function, there shall
7463       // exist for each argument an implicit conversion sequence
7464       // (13.3.3.1) that converts that argument to the corresponding
7465       // parameter of F.
7466       QualType ParamType = Proto->getParamType(ArgIdx);
7467       Candidate.Conversions[ArgIdx + 1]
7468         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7469                                 /*SuppressUserConversions=*/false,
7470                                 /*InOverloadResolution=*/false,
7471                                 /*AllowObjCWritebackConversion=*/
7472                                   getLangOpts().ObjCAutoRefCount);
7473       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7474         Candidate.Viable = false;
7475         Candidate.FailureKind = ovl_fail_bad_conversion;
7476         return;
7477       }
7478     } else {
7479       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7480       // argument for which there is no corresponding parameter is
7481       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7482       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7483     }
7484   }
7485 
7486   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7487     Candidate.Viable = false;
7488     Candidate.FailureKind = ovl_fail_enable_if;
7489     Candidate.DeductionFailure.Data = FailedAttr;
7490     return;
7491   }
7492 }
7493 
7494 /// Add all of the non-member operator function declarations in the given
7495 /// function set to the overload candidate set.
7496 void Sema::AddNonMemberOperatorCandidates(
7497     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7498     OverloadCandidateSet &CandidateSet,
7499     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7500   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7501     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7502     ArrayRef<Expr *> FunctionArgs = Args;
7503 
7504     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7505     FunctionDecl *FD =
7506         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7507 
7508     // Don't consider rewritten functions if we're not rewriting.
7509     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7510       continue;
7511 
7512     assert(!isa<CXXMethodDecl>(FD) &&
7513            "unqualified operator lookup found a member function");
7514 
7515     if (FunTmpl) {
7516       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7517                                    FunctionArgs, CandidateSet);
7518       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7519         AddTemplateOverloadCandidate(
7520             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7521             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7522             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7523     } else {
7524       if (ExplicitTemplateArgs)
7525         continue;
7526       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7527       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7528         AddOverloadCandidate(FD, F.getPair(),
7529                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7530                              false, false, true, false, ADLCallKind::NotADL,
7531                              None, OverloadCandidateParamOrder::Reversed);
7532     }
7533   }
7534 }
7535 
7536 /// Add overload candidates for overloaded operators that are
7537 /// member functions.
7538 ///
7539 /// Add the overloaded operator candidates that are member functions
7540 /// for the operator Op that was used in an operator expression such
7541 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7542 /// CandidateSet will store the added overload candidates. (C++
7543 /// [over.match.oper]).
7544 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7545                                        SourceLocation OpLoc,
7546                                        ArrayRef<Expr *> Args,
7547                                        OverloadCandidateSet &CandidateSet,
7548                                        OverloadCandidateParamOrder PO) {
7549   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7550 
7551   // C++ [over.match.oper]p3:
7552   //   For a unary operator @ with an operand of a type whose
7553   //   cv-unqualified version is T1, and for a binary operator @ with
7554   //   a left operand of a type whose cv-unqualified version is T1 and
7555   //   a right operand of a type whose cv-unqualified version is T2,
7556   //   three sets of candidate functions, designated member
7557   //   candidates, non-member candidates and built-in candidates, are
7558   //   constructed as follows:
7559   QualType T1 = Args[0]->getType();
7560 
7561   //     -- If T1 is a complete class type or a class currently being
7562   //        defined, the set of member candidates is the result of the
7563   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7564   //        the set of member candidates is empty.
7565   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7566     // Complete the type if it can be completed.
7567     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7568       return;
7569     // If the type is neither complete nor being defined, bail out now.
7570     if (!T1Rec->getDecl()->getDefinition())
7571       return;
7572 
7573     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7574     LookupQualifiedName(Operators, T1Rec->getDecl());
7575     Operators.suppressDiagnostics();
7576 
7577     for (LookupResult::iterator Oper = Operators.begin(),
7578                              OperEnd = Operators.end();
7579          Oper != OperEnd;
7580          ++Oper)
7581       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7582                          Args[0]->Classify(Context), Args.slice(1),
7583                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7584   }
7585 }
7586 
7587 /// AddBuiltinCandidate - Add a candidate for a built-in
7588 /// operator. ResultTy and ParamTys are the result and parameter types
7589 /// of the built-in candidate, respectively. Args and NumArgs are the
7590 /// arguments being passed to the candidate. IsAssignmentOperator
7591 /// should be true when this built-in candidate is an assignment
7592 /// operator. NumContextualBoolArguments is the number of arguments
7593 /// (at the beginning of the argument list) that will be contextually
7594 /// converted to bool.
7595 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7596                                OverloadCandidateSet& CandidateSet,
7597                                bool IsAssignmentOperator,
7598                                unsigned NumContextualBoolArguments) {
7599   // Overload resolution is always an unevaluated context.
7600   EnterExpressionEvaluationContext Unevaluated(
7601       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7602 
7603   // Add this candidate
7604   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7605   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7606   Candidate.Function = nullptr;
7607   Candidate.IsSurrogate = false;
7608   Candidate.IgnoreObjectArgument = false;
7609   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7610 
7611   // Determine the implicit conversion sequences for each of the
7612   // arguments.
7613   Candidate.Viable = true;
7614   Candidate.ExplicitCallArguments = Args.size();
7615   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7616     // C++ [over.match.oper]p4:
7617     //   For the built-in assignment operators, conversions of the
7618     //   left operand are restricted as follows:
7619     //     -- no temporaries are introduced to hold the left operand, and
7620     //     -- no user-defined conversions are applied to the left
7621     //        operand to achieve a type match with the left-most
7622     //        parameter of a built-in candidate.
7623     //
7624     // We block these conversions by turning off user-defined
7625     // conversions, since that is the only way that initialization of
7626     // a reference to a non-class type can occur from something that
7627     // is not of the same type.
7628     if (ArgIdx < NumContextualBoolArguments) {
7629       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7630              "Contextual conversion to bool requires bool type");
7631       Candidate.Conversions[ArgIdx]
7632         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7633     } else {
7634       Candidate.Conversions[ArgIdx]
7635         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7636                                 ArgIdx == 0 && IsAssignmentOperator,
7637                                 /*InOverloadResolution=*/false,
7638                                 /*AllowObjCWritebackConversion=*/
7639                                   getLangOpts().ObjCAutoRefCount);
7640     }
7641     if (Candidate.Conversions[ArgIdx].isBad()) {
7642       Candidate.Viable = false;
7643       Candidate.FailureKind = ovl_fail_bad_conversion;
7644       break;
7645     }
7646   }
7647 }
7648 
7649 namespace {
7650 
7651 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7652 /// candidate operator functions for built-in operators (C++
7653 /// [over.built]). The types are separated into pointer types and
7654 /// enumeration types.
7655 class BuiltinCandidateTypeSet  {
7656   /// TypeSet - A set of types.
7657   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7658                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7659 
7660   /// PointerTypes - The set of pointer types that will be used in the
7661   /// built-in candidates.
7662   TypeSet PointerTypes;
7663 
7664   /// MemberPointerTypes - The set of member pointer types that will be
7665   /// used in the built-in candidates.
7666   TypeSet MemberPointerTypes;
7667 
7668   /// EnumerationTypes - The set of enumeration types that will be
7669   /// used in the built-in candidates.
7670   TypeSet EnumerationTypes;
7671 
7672   /// The set of vector types that will be used in the built-in
7673   /// candidates.
7674   TypeSet VectorTypes;
7675 
7676   /// A flag indicating non-record types are viable candidates
7677   bool HasNonRecordTypes;
7678 
7679   /// A flag indicating whether either arithmetic or enumeration types
7680   /// were present in the candidate set.
7681   bool HasArithmeticOrEnumeralTypes;
7682 
7683   /// A flag indicating whether the nullptr type was present in the
7684   /// candidate set.
7685   bool HasNullPtrType;
7686 
7687   /// Sema - The semantic analysis instance where we are building the
7688   /// candidate type set.
7689   Sema &SemaRef;
7690 
7691   /// Context - The AST context in which we will build the type sets.
7692   ASTContext &Context;
7693 
7694   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7695                                                const Qualifiers &VisibleQuals);
7696   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7697 
7698 public:
7699   /// iterator - Iterates through the types that are part of the set.
7700   typedef TypeSet::iterator iterator;
7701 
7702   BuiltinCandidateTypeSet(Sema &SemaRef)
7703     : HasNonRecordTypes(false),
7704       HasArithmeticOrEnumeralTypes(false),
7705       HasNullPtrType(false),
7706       SemaRef(SemaRef),
7707       Context(SemaRef.Context) { }
7708 
7709   void AddTypesConvertedFrom(QualType Ty,
7710                              SourceLocation Loc,
7711                              bool AllowUserConversions,
7712                              bool AllowExplicitConversions,
7713                              const Qualifiers &VisibleTypeConversionsQuals);
7714 
7715   /// pointer_begin - First pointer type found;
7716   iterator pointer_begin() { return PointerTypes.begin(); }
7717 
7718   /// pointer_end - Past the last pointer type found;
7719   iterator pointer_end() { return PointerTypes.end(); }
7720 
7721   /// member_pointer_begin - First member pointer type found;
7722   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7723 
7724   /// member_pointer_end - Past the last member pointer type found;
7725   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7726 
7727   /// enumeration_begin - First enumeration type found;
7728   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7729 
7730   /// enumeration_end - Past the last enumeration type found;
7731   iterator enumeration_end() { return EnumerationTypes.end(); }
7732 
7733   iterator vector_begin() { return VectorTypes.begin(); }
7734   iterator vector_end() { return VectorTypes.end(); }
7735 
7736   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7737   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7738   bool hasNullPtrType() const { return HasNullPtrType; }
7739 };
7740 
7741 } // end anonymous namespace
7742 
7743 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7744 /// the set of pointer types along with any more-qualified variants of
7745 /// that type. For example, if @p Ty is "int const *", this routine
7746 /// will add "int const *", "int const volatile *", "int const
7747 /// restrict *", and "int const volatile restrict *" to the set of
7748 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7749 /// false otherwise.
7750 ///
7751 /// FIXME: what to do about extended qualifiers?
7752 bool
7753 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7754                                              const Qualifiers &VisibleQuals) {
7755 
7756   // Insert this type.
7757   if (!PointerTypes.insert(Ty))
7758     return false;
7759 
7760   QualType PointeeTy;
7761   const PointerType *PointerTy = Ty->getAs<PointerType>();
7762   bool buildObjCPtr = false;
7763   if (!PointerTy) {
7764     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7765     PointeeTy = PTy->getPointeeType();
7766     buildObjCPtr = true;
7767   } else {
7768     PointeeTy = PointerTy->getPointeeType();
7769   }
7770 
7771   // Don't add qualified variants of arrays. For one, they're not allowed
7772   // (the qualifier would sink to the element type), and for another, the
7773   // only overload situation where it matters is subscript or pointer +- int,
7774   // and those shouldn't have qualifier variants anyway.
7775   if (PointeeTy->isArrayType())
7776     return true;
7777 
7778   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7779   bool hasVolatile = VisibleQuals.hasVolatile();
7780   bool hasRestrict = VisibleQuals.hasRestrict();
7781 
7782   // Iterate through all strict supersets of BaseCVR.
7783   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7784     if ((CVR | BaseCVR) != CVR) continue;
7785     // Skip over volatile if no volatile found anywhere in the types.
7786     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7787 
7788     // Skip over restrict if no restrict found anywhere in the types, or if
7789     // the type cannot be restrict-qualified.
7790     if ((CVR & Qualifiers::Restrict) &&
7791         (!hasRestrict ||
7792          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7793       continue;
7794 
7795     // Build qualified pointee type.
7796     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7797 
7798     // Build qualified pointer type.
7799     QualType QPointerTy;
7800     if (!buildObjCPtr)
7801       QPointerTy = Context.getPointerType(QPointeeTy);
7802     else
7803       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7804 
7805     // Insert qualified pointer type.
7806     PointerTypes.insert(QPointerTy);
7807   }
7808 
7809   return true;
7810 }
7811 
7812 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7813 /// to the set of pointer types along with any more-qualified variants of
7814 /// that type. For example, if @p Ty is "int const *", this routine
7815 /// will add "int const *", "int const volatile *", "int const
7816 /// restrict *", and "int const volatile restrict *" to the set of
7817 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7818 /// false otherwise.
7819 ///
7820 /// FIXME: what to do about extended qualifiers?
7821 bool
7822 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7823     QualType Ty) {
7824   // Insert this type.
7825   if (!MemberPointerTypes.insert(Ty))
7826     return false;
7827 
7828   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7829   assert(PointerTy && "type was not a member pointer type!");
7830 
7831   QualType PointeeTy = PointerTy->getPointeeType();
7832   // Don't add qualified variants of arrays. For one, they're not allowed
7833   // (the qualifier would sink to the element type), and for another, the
7834   // only overload situation where it matters is subscript or pointer +- int,
7835   // and those shouldn't have qualifier variants anyway.
7836   if (PointeeTy->isArrayType())
7837     return true;
7838   const Type *ClassTy = PointerTy->getClass();
7839 
7840   // Iterate through all strict supersets of the pointee type's CVR
7841   // qualifiers.
7842   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7843   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7844     if ((CVR | BaseCVR) != CVR) continue;
7845 
7846     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7847     MemberPointerTypes.insert(
7848       Context.getMemberPointerType(QPointeeTy, ClassTy));
7849   }
7850 
7851   return true;
7852 }
7853 
7854 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7855 /// Ty can be implicit converted to the given set of @p Types. We're
7856 /// primarily interested in pointer types and enumeration types. We also
7857 /// take member pointer types, for the conditional operator.
7858 /// AllowUserConversions is true if we should look at the conversion
7859 /// functions of a class type, and AllowExplicitConversions if we
7860 /// should also include the explicit conversion functions of a class
7861 /// type.
7862 void
7863 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7864                                                SourceLocation Loc,
7865                                                bool AllowUserConversions,
7866                                                bool AllowExplicitConversions,
7867                                                const Qualifiers &VisibleQuals) {
7868   // Only deal with canonical types.
7869   Ty = Context.getCanonicalType(Ty);
7870 
7871   // Look through reference types; they aren't part of the type of an
7872   // expression for the purposes of conversions.
7873   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7874     Ty = RefTy->getPointeeType();
7875 
7876   // If we're dealing with an array type, decay to the pointer.
7877   if (Ty->isArrayType())
7878     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7879 
7880   // Otherwise, we don't care about qualifiers on the type.
7881   Ty = Ty.getLocalUnqualifiedType();
7882 
7883   // Flag if we ever add a non-record type.
7884   const RecordType *TyRec = Ty->getAs<RecordType>();
7885   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7886 
7887   // Flag if we encounter an arithmetic type.
7888   HasArithmeticOrEnumeralTypes =
7889     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7890 
7891   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7892     PointerTypes.insert(Ty);
7893   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7894     // Insert our type, and its more-qualified variants, into the set
7895     // of types.
7896     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7897       return;
7898   } else if (Ty->isMemberPointerType()) {
7899     // Member pointers are far easier, since the pointee can't be converted.
7900     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7901       return;
7902   } else if (Ty->isEnumeralType()) {
7903     HasArithmeticOrEnumeralTypes = true;
7904     EnumerationTypes.insert(Ty);
7905   } else if (Ty->isVectorType()) {
7906     // We treat vector types as arithmetic types in many contexts as an
7907     // extension.
7908     HasArithmeticOrEnumeralTypes = true;
7909     VectorTypes.insert(Ty);
7910   } else if (Ty->isNullPtrType()) {
7911     HasNullPtrType = true;
7912   } else if (AllowUserConversions && TyRec) {
7913     // No conversion functions in incomplete types.
7914     if (!SemaRef.isCompleteType(Loc, Ty))
7915       return;
7916 
7917     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7918     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7919       if (isa<UsingShadowDecl>(D))
7920         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7921 
7922       // Skip conversion function templates; they don't tell us anything
7923       // about which builtin types we can convert to.
7924       if (isa<FunctionTemplateDecl>(D))
7925         continue;
7926 
7927       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7928       if (AllowExplicitConversions || !Conv->isExplicit()) {
7929         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7930                               VisibleQuals);
7931       }
7932     }
7933   }
7934 }
7935 /// Helper function for adjusting address spaces for the pointer or reference
7936 /// operands of builtin operators depending on the argument.
7937 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7938                                                         Expr *Arg) {
7939   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7940 }
7941 
7942 /// Helper function for AddBuiltinOperatorCandidates() that adds
7943 /// the volatile- and non-volatile-qualified assignment operators for the
7944 /// given type to the candidate set.
7945 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7946                                                    QualType T,
7947                                                    ArrayRef<Expr *> Args,
7948                                     OverloadCandidateSet &CandidateSet) {
7949   QualType ParamTypes[2];
7950 
7951   // T& operator=(T&, T)
7952   ParamTypes[0] = S.Context.getLValueReferenceType(
7953       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7954   ParamTypes[1] = T;
7955   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7956                         /*IsAssignmentOperator=*/true);
7957 
7958   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7959     // volatile T& operator=(volatile T&, T)
7960     ParamTypes[0] = S.Context.getLValueReferenceType(
7961         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7962                                                 Args[0]));
7963     ParamTypes[1] = T;
7964     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7965                           /*IsAssignmentOperator=*/true);
7966   }
7967 }
7968 
7969 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7970 /// if any, found in visible type conversion functions found in ArgExpr's type.
7971 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7972     Qualifiers VRQuals;
7973     const RecordType *TyRec;
7974     if (const MemberPointerType *RHSMPType =
7975         ArgExpr->getType()->getAs<MemberPointerType>())
7976       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7977     else
7978       TyRec = ArgExpr->getType()->getAs<RecordType>();
7979     if (!TyRec) {
7980       // Just to be safe, assume the worst case.
7981       VRQuals.addVolatile();
7982       VRQuals.addRestrict();
7983       return VRQuals;
7984     }
7985 
7986     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7987     if (!ClassDecl->hasDefinition())
7988       return VRQuals;
7989 
7990     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7991       if (isa<UsingShadowDecl>(D))
7992         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7993       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7994         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7995         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7996           CanTy = ResTypeRef->getPointeeType();
7997         // Need to go down the pointer/mempointer chain and add qualifiers
7998         // as see them.
7999         bool done = false;
8000         while (!done) {
8001           if (CanTy.isRestrictQualified())
8002             VRQuals.addRestrict();
8003           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8004             CanTy = ResTypePtr->getPointeeType();
8005           else if (const MemberPointerType *ResTypeMPtr =
8006                 CanTy->getAs<MemberPointerType>())
8007             CanTy = ResTypeMPtr->getPointeeType();
8008           else
8009             done = true;
8010           if (CanTy.isVolatileQualified())
8011             VRQuals.addVolatile();
8012           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8013             return VRQuals;
8014         }
8015       }
8016     }
8017     return VRQuals;
8018 }
8019 
8020 namespace {
8021 
8022 /// Helper class to manage the addition of builtin operator overload
8023 /// candidates. It provides shared state and utility methods used throughout
8024 /// the process, as well as a helper method to add each group of builtin
8025 /// operator overloads from the standard to a candidate set.
8026 class BuiltinOperatorOverloadBuilder {
8027   // Common instance state available to all overload candidate addition methods.
8028   Sema &S;
8029   ArrayRef<Expr *> Args;
8030   Qualifiers VisibleTypeConversionsQuals;
8031   bool HasArithmeticOrEnumeralCandidateType;
8032   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8033   OverloadCandidateSet &CandidateSet;
8034 
8035   static constexpr int ArithmeticTypesCap = 24;
8036   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8037 
8038   // Define some indices used to iterate over the arithmetic types in
8039   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8040   // types are that preserved by promotion (C++ [over.built]p2).
8041   unsigned FirstIntegralType,
8042            LastIntegralType;
8043   unsigned FirstPromotedIntegralType,
8044            LastPromotedIntegralType;
8045   unsigned FirstPromotedArithmeticType,
8046            LastPromotedArithmeticType;
8047   unsigned NumArithmeticTypes;
8048 
8049   void InitArithmeticTypes() {
8050     // Start of promoted types.
8051     FirstPromotedArithmeticType = 0;
8052     ArithmeticTypes.push_back(S.Context.FloatTy);
8053     ArithmeticTypes.push_back(S.Context.DoubleTy);
8054     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8055     if (S.Context.getTargetInfo().hasFloat128Type())
8056       ArithmeticTypes.push_back(S.Context.Float128Ty);
8057 
8058     // Start of integral types.
8059     FirstIntegralType = ArithmeticTypes.size();
8060     FirstPromotedIntegralType = ArithmeticTypes.size();
8061     ArithmeticTypes.push_back(S.Context.IntTy);
8062     ArithmeticTypes.push_back(S.Context.LongTy);
8063     ArithmeticTypes.push_back(S.Context.LongLongTy);
8064     if (S.Context.getTargetInfo().hasInt128Type())
8065       ArithmeticTypes.push_back(S.Context.Int128Ty);
8066     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8067     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8068     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8069     if (S.Context.getTargetInfo().hasInt128Type())
8070       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8071     LastPromotedIntegralType = ArithmeticTypes.size();
8072     LastPromotedArithmeticType = ArithmeticTypes.size();
8073     // End of promoted types.
8074 
8075     ArithmeticTypes.push_back(S.Context.BoolTy);
8076     ArithmeticTypes.push_back(S.Context.CharTy);
8077     ArithmeticTypes.push_back(S.Context.WCharTy);
8078     if (S.Context.getLangOpts().Char8)
8079       ArithmeticTypes.push_back(S.Context.Char8Ty);
8080     ArithmeticTypes.push_back(S.Context.Char16Ty);
8081     ArithmeticTypes.push_back(S.Context.Char32Ty);
8082     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8083     ArithmeticTypes.push_back(S.Context.ShortTy);
8084     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8085     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8086     LastIntegralType = ArithmeticTypes.size();
8087     NumArithmeticTypes = ArithmeticTypes.size();
8088     // End of integral types.
8089     // FIXME: What about complex? What about half?
8090 
8091     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8092            "Enough inline storage for all arithmetic types.");
8093   }
8094 
8095   /// Helper method to factor out the common pattern of adding overloads
8096   /// for '++' and '--' builtin operators.
8097   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8098                                            bool HasVolatile,
8099                                            bool HasRestrict) {
8100     QualType ParamTypes[2] = {
8101       S.Context.getLValueReferenceType(CandidateTy),
8102       S.Context.IntTy
8103     };
8104 
8105     // Non-volatile version.
8106     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8107 
8108     // Use a heuristic to reduce number of builtin candidates in the set:
8109     // add volatile version only if there are conversions to a volatile type.
8110     if (HasVolatile) {
8111       ParamTypes[0] =
8112         S.Context.getLValueReferenceType(
8113           S.Context.getVolatileType(CandidateTy));
8114       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8115     }
8116 
8117     // Add restrict version only if there are conversions to a restrict type
8118     // and our candidate type is a non-restrict-qualified pointer.
8119     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8120         !CandidateTy.isRestrictQualified()) {
8121       ParamTypes[0]
8122         = S.Context.getLValueReferenceType(
8123             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8124       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8125 
8126       if (HasVolatile) {
8127         ParamTypes[0]
8128           = S.Context.getLValueReferenceType(
8129               S.Context.getCVRQualifiedType(CandidateTy,
8130                                             (Qualifiers::Volatile |
8131                                              Qualifiers::Restrict)));
8132         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8133       }
8134     }
8135 
8136   }
8137 
8138 public:
8139   BuiltinOperatorOverloadBuilder(
8140     Sema &S, ArrayRef<Expr *> Args,
8141     Qualifiers VisibleTypeConversionsQuals,
8142     bool HasArithmeticOrEnumeralCandidateType,
8143     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8144     OverloadCandidateSet &CandidateSet)
8145     : S(S), Args(Args),
8146       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8147       HasArithmeticOrEnumeralCandidateType(
8148         HasArithmeticOrEnumeralCandidateType),
8149       CandidateTypes(CandidateTypes),
8150       CandidateSet(CandidateSet) {
8151 
8152     InitArithmeticTypes();
8153   }
8154 
8155   // Increment is deprecated for bool since C++17.
8156   //
8157   // C++ [over.built]p3:
8158   //
8159   //   For every pair (T, VQ), where T is an arithmetic type other
8160   //   than bool, and VQ is either volatile or empty, there exist
8161   //   candidate operator functions of the form
8162   //
8163   //       VQ T&      operator++(VQ T&);
8164   //       T          operator++(VQ T&, int);
8165   //
8166   // C++ [over.built]p4:
8167   //
8168   //   For every pair (T, VQ), where T is an arithmetic type other
8169   //   than bool, and VQ is either volatile or empty, there exist
8170   //   candidate operator functions of the form
8171   //
8172   //       VQ T&      operator--(VQ T&);
8173   //       T          operator--(VQ T&, int);
8174   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8175     if (!HasArithmeticOrEnumeralCandidateType)
8176       return;
8177 
8178     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8179       const auto TypeOfT = ArithmeticTypes[Arith];
8180       if (TypeOfT == S.Context.BoolTy) {
8181         if (Op == OO_MinusMinus)
8182           continue;
8183         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8184           continue;
8185       }
8186       addPlusPlusMinusMinusStyleOverloads(
8187         TypeOfT,
8188         VisibleTypeConversionsQuals.hasVolatile(),
8189         VisibleTypeConversionsQuals.hasRestrict());
8190     }
8191   }
8192 
8193   // C++ [over.built]p5:
8194   //
8195   //   For every pair (T, VQ), where T is a cv-qualified or
8196   //   cv-unqualified object type, and VQ is either volatile or
8197   //   empty, there exist candidate operator functions of the form
8198   //
8199   //       T*VQ&      operator++(T*VQ&);
8200   //       T*VQ&      operator--(T*VQ&);
8201   //       T*         operator++(T*VQ&, int);
8202   //       T*         operator--(T*VQ&, int);
8203   void addPlusPlusMinusMinusPointerOverloads() {
8204     for (BuiltinCandidateTypeSet::iterator
8205               Ptr = CandidateTypes[0].pointer_begin(),
8206            PtrEnd = CandidateTypes[0].pointer_end();
8207          Ptr != PtrEnd; ++Ptr) {
8208       // Skip pointer types that aren't pointers to object types.
8209       if (!(*Ptr)->getPointeeType()->isObjectType())
8210         continue;
8211 
8212       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8213         (!(*Ptr).isVolatileQualified() &&
8214          VisibleTypeConversionsQuals.hasVolatile()),
8215         (!(*Ptr).isRestrictQualified() &&
8216          VisibleTypeConversionsQuals.hasRestrict()));
8217     }
8218   }
8219 
8220   // C++ [over.built]p6:
8221   //   For every cv-qualified or cv-unqualified object type T, there
8222   //   exist candidate operator functions of the form
8223   //
8224   //       T&         operator*(T*);
8225   //
8226   // C++ [over.built]p7:
8227   //   For every function type T that does not have cv-qualifiers or a
8228   //   ref-qualifier, there exist candidate operator functions of the form
8229   //       T&         operator*(T*);
8230   void addUnaryStarPointerOverloads() {
8231     for (BuiltinCandidateTypeSet::iterator
8232               Ptr = CandidateTypes[0].pointer_begin(),
8233            PtrEnd = CandidateTypes[0].pointer_end();
8234          Ptr != PtrEnd; ++Ptr) {
8235       QualType ParamTy = *Ptr;
8236       QualType PointeeTy = ParamTy->getPointeeType();
8237       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8238         continue;
8239 
8240       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8241         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8242           continue;
8243 
8244       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8245     }
8246   }
8247 
8248   // C++ [over.built]p9:
8249   //  For every promoted arithmetic type T, there exist candidate
8250   //  operator functions of the form
8251   //
8252   //       T         operator+(T);
8253   //       T         operator-(T);
8254   void addUnaryPlusOrMinusArithmeticOverloads() {
8255     if (!HasArithmeticOrEnumeralCandidateType)
8256       return;
8257 
8258     for (unsigned Arith = FirstPromotedArithmeticType;
8259          Arith < LastPromotedArithmeticType; ++Arith) {
8260       QualType ArithTy = ArithmeticTypes[Arith];
8261       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8262     }
8263 
8264     // Extension: We also add these operators for vector types.
8265     for (BuiltinCandidateTypeSet::iterator
8266               Vec = CandidateTypes[0].vector_begin(),
8267            VecEnd = CandidateTypes[0].vector_end();
8268          Vec != VecEnd; ++Vec) {
8269       QualType VecTy = *Vec;
8270       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8271     }
8272   }
8273 
8274   // C++ [over.built]p8:
8275   //   For every type T, there exist candidate operator functions of
8276   //   the form
8277   //
8278   //       T*         operator+(T*);
8279   void addUnaryPlusPointerOverloads() {
8280     for (BuiltinCandidateTypeSet::iterator
8281               Ptr = CandidateTypes[0].pointer_begin(),
8282            PtrEnd = CandidateTypes[0].pointer_end();
8283          Ptr != PtrEnd; ++Ptr) {
8284       QualType ParamTy = *Ptr;
8285       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8286     }
8287   }
8288 
8289   // C++ [over.built]p10:
8290   //   For every promoted integral type T, there exist candidate
8291   //   operator functions of the form
8292   //
8293   //        T         operator~(T);
8294   void addUnaryTildePromotedIntegralOverloads() {
8295     if (!HasArithmeticOrEnumeralCandidateType)
8296       return;
8297 
8298     for (unsigned Int = FirstPromotedIntegralType;
8299          Int < LastPromotedIntegralType; ++Int) {
8300       QualType IntTy = ArithmeticTypes[Int];
8301       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8302     }
8303 
8304     // Extension: We also add this operator for vector types.
8305     for (BuiltinCandidateTypeSet::iterator
8306               Vec = CandidateTypes[0].vector_begin(),
8307            VecEnd = CandidateTypes[0].vector_end();
8308          Vec != VecEnd; ++Vec) {
8309       QualType VecTy = *Vec;
8310       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8311     }
8312   }
8313 
8314   // C++ [over.match.oper]p16:
8315   //   For every pointer to member type T or type std::nullptr_t, there
8316   //   exist candidate operator functions of the form
8317   //
8318   //        bool operator==(T,T);
8319   //        bool operator!=(T,T);
8320   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8321     /// Set of (canonical) types that we've already handled.
8322     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8323 
8324     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8325       for (BuiltinCandidateTypeSet::iterator
8326                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8327              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8328            MemPtr != MemPtrEnd;
8329            ++MemPtr) {
8330         // Don't add the same builtin candidate twice.
8331         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8332           continue;
8333 
8334         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8335         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8336       }
8337 
8338       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8339         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8340         if (AddedTypes.insert(NullPtrTy).second) {
8341           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8342           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8343         }
8344       }
8345     }
8346   }
8347 
8348   // C++ [over.built]p15:
8349   //
8350   //   For every T, where T is an enumeration type or a pointer type,
8351   //   there exist candidate operator functions of the form
8352   //
8353   //        bool       operator<(T, T);
8354   //        bool       operator>(T, T);
8355   //        bool       operator<=(T, T);
8356   //        bool       operator>=(T, T);
8357   //        bool       operator==(T, T);
8358   //        bool       operator!=(T, T);
8359   //           R       operator<=>(T, T)
8360   void addGenericBinaryPointerOrEnumeralOverloads() {
8361     // C++ [over.match.oper]p3:
8362     //   [...]the built-in candidates include all of the candidate operator
8363     //   functions defined in 13.6 that, compared to the given operator, [...]
8364     //   do not have the same parameter-type-list as any non-template non-member
8365     //   candidate.
8366     //
8367     // Note that in practice, this only affects enumeration types because there
8368     // aren't any built-in candidates of record type, and a user-defined operator
8369     // must have an operand of record or enumeration type. Also, the only other
8370     // overloaded operator with enumeration arguments, operator=,
8371     // cannot be overloaded for enumeration types, so this is the only place
8372     // where we must suppress candidates like this.
8373     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8374       UserDefinedBinaryOperators;
8375 
8376     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8377       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8378           CandidateTypes[ArgIdx].enumeration_end()) {
8379         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8380                                          CEnd = CandidateSet.end();
8381              C != CEnd; ++C) {
8382           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8383             continue;
8384 
8385           if (C->Function->isFunctionTemplateSpecialization())
8386             continue;
8387 
8388           // We interpret "same parameter-type-list" as applying to the
8389           // "synthesized candidate, with the order of the two parameters
8390           // reversed", not to the original function.
8391           bool Reversed = C->RewriteKind & CRK_Reversed;
8392           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8393                                         ->getType()
8394                                         .getUnqualifiedType();
8395           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8396                                          ->getType()
8397                                          .getUnqualifiedType();
8398 
8399           // Skip if either parameter isn't of enumeral type.
8400           if (!FirstParamType->isEnumeralType() ||
8401               !SecondParamType->isEnumeralType())
8402             continue;
8403 
8404           // Add this operator to the set of known user-defined operators.
8405           UserDefinedBinaryOperators.insert(
8406             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8407                            S.Context.getCanonicalType(SecondParamType)));
8408         }
8409       }
8410     }
8411 
8412     /// Set of (canonical) types that we've already handled.
8413     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8414 
8415     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8416       for (BuiltinCandidateTypeSet::iterator
8417                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8418              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8419            Ptr != PtrEnd; ++Ptr) {
8420         // Don't add the same builtin candidate twice.
8421         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8422           continue;
8423 
8424         QualType ParamTypes[2] = { *Ptr, *Ptr };
8425         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8426       }
8427       for (BuiltinCandidateTypeSet::iterator
8428                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8429              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8430            Enum != EnumEnd; ++Enum) {
8431         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8432 
8433         // Don't add the same builtin candidate twice, or if a user defined
8434         // candidate exists.
8435         if (!AddedTypes.insert(CanonType).second ||
8436             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8437                                                             CanonType)))
8438           continue;
8439         QualType ParamTypes[2] = { *Enum, *Enum };
8440         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8441       }
8442     }
8443   }
8444 
8445   // C++ [over.built]p13:
8446   //
8447   //   For every cv-qualified or cv-unqualified object type T
8448   //   there exist candidate operator functions of the form
8449   //
8450   //      T*         operator+(T*, ptrdiff_t);
8451   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8452   //      T*         operator-(T*, ptrdiff_t);
8453   //      T*         operator+(ptrdiff_t, T*);
8454   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8455   //
8456   // C++ [over.built]p14:
8457   //
8458   //   For every T, where T is a pointer to object type, there
8459   //   exist candidate operator functions of the form
8460   //
8461   //      ptrdiff_t  operator-(T, T);
8462   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8463     /// Set of (canonical) types that we've already handled.
8464     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8465 
8466     for (int Arg = 0; Arg < 2; ++Arg) {
8467       QualType AsymmetricParamTypes[2] = {
8468         S.Context.getPointerDiffType(),
8469         S.Context.getPointerDiffType(),
8470       };
8471       for (BuiltinCandidateTypeSet::iterator
8472                 Ptr = CandidateTypes[Arg].pointer_begin(),
8473              PtrEnd = CandidateTypes[Arg].pointer_end();
8474            Ptr != PtrEnd; ++Ptr) {
8475         QualType PointeeTy = (*Ptr)->getPointeeType();
8476         if (!PointeeTy->isObjectType())
8477           continue;
8478 
8479         AsymmetricParamTypes[Arg] = *Ptr;
8480         if (Arg == 0 || Op == OO_Plus) {
8481           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8482           // T* operator+(ptrdiff_t, T*);
8483           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8484         }
8485         if (Op == OO_Minus) {
8486           // ptrdiff_t operator-(T, T);
8487           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8488             continue;
8489 
8490           QualType ParamTypes[2] = { *Ptr, *Ptr };
8491           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8492         }
8493       }
8494     }
8495   }
8496 
8497   // C++ [over.built]p12:
8498   //
8499   //   For every pair of promoted arithmetic types L and R, there
8500   //   exist candidate operator functions of the form
8501   //
8502   //        LR         operator*(L, R);
8503   //        LR         operator/(L, R);
8504   //        LR         operator+(L, R);
8505   //        LR         operator-(L, R);
8506   //        bool       operator<(L, R);
8507   //        bool       operator>(L, R);
8508   //        bool       operator<=(L, R);
8509   //        bool       operator>=(L, R);
8510   //        bool       operator==(L, R);
8511   //        bool       operator!=(L, R);
8512   //
8513   //   where LR is the result of the usual arithmetic conversions
8514   //   between types L and R.
8515   //
8516   // C++ [over.built]p24:
8517   //
8518   //   For every pair of promoted arithmetic types L and R, there exist
8519   //   candidate operator functions of the form
8520   //
8521   //        LR       operator?(bool, L, R);
8522   //
8523   //   where LR is the result of the usual arithmetic conversions
8524   //   between types L and R.
8525   // Our candidates ignore the first parameter.
8526   void addGenericBinaryArithmeticOverloads() {
8527     if (!HasArithmeticOrEnumeralCandidateType)
8528       return;
8529 
8530     for (unsigned Left = FirstPromotedArithmeticType;
8531          Left < LastPromotedArithmeticType; ++Left) {
8532       for (unsigned Right = FirstPromotedArithmeticType;
8533            Right < LastPromotedArithmeticType; ++Right) {
8534         QualType LandR[2] = { ArithmeticTypes[Left],
8535                               ArithmeticTypes[Right] };
8536         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8537       }
8538     }
8539 
8540     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8541     // conditional operator for vector types.
8542     for (BuiltinCandidateTypeSet::iterator
8543               Vec1 = CandidateTypes[0].vector_begin(),
8544            Vec1End = CandidateTypes[0].vector_end();
8545          Vec1 != Vec1End; ++Vec1) {
8546       for (BuiltinCandidateTypeSet::iterator
8547                 Vec2 = CandidateTypes[1].vector_begin(),
8548              Vec2End = CandidateTypes[1].vector_end();
8549            Vec2 != Vec2End; ++Vec2) {
8550         QualType LandR[2] = { *Vec1, *Vec2 };
8551         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8552       }
8553     }
8554   }
8555 
8556   // C++2a [over.built]p14:
8557   //
8558   //   For every integral type T there exists a candidate operator function
8559   //   of the form
8560   //
8561   //        std::strong_ordering operator<=>(T, T)
8562   //
8563   // C++2a [over.built]p15:
8564   //
8565   //   For every pair of floating-point types L and R, there exists a candidate
8566   //   operator function of the form
8567   //
8568   //       std::partial_ordering operator<=>(L, R);
8569   //
8570   // FIXME: The current specification for integral types doesn't play nice with
8571   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8572   // comparisons. Under the current spec this can lead to ambiguity during
8573   // overload resolution. For example:
8574   //
8575   //   enum A : int {a};
8576   //   auto x = (a <=> (long)42);
8577   //
8578   //   error: call is ambiguous for arguments 'A' and 'long'.
8579   //   note: candidate operator<=>(int, int)
8580   //   note: candidate operator<=>(long, long)
8581   //
8582   // To avoid this error, this function deviates from the specification and adds
8583   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8584   // arithmetic types (the same as the generic relational overloads).
8585   //
8586   // For now this function acts as a placeholder.
8587   void addThreeWayArithmeticOverloads() {
8588     addGenericBinaryArithmeticOverloads();
8589   }
8590 
8591   // C++ [over.built]p17:
8592   //
8593   //   For every pair of promoted integral types L and R, there
8594   //   exist candidate operator functions of the form
8595   //
8596   //      LR         operator%(L, R);
8597   //      LR         operator&(L, R);
8598   //      LR         operator^(L, R);
8599   //      LR         operator|(L, R);
8600   //      L          operator<<(L, R);
8601   //      L          operator>>(L, R);
8602   //
8603   //   where LR is the result of the usual arithmetic conversions
8604   //   between types L and R.
8605   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8606     if (!HasArithmeticOrEnumeralCandidateType)
8607       return;
8608 
8609     for (unsigned Left = FirstPromotedIntegralType;
8610          Left < LastPromotedIntegralType; ++Left) {
8611       for (unsigned Right = FirstPromotedIntegralType;
8612            Right < LastPromotedIntegralType; ++Right) {
8613         QualType LandR[2] = { ArithmeticTypes[Left],
8614                               ArithmeticTypes[Right] };
8615         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8616       }
8617     }
8618   }
8619 
8620   // C++ [over.built]p20:
8621   //
8622   //   For every pair (T, VQ), where T is an enumeration or
8623   //   pointer to member type and VQ is either volatile or
8624   //   empty, there exist candidate operator functions of the form
8625   //
8626   //        VQ T&      operator=(VQ T&, T);
8627   void addAssignmentMemberPointerOrEnumeralOverloads() {
8628     /// Set of (canonical) types that we've already handled.
8629     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8630 
8631     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8632       for (BuiltinCandidateTypeSet::iterator
8633                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8634              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8635            Enum != EnumEnd; ++Enum) {
8636         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8637           continue;
8638 
8639         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8640       }
8641 
8642       for (BuiltinCandidateTypeSet::iterator
8643                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8644              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8645            MemPtr != MemPtrEnd; ++MemPtr) {
8646         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8647           continue;
8648 
8649         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8650       }
8651     }
8652   }
8653 
8654   // C++ [over.built]p19:
8655   //
8656   //   For every pair (T, VQ), where T is any type and VQ is either
8657   //   volatile or empty, there exist candidate operator functions
8658   //   of the form
8659   //
8660   //        T*VQ&      operator=(T*VQ&, T*);
8661   //
8662   // C++ [over.built]p21:
8663   //
8664   //   For every pair (T, VQ), where T is a cv-qualified or
8665   //   cv-unqualified object type and VQ is either volatile or
8666   //   empty, there exist candidate operator functions of the form
8667   //
8668   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8669   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8670   void addAssignmentPointerOverloads(bool isEqualOp) {
8671     /// Set of (canonical) types that we've already handled.
8672     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8673 
8674     for (BuiltinCandidateTypeSet::iterator
8675               Ptr = CandidateTypes[0].pointer_begin(),
8676            PtrEnd = CandidateTypes[0].pointer_end();
8677          Ptr != PtrEnd; ++Ptr) {
8678       // If this is operator=, keep track of the builtin candidates we added.
8679       if (isEqualOp)
8680         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8681       else if (!(*Ptr)->getPointeeType()->isObjectType())
8682         continue;
8683 
8684       // non-volatile version
8685       QualType ParamTypes[2] = {
8686         S.Context.getLValueReferenceType(*Ptr),
8687         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8688       };
8689       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8690                             /*IsAssignmentOperator=*/ isEqualOp);
8691 
8692       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8693                           VisibleTypeConversionsQuals.hasVolatile();
8694       if (NeedVolatile) {
8695         // volatile version
8696         ParamTypes[0] =
8697           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8698         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8699                               /*IsAssignmentOperator=*/isEqualOp);
8700       }
8701 
8702       if (!(*Ptr).isRestrictQualified() &&
8703           VisibleTypeConversionsQuals.hasRestrict()) {
8704         // restrict version
8705         ParamTypes[0]
8706           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8707         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8708                               /*IsAssignmentOperator=*/isEqualOp);
8709 
8710         if (NeedVolatile) {
8711           // volatile restrict version
8712           ParamTypes[0]
8713             = S.Context.getLValueReferenceType(
8714                 S.Context.getCVRQualifiedType(*Ptr,
8715                                               (Qualifiers::Volatile |
8716                                                Qualifiers::Restrict)));
8717           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8718                                 /*IsAssignmentOperator=*/isEqualOp);
8719         }
8720       }
8721     }
8722 
8723     if (isEqualOp) {
8724       for (BuiltinCandidateTypeSet::iterator
8725                 Ptr = CandidateTypes[1].pointer_begin(),
8726              PtrEnd = CandidateTypes[1].pointer_end();
8727            Ptr != PtrEnd; ++Ptr) {
8728         // Make sure we don't add the same candidate twice.
8729         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8730           continue;
8731 
8732         QualType ParamTypes[2] = {
8733           S.Context.getLValueReferenceType(*Ptr),
8734           *Ptr,
8735         };
8736 
8737         // non-volatile version
8738         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8739                               /*IsAssignmentOperator=*/true);
8740 
8741         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8742                            VisibleTypeConversionsQuals.hasVolatile();
8743         if (NeedVolatile) {
8744           // volatile version
8745           ParamTypes[0] =
8746             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8747           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8748                                 /*IsAssignmentOperator=*/true);
8749         }
8750 
8751         if (!(*Ptr).isRestrictQualified() &&
8752             VisibleTypeConversionsQuals.hasRestrict()) {
8753           // restrict version
8754           ParamTypes[0]
8755             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8756           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8757                                 /*IsAssignmentOperator=*/true);
8758 
8759           if (NeedVolatile) {
8760             // volatile restrict version
8761             ParamTypes[0]
8762               = S.Context.getLValueReferenceType(
8763                   S.Context.getCVRQualifiedType(*Ptr,
8764                                                 (Qualifiers::Volatile |
8765                                                  Qualifiers::Restrict)));
8766             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8767                                   /*IsAssignmentOperator=*/true);
8768           }
8769         }
8770       }
8771     }
8772   }
8773 
8774   // C++ [over.built]p18:
8775   //
8776   //   For every triple (L, VQ, R), where L is an arithmetic type,
8777   //   VQ is either volatile or empty, and R is a promoted
8778   //   arithmetic type, there exist candidate operator functions of
8779   //   the form
8780   //
8781   //        VQ L&      operator=(VQ L&, R);
8782   //        VQ L&      operator*=(VQ L&, R);
8783   //        VQ L&      operator/=(VQ L&, R);
8784   //        VQ L&      operator+=(VQ L&, R);
8785   //        VQ L&      operator-=(VQ L&, R);
8786   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8787     if (!HasArithmeticOrEnumeralCandidateType)
8788       return;
8789 
8790     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8791       for (unsigned Right = FirstPromotedArithmeticType;
8792            Right < LastPromotedArithmeticType; ++Right) {
8793         QualType ParamTypes[2];
8794         ParamTypes[1] = ArithmeticTypes[Right];
8795         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8796             S, ArithmeticTypes[Left], Args[0]);
8797         // Add this built-in operator as a candidate (VQ is empty).
8798         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8799         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8800                               /*IsAssignmentOperator=*/isEqualOp);
8801 
8802         // Add this built-in operator as a candidate (VQ is 'volatile').
8803         if (VisibleTypeConversionsQuals.hasVolatile()) {
8804           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8805           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8806           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8807                                 /*IsAssignmentOperator=*/isEqualOp);
8808         }
8809       }
8810     }
8811 
8812     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8813     for (BuiltinCandidateTypeSet::iterator
8814               Vec1 = CandidateTypes[0].vector_begin(),
8815            Vec1End = CandidateTypes[0].vector_end();
8816          Vec1 != Vec1End; ++Vec1) {
8817       for (BuiltinCandidateTypeSet::iterator
8818                 Vec2 = CandidateTypes[1].vector_begin(),
8819              Vec2End = CandidateTypes[1].vector_end();
8820            Vec2 != Vec2End; ++Vec2) {
8821         QualType ParamTypes[2];
8822         ParamTypes[1] = *Vec2;
8823         // Add this built-in operator as a candidate (VQ is empty).
8824         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8825         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8826                               /*IsAssignmentOperator=*/isEqualOp);
8827 
8828         // Add this built-in operator as a candidate (VQ is 'volatile').
8829         if (VisibleTypeConversionsQuals.hasVolatile()) {
8830           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8831           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8832           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8833                                 /*IsAssignmentOperator=*/isEqualOp);
8834         }
8835       }
8836     }
8837   }
8838 
8839   // C++ [over.built]p22:
8840   //
8841   //   For every triple (L, VQ, R), where L is an integral type, VQ
8842   //   is either volatile or empty, and R is a promoted integral
8843   //   type, there exist candidate operator functions of the form
8844   //
8845   //        VQ L&       operator%=(VQ L&, R);
8846   //        VQ L&       operator<<=(VQ L&, R);
8847   //        VQ L&       operator>>=(VQ L&, R);
8848   //        VQ L&       operator&=(VQ L&, R);
8849   //        VQ L&       operator^=(VQ L&, R);
8850   //        VQ L&       operator|=(VQ L&, R);
8851   void addAssignmentIntegralOverloads() {
8852     if (!HasArithmeticOrEnumeralCandidateType)
8853       return;
8854 
8855     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8856       for (unsigned Right = FirstPromotedIntegralType;
8857            Right < LastPromotedIntegralType; ++Right) {
8858         QualType ParamTypes[2];
8859         ParamTypes[1] = ArithmeticTypes[Right];
8860         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8861             S, ArithmeticTypes[Left], Args[0]);
8862         // Add this built-in operator as a candidate (VQ is empty).
8863         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8864         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8865         if (VisibleTypeConversionsQuals.hasVolatile()) {
8866           // Add this built-in operator as a candidate (VQ is 'volatile').
8867           ParamTypes[0] = LeftBaseTy;
8868           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8869           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8870           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8871         }
8872       }
8873     }
8874   }
8875 
8876   // C++ [over.operator]p23:
8877   //
8878   //   There also exist candidate operator functions of the form
8879   //
8880   //        bool        operator!(bool);
8881   //        bool        operator&&(bool, bool);
8882   //        bool        operator||(bool, bool);
8883   void addExclaimOverload() {
8884     QualType ParamTy = S.Context.BoolTy;
8885     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8886                           /*IsAssignmentOperator=*/false,
8887                           /*NumContextualBoolArguments=*/1);
8888   }
8889   void addAmpAmpOrPipePipeOverload() {
8890     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8891     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8892                           /*IsAssignmentOperator=*/false,
8893                           /*NumContextualBoolArguments=*/2);
8894   }
8895 
8896   // C++ [over.built]p13:
8897   //
8898   //   For every cv-qualified or cv-unqualified object type T there
8899   //   exist candidate operator functions of the form
8900   //
8901   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8902   //        T&         operator[](T*, ptrdiff_t);
8903   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8904   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8905   //        T&         operator[](ptrdiff_t, T*);
8906   void addSubscriptOverloads() {
8907     for (BuiltinCandidateTypeSet::iterator
8908               Ptr = CandidateTypes[0].pointer_begin(),
8909            PtrEnd = CandidateTypes[0].pointer_end();
8910          Ptr != PtrEnd; ++Ptr) {
8911       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8912       QualType PointeeType = (*Ptr)->getPointeeType();
8913       if (!PointeeType->isObjectType())
8914         continue;
8915 
8916       // T& operator[](T*, ptrdiff_t)
8917       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8918     }
8919 
8920     for (BuiltinCandidateTypeSet::iterator
8921               Ptr = CandidateTypes[1].pointer_begin(),
8922            PtrEnd = CandidateTypes[1].pointer_end();
8923          Ptr != PtrEnd; ++Ptr) {
8924       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8925       QualType PointeeType = (*Ptr)->getPointeeType();
8926       if (!PointeeType->isObjectType())
8927         continue;
8928 
8929       // T& operator[](ptrdiff_t, T*)
8930       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8931     }
8932   }
8933 
8934   // C++ [over.built]p11:
8935   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8936   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8937   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8938   //    there exist candidate operator functions of the form
8939   //
8940   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8941   //
8942   //    where CV12 is the union of CV1 and CV2.
8943   void addArrowStarOverloads() {
8944     for (BuiltinCandidateTypeSet::iterator
8945              Ptr = CandidateTypes[0].pointer_begin(),
8946            PtrEnd = CandidateTypes[0].pointer_end();
8947          Ptr != PtrEnd; ++Ptr) {
8948       QualType C1Ty = (*Ptr);
8949       QualType C1;
8950       QualifierCollector Q1;
8951       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8952       if (!isa<RecordType>(C1))
8953         continue;
8954       // heuristic to reduce number of builtin candidates in the set.
8955       // Add volatile/restrict version only if there are conversions to a
8956       // volatile/restrict type.
8957       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8958         continue;
8959       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8960         continue;
8961       for (BuiltinCandidateTypeSet::iterator
8962                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8963              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8964            MemPtr != MemPtrEnd; ++MemPtr) {
8965         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8966         QualType C2 = QualType(mptr->getClass(), 0);
8967         C2 = C2.getUnqualifiedType();
8968         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8969           break;
8970         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8971         // build CV12 T&
8972         QualType T = mptr->getPointeeType();
8973         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8974             T.isVolatileQualified())
8975           continue;
8976         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8977             T.isRestrictQualified())
8978           continue;
8979         T = Q1.apply(S.Context, T);
8980         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8981       }
8982     }
8983   }
8984 
8985   // Note that we don't consider the first argument, since it has been
8986   // contextually converted to bool long ago. The candidates below are
8987   // therefore added as binary.
8988   //
8989   // C++ [over.built]p25:
8990   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8991   //   enumeration type, there exist candidate operator functions of the form
8992   //
8993   //        T        operator?(bool, T, T);
8994   //
8995   void addConditionalOperatorOverloads() {
8996     /// Set of (canonical) types that we've already handled.
8997     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8998 
8999     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9000       for (BuiltinCandidateTypeSet::iterator
9001                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9002              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9003            Ptr != PtrEnd; ++Ptr) {
9004         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9005           continue;
9006 
9007         QualType ParamTypes[2] = { *Ptr, *Ptr };
9008         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9009       }
9010 
9011       for (BuiltinCandidateTypeSet::iterator
9012                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9013              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9014            MemPtr != MemPtrEnd; ++MemPtr) {
9015         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9016           continue;
9017 
9018         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9019         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9020       }
9021 
9022       if (S.getLangOpts().CPlusPlus11) {
9023         for (BuiltinCandidateTypeSet::iterator
9024                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9025                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9026              Enum != EnumEnd; ++Enum) {
9027           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9028             continue;
9029 
9030           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9031             continue;
9032 
9033           QualType ParamTypes[2] = { *Enum, *Enum };
9034           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9035         }
9036       }
9037     }
9038   }
9039 };
9040 
9041 } // end anonymous namespace
9042 
9043 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9044 /// operator overloads to the candidate set (C++ [over.built]), based
9045 /// on the operator @p Op and the arguments given. For example, if the
9046 /// operator is a binary '+', this routine might add "int
9047 /// operator+(int, int)" to cover integer addition.
9048 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9049                                         SourceLocation OpLoc,
9050                                         ArrayRef<Expr *> Args,
9051                                         OverloadCandidateSet &CandidateSet) {
9052   // Find all of the types that the arguments can convert to, but only
9053   // if the operator we're looking at has built-in operator candidates
9054   // that make use of these types. Also record whether we encounter non-record
9055   // candidate types or either arithmetic or enumeral candidate types.
9056   Qualifiers VisibleTypeConversionsQuals;
9057   VisibleTypeConversionsQuals.addConst();
9058   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9059     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9060 
9061   bool HasNonRecordCandidateType = false;
9062   bool HasArithmeticOrEnumeralCandidateType = false;
9063   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9064   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9065     CandidateTypes.emplace_back(*this);
9066     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9067                                                  OpLoc,
9068                                                  true,
9069                                                  (Op == OO_Exclaim ||
9070                                                   Op == OO_AmpAmp ||
9071                                                   Op == OO_PipePipe),
9072                                                  VisibleTypeConversionsQuals);
9073     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9074         CandidateTypes[ArgIdx].hasNonRecordTypes();
9075     HasArithmeticOrEnumeralCandidateType =
9076         HasArithmeticOrEnumeralCandidateType ||
9077         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9078   }
9079 
9080   // Exit early when no non-record types have been added to the candidate set
9081   // for any of the arguments to the operator.
9082   //
9083   // We can't exit early for !, ||, or &&, since there we have always have
9084   // 'bool' overloads.
9085   if (!HasNonRecordCandidateType &&
9086       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9087     return;
9088 
9089   // Setup an object to manage the common state for building overloads.
9090   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9091                                            VisibleTypeConversionsQuals,
9092                                            HasArithmeticOrEnumeralCandidateType,
9093                                            CandidateTypes, CandidateSet);
9094 
9095   // Dispatch over the operation to add in only those overloads which apply.
9096   switch (Op) {
9097   case OO_None:
9098   case NUM_OVERLOADED_OPERATORS:
9099     llvm_unreachable("Expected an overloaded operator");
9100 
9101   case OO_New:
9102   case OO_Delete:
9103   case OO_Array_New:
9104   case OO_Array_Delete:
9105   case OO_Call:
9106     llvm_unreachable(
9107                     "Special operators don't use AddBuiltinOperatorCandidates");
9108 
9109   case OO_Comma:
9110   case OO_Arrow:
9111   case OO_Coawait:
9112     // C++ [over.match.oper]p3:
9113     //   -- For the operator ',', the unary operator '&', the
9114     //      operator '->', or the operator 'co_await', the
9115     //      built-in candidates set is empty.
9116     break;
9117 
9118   case OO_Plus: // '+' is either unary or binary
9119     if (Args.size() == 1)
9120       OpBuilder.addUnaryPlusPointerOverloads();
9121     LLVM_FALLTHROUGH;
9122 
9123   case OO_Minus: // '-' is either unary or binary
9124     if (Args.size() == 1) {
9125       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9126     } else {
9127       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9128       OpBuilder.addGenericBinaryArithmeticOverloads();
9129     }
9130     break;
9131 
9132   case OO_Star: // '*' is either unary or binary
9133     if (Args.size() == 1)
9134       OpBuilder.addUnaryStarPointerOverloads();
9135     else
9136       OpBuilder.addGenericBinaryArithmeticOverloads();
9137     break;
9138 
9139   case OO_Slash:
9140     OpBuilder.addGenericBinaryArithmeticOverloads();
9141     break;
9142 
9143   case OO_PlusPlus:
9144   case OO_MinusMinus:
9145     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9146     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9147     break;
9148 
9149   case OO_EqualEqual:
9150   case OO_ExclaimEqual:
9151     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9152     LLVM_FALLTHROUGH;
9153 
9154   case OO_Less:
9155   case OO_Greater:
9156   case OO_LessEqual:
9157   case OO_GreaterEqual:
9158     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9159     OpBuilder.addGenericBinaryArithmeticOverloads();
9160     break;
9161 
9162   case OO_Spaceship:
9163     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9164     OpBuilder.addThreeWayArithmeticOverloads();
9165     break;
9166 
9167   case OO_Percent:
9168   case OO_Caret:
9169   case OO_Pipe:
9170   case OO_LessLess:
9171   case OO_GreaterGreater:
9172     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9173     break;
9174 
9175   case OO_Amp: // '&' is either unary or binary
9176     if (Args.size() == 1)
9177       // C++ [over.match.oper]p3:
9178       //   -- For the operator ',', the unary operator '&', or the
9179       //      operator '->', the built-in candidates set is empty.
9180       break;
9181 
9182     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9183     break;
9184 
9185   case OO_Tilde:
9186     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9187     break;
9188 
9189   case OO_Equal:
9190     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9191     LLVM_FALLTHROUGH;
9192 
9193   case OO_PlusEqual:
9194   case OO_MinusEqual:
9195     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9196     LLVM_FALLTHROUGH;
9197 
9198   case OO_StarEqual:
9199   case OO_SlashEqual:
9200     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9201     break;
9202 
9203   case OO_PercentEqual:
9204   case OO_LessLessEqual:
9205   case OO_GreaterGreaterEqual:
9206   case OO_AmpEqual:
9207   case OO_CaretEqual:
9208   case OO_PipeEqual:
9209     OpBuilder.addAssignmentIntegralOverloads();
9210     break;
9211 
9212   case OO_Exclaim:
9213     OpBuilder.addExclaimOverload();
9214     break;
9215 
9216   case OO_AmpAmp:
9217   case OO_PipePipe:
9218     OpBuilder.addAmpAmpOrPipePipeOverload();
9219     break;
9220 
9221   case OO_Subscript:
9222     OpBuilder.addSubscriptOverloads();
9223     break;
9224 
9225   case OO_ArrowStar:
9226     OpBuilder.addArrowStarOverloads();
9227     break;
9228 
9229   case OO_Conditional:
9230     OpBuilder.addConditionalOperatorOverloads();
9231     OpBuilder.addGenericBinaryArithmeticOverloads();
9232     break;
9233   }
9234 }
9235 
9236 /// Add function candidates found via argument-dependent lookup
9237 /// to the set of overloading candidates.
9238 ///
9239 /// This routine performs argument-dependent name lookup based on the
9240 /// given function name (which may also be an operator name) and adds
9241 /// all of the overload candidates found by ADL to the overload
9242 /// candidate set (C++ [basic.lookup.argdep]).
9243 void
9244 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9245                                            SourceLocation Loc,
9246                                            ArrayRef<Expr *> Args,
9247                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9248                                            OverloadCandidateSet& CandidateSet,
9249                                            bool PartialOverloading) {
9250   ADLResult Fns;
9251 
9252   // FIXME: This approach for uniquing ADL results (and removing
9253   // redundant candidates from the set) relies on pointer-equality,
9254   // which means we need to key off the canonical decl.  However,
9255   // always going back to the canonical decl might not get us the
9256   // right set of default arguments.  What default arguments are
9257   // we supposed to consider on ADL candidates, anyway?
9258 
9259   // FIXME: Pass in the explicit template arguments?
9260   ArgumentDependentLookup(Name, Loc, Args, Fns);
9261 
9262   // Erase all of the candidates we already knew about.
9263   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9264                                    CandEnd = CandidateSet.end();
9265        Cand != CandEnd; ++Cand)
9266     if (Cand->Function) {
9267       Fns.erase(Cand->Function);
9268       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9269         Fns.erase(FunTmpl);
9270     }
9271 
9272   // For each of the ADL candidates we found, add it to the overload
9273   // set.
9274   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9275     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9276 
9277     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9278       if (ExplicitTemplateArgs)
9279         continue;
9280 
9281       AddOverloadCandidate(
9282           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9283           PartialOverloading, /*AllowExplicit=*/true,
9284           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9285       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9286         AddOverloadCandidate(
9287             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9288             /*SuppressUserConversions=*/false, PartialOverloading,
9289             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9290             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9291       }
9292     } else {
9293       auto *FTD = cast<FunctionTemplateDecl>(*I);
9294       AddTemplateOverloadCandidate(
9295           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9296           /*SuppressUserConversions=*/false, PartialOverloading,
9297           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9298       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9299               Context, FTD->getTemplatedDecl())) {
9300         AddTemplateOverloadCandidate(
9301             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9302             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9303             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9304             OverloadCandidateParamOrder::Reversed);
9305       }
9306     }
9307   }
9308 }
9309 
9310 namespace {
9311 enum class Comparison { Equal, Better, Worse };
9312 }
9313 
9314 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9315 /// overload resolution.
9316 ///
9317 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9318 /// Cand1's first N enable_if attributes have precisely the same conditions as
9319 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9320 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9321 ///
9322 /// Note that you can have a pair of candidates such that Cand1's enable_if
9323 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9324 /// worse than Cand1's.
9325 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9326                                        const FunctionDecl *Cand2) {
9327   // Common case: One (or both) decls don't have enable_if attrs.
9328   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9329   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9330   if (!Cand1Attr || !Cand2Attr) {
9331     if (Cand1Attr == Cand2Attr)
9332       return Comparison::Equal;
9333     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9334   }
9335 
9336   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9337   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9338 
9339   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9340   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9341     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9342     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9343 
9344     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9345     // has fewer enable_if attributes than Cand2, and vice versa.
9346     if (!Cand1A)
9347       return Comparison::Worse;
9348     if (!Cand2A)
9349       return Comparison::Better;
9350 
9351     Cand1ID.clear();
9352     Cand2ID.clear();
9353 
9354     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9355     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9356     if (Cand1ID != Cand2ID)
9357       return Comparison::Worse;
9358   }
9359 
9360   return Comparison::Equal;
9361 }
9362 
9363 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9364                                           const OverloadCandidate &Cand2) {
9365   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9366       !Cand2.Function->isMultiVersion())
9367     return false;
9368 
9369   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9370   // is obviously better.
9371   if (Cand1.Function->isInvalidDecl()) return false;
9372   if (Cand2.Function->isInvalidDecl()) return true;
9373 
9374   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9375   // cpu_dispatch, else arbitrarily based on the identifiers.
9376   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9377   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9378   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9379   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9380 
9381   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9382     return false;
9383 
9384   if (Cand1CPUDisp && !Cand2CPUDisp)
9385     return true;
9386   if (Cand2CPUDisp && !Cand1CPUDisp)
9387     return false;
9388 
9389   if (Cand1CPUSpec && Cand2CPUSpec) {
9390     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9391       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9392 
9393     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9394         FirstDiff = std::mismatch(
9395             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9396             Cand2CPUSpec->cpus_begin(),
9397             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9398               return LHS->getName() == RHS->getName();
9399             });
9400 
9401     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9402            "Two different cpu-specific versions should not have the same "
9403            "identifier list, otherwise they'd be the same decl!");
9404     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9405   }
9406   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9407 }
9408 
9409 /// isBetterOverloadCandidate - Determines whether the first overload
9410 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9411 bool clang::isBetterOverloadCandidate(
9412     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9413     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9414   // Define viable functions to be better candidates than non-viable
9415   // functions.
9416   if (!Cand2.Viable)
9417     return Cand1.Viable;
9418   else if (!Cand1.Viable)
9419     return false;
9420 
9421   // C++ [over.match.best]p1:
9422   //
9423   //   -- if F is a static member function, ICS1(F) is defined such
9424   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9425   //      any function G, and, symmetrically, ICS1(G) is neither
9426   //      better nor worse than ICS1(F).
9427   unsigned StartArg = 0;
9428   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9429     StartArg = 1;
9430 
9431   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9432     // We don't allow incompatible pointer conversions in C++.
9433     if (!S.getLangOpts().CPlusPlus)
9434       return ICS.isStandard() &&
9435              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9436 
9437     // The only ill-formed conversion we allow in C++ is the string literal to
9438     // char* conversion, which is only considered ill-formed after C++11.
9439     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9440            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9441   };
9442 
9443   // Define functions that don't require ill-formed conversions for a given
9444   // argument to be better candidates than functions that do.
9445   unsigned NumArgs = Cand1.Conversions.size();
9446   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9447   bool HasBetterConversion = false;
9448   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9449     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9450     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9451     if (Cand1Bad != Cand2Bad) {
9452       if (Cand1Bad)
9453         return false;
9454       HasBetterConversion = true;
9455     }
9456   }
9457 
9458   if (HasBetterConversion)
9459     return true;
9460 
9461   // C++ [over.match.best]p1:
9462   //   A viable function F1 is defined to be a better function than another
9463   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9464   //   conversion sequence than ICSi(F2), and then...
9465   bool HasWorseConversion = false;
9466   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9467     switch (CompareImplicitConversionSequences(S, Loc,
9468                                                Cand1.Conversions[ArgIdx],
9469                                                Cand2.Conversions[ArgIdx])) {
9470     case ImplicitConversionSequence::Better:
9471       // Cand1 has a better conversion sequence.
9472       HasBetterConversion = true;
9473       break;
9474 
9475     case ImplicitConversionSequence::Worse:
9476       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9477           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9478         // Work around large-scale breakage caused by considering reversed
9479         // forms of operator== in C++20:
9480         //
9481         // When comparing a function against its reversed form, if we have a
9482         // better conversion for one argument and a worse conversion for the
9483         // other, we prefer the non-reversed form.
9484         //
9485         // This prevents a conversion function from being considered ambiguous
9486         // with its own reversed form in various where it's only incidentally
9487         // heterogeneous.
9488         //
9489         // We diagnose this as an extension from CreateOverloadedBinOp.
9490         HasWorseConversion = true;
9491         break;
9492       }
9493 
9494       // Cand1 can't be better than Cand2.
9495       return false;
9496 
9497     case ImplicitConversionSequence::Indistinguishable:
9498       // Do nothing.
9499       break;
9500     }
9501   }
9502 
9503   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9504   //       ICSj(F2), or, if not that,
9505   if (HasBetterConversion)
9506     return true;
9507   if (HasWorseConversion)
9508     return false;
9509 
9510   //   -- the context is an initialization by user-defined conversion
9511   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9512   //      from the return type of F1 to the destination type (i.e.,
9513   //      the type of the entity being initialized) is a better
9514   //      conversion sequence than the standard conversion sequence
9515   //      from the return type of F2 to the destination type.
9516   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9517       Cand1.Function && Cand2.Function &&
9518       isa<CXXConversionDecl>(Cand1.Function) &&
9519       isa<CXXConversionDecl>(Cand2.Function)) {
9520     // First check whether we prefer one of the conversion functions over the
9521     // other. This only distinguishes the results in non-standard, extension
9522     // cases such as the conversion from a lambda closure type to a function
9523     // pointer or block.
9524     ImplicitConversionSequence::CompareKind Result =
9525         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9526     if (Result == ImplicitConversionSequence::Indistinguishable)
9527       Result = CompareStandardConversionSequences(S, Loc,
9528                                                   Cand1.FinalConversion,
9529                                                   Cand2.FinalConversion);
9530 
9531     if (Result != ImplicitConversionSequence::Indistinguishable)
9532       return Result == ImplicitConversionSequence::Better;
9533 
9534     // FIXME: Compare kind of reference binding if conversion functions
9535     // convert to a reference type used in direct reference binding, per
9536     // C++14 [over.match.best]p1 section 2 bullet 3.
9537   }
9538 
9539   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9540   // as combined with the resolution to CWG issue 243.
9541   //
9542   // When the context is initialization by constructor ([over.match.ctor] or
9543   // either phase of [over.match.list]), a constructor is preferred over
9544   // a conversion function.
9545   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9546       Cand1.Function && Cand2.Function &&
9547       isa<CXXConstructorDecl>(Cand1.Function) !=
9548           isa<CXXConstructorDecl>(Cand2.Function))
9549     return isa<CXXConstructorDecl>(Cand1.Function);
9550 
9551   //    -- F1 is a non-template function and F2 is a function template
9552   //       specialization, or, if not that,
9553   bool Cand1IsSpecialization = Cand1.Function &&
9554                                Cand1.Function->getPrimaryTemplate();
9555   bool Cand2IsSpecialization = Cand2.Function &&
9556                                Cand2.Function->getPrimaryTemplate();
9557   if (Cand1IsSpecialization != Cand2IsSpecialization)
9558     return Cand2IsSpecialization;
9559 
9560   //   -- F1 and F2 are function template specializations, and the function
9561   //      template for F1 is more specialized than the template for F2
9562   //      according to the partial ordering rules described in 14.5.5.2, or,
9563   //      if not that,
9564   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9565     if (FunctionTemplateDecl *BetterTemplate
9566           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9567                                          Cand2.Function->getPrimaryTemplate(),
9568                                          Loc,
9569                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9570                                                              : TPOC_Call,
9571                                          Cand1.ExplicitCallArguments,
9572                                          Cand2.ExplicitCallArguments))
9573       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9574   }
9575 
9576   //   -— F1 and F2 are non-template functions with the same
9577   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9578   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9579       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9580       Cand2.Function->hasPrototype()) {
9581     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9582     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9583     if (PT1->getNumParams() == PT2->getNumParams() &&
9584         PT1->isVariadic() == PT2->isVariadic() &&
9585         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9586       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9587       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9588       if (RC1 && RC2) {
9589         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9590         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9591                                      {RC2}, AtLeastAsConstrained1) ||
9592             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9593                                      {RC1}, AtLeastAsConstrained2))
9594           return false;
9595         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9596           return AtLeastAsConstrained1;
9597       } else if (RC1 || RC2) {
9598         return RC1 != nullptr;
9599       }
9600     }
9601   }
9602 
9603   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9604   //      class B of D, and for all arguments the corresponding parameters of
9605   //      F1 and F2 have the same type.
9606   // FIXME: Implement the "all parameters have the same type" check.
9607   bool Cand1IsInherited =
9608       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9609   bool Cand2IsInherited =
9610       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9611   if (Cand1IsInherited != Cand2IsInherited)
9612     return Cand2IsInherited;
9613   else if (Cand1IsInherited) {
9614     assert(Cand2IsInherited);
9615     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9616     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9617     if (Cand1Class->isDerivedFrom(Cand2Class))
9618       return true;
9619     if (Cand2Class->isDerivedFrom(Cand1Class))
9620       return false;
9621     // Inherited from sibling base classes: still ambiguous.
9622   }
9623 
9624   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9625   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9626   //      with reversed order of parameters and F1 is not
9627   //
9628   // We rank reversed + different operator as worse than just reversed, but
9629   // that comparison can never happen, because we only consider reversing for
9630   // the maximally-rewritten operator (== or <=>).
9631   if (Cand1.RewriteKind != Cand2.RewriteKind)
9632     return Cand1.RewriteKind < Cand2.RewriteKind;
9633 
9634   // Check C++17 tie-breakers for deduction guides.
9635   {
9636     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9637     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9638     if (Guide1 && Guide2) {
9639       //  -- F1 is generated from a deduction-guide and F2 is not
9640       if (Guide1->isImplicit() != Guide2->isImplicit())
9641         return Guide2->isImplicit();
9642 
9643       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9644       if (Guide1->isCopyDeductionCandidate())
9645         return true;
9646     }
9647   }
9648 
9649   // Check for enable_if value-based overload resolution.
9650   if (Cand1.Function && Cand2.Function) {
9651     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9652     if (Cmp != Comparison::Equal)
9653       return Cmp == Comparison::Better;
9654   }
9655 
9656   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9657     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9658     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9659            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9660   }
9661 
9662   bool HasPS1 = Cand1.Function != nullptr &&
9663                 functionHasPassObjectSizeParams(Cand1.Function);
9664   bool HasPS2 = Cand2.Function != nullptr &&
9665                 functionHasPassObjectSizeParams(Cand2.Function);
9666   if (HasPS1 != HasPS2 && HasPS1)
9667     return true;
9668 
9669   return isBetterMultiversionCandidate(Cand1, Cand2);
9670 }
9671 
9672 /// Determine whether two declarations are "equivalent" for the purposes of
9673 /// name lookup and overload resolution. This applies when the same internal/no
9674 /// linkage entity is defined by two modules (probably by textually including
9675 /// the same header). In such a case, we don't consider the declarations to
9676 /// declare the same entity, but we also don't want lookups with both
9677 /// declarations visible to be ambiguous in some cases (this happens when using
9678 /// a modularized libstdc++).
9679 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9680                                                   const NamedDecl *B) {
9681   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9682   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9683   if (!VA || !VB)
9684     return false;
9685 
9686   // The declarations must be declaring the same name as an internal linkage
9687   // entity in different modules.
9688   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9689           VB->getDeclContext()->getRedeclContext()) ||
9690       getOwningModule(VA) == getOwningModule(VB) ||
9691       VA->isExternallyVisible() || VB->isExternallyVisible())
9692     return false;
9693 
9694   // Check that the declarations appear to be equivalent.
9695   //
9696   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9697   // For constants and functions, we should check the initializer or body is
9698   // the same. For non-constant variables, we shouldn't allow it at all.
9699   if (Context.hasSameType(VA->getType(), VB->getType()))
9700     return true;
9701 
9702   // Enum constants within unnamed enumerations will have different types, but
9703   // may still be similar enough to be interchangeable for our purposes.
9704   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9705     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9706       // Only handle anonymous enums. If the enumerations were named and
9707       // equivalent, they would have been merged to the same type.
9708       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9709       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9710       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9711           !Context.hasSameType(EnumA->getIntegerType(),
9712                                EnumB->getIntegerType()))
9713         return false;
9714       // Allow this only if the value is the same for both enumerators.
9715       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9716     }
9717   }
9718 
9719   // Nothing else is sufficiently similar.
9720   return false;
9721 }
9722 
9723 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9724     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9725   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9726 
9727   Module *M = getOwningModule(D);
9728   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9729       << !M << (M ? M->getFullModuleName() : "");
9730 
9731   for (auto *E : Equiv) {
9732     Module *M = getOwningModule(E);
9733     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9734         << !M << (M ? M->getFullModuleName() : "");
9735   }
9736 }
9737 
9738 /// Computes the best viable function (C++ 13.3.3)
9739 /// within an overload candidate set.
9740 ///
9741 /// \param Loc The location of the function name (or operator symbol) for
9742 /// which overload resolution occurs.
9743 ///
9744 /// \param Best If overload resolution was successful or found a deleted
9745 /// function, \p Best points to the candidate function found.
9746 ///
9747 /// \returns The result of overload resolution.
9748 OverloadingResult
9749 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9750                                          iterator &Best) {
9751   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9752   std::transform(begin(), end(), std::back_inserter(Candidates),
9753                  [](OverloadCandidate &Cand) { return &Cand; });
9754 
9755   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9756   // are accepted by both clang and NVCC. However, during a particular
9757   // compilation mode only one call variant is viable. We need to
9758   // exclude non-viable overload candidates from consideration based
9759   // only on their host/device attributes. Specifically, if one
9760   // candidate call is WrongSide and the other is SameSide, we ignore
9761   // the WrongSide candidate.
9762   if (S.getLangOpts().CUDA) {
9763     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9764     bool ContainsSameSideCandidate =
9765         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9766           // Check viable function only.
9767           return Cand->Viable && Cand->Function &&
9768                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9769                      Sema::CFP_SameSide;
9770         });
9771     if (ContainsSameSideCandidate) {
9772       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9773         // Check viable function only to avoid unnecessary data copying/moving.
9774         return Cand->Viable && Cand->Function &&
9775                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9776                    Sema::CFP_WrongSide;
9777       };
9778       llvm::erase_if(Candidates, IsWrongSideCandidate);
9779     }
9780   }
9781 
9782   // Find the best viable function.
9783   Best = end();
9784   for (auto *Cand : Candidates) {
9785     Cand->Best = false;
9786     if (Cand->Viable)
9787       if (Best == end() ||
9788           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9789         Best = Cand;
9790   }
9791 
9792   // If we didn't find any viable functions, abort.
9793   if (Best == end())
9794     return OR_No_Viable_Function;
9795 
9796   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9797 
9798   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9799   PendingBest.push_back(&*Best);
9800   Best->Best = true;
9801 
9802   // Make sure that this function is better than every other viable
9803   // function. If not, we have an ambiguity.
9804   while (!PendingBest.empty()) {
9805     auto *Curr = PendingBest.pop_back_val();
9806     for (auto *Cand : Candidates) {
9807       if (Cand->Viable && !Cand->Best &&
9808           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9809         PendingBest.push_back(Cand);
9810         Cand->Best = true;
9811 
9812         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9813                                                      Curr->Function))
9814           EquivalentCands.push_back(Cand->Function);
9815         else
9816           Best = end();
9817       }
9818     }
9819   }
9820 
9821   // If we found more than one best candidate, this is ambiguous.
9822   if (Best == end())
9823     return OR_Ambiguous;
9824 
9825   // Best is the best viable function.
9826   if (Best->Function && Best->Function->isDeleted())
9827     return OR_Deleted;
9828 
9829   if (!EquivalentCands.empty())
9830     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9831                                                     EquivalentCands);
9832 
9833   return OR_Success;
9834 }
9835 
9836 namespace {
9837 
9838 enum OverloadCandidateKind {
9839   oc_function,
9840   oc_method,
9841   oc_reversed_binary_operator,
9842   oc_constructor,
9843   oc_implicit_default_constructor,
9844   oc_implicit_copy_constructor,
9845   oc_implicit_move_constructor,
9846   oc_implicit_copy_assignment,
9847   oc_implicit_move_assignment,
9848   oc_implicit_equality_comparison,
9849   oc_inherited_constructor
9850 };
9851 
9852 enum OverloadCandidateSelect {
9853   ocs_non_template,
9854   ocs_template,
9855   ocs_described_template,
9856 };
9857 
9858 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9859 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9860                           OverloadCandidateRewriteKind CRK,
9861                           std::string &Description) {
9862 
9863   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9864   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9865     isTemplate = true;
9866     Description = S.getTemplateArgumentBindingsText(
9867         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9868   }
9869 
9870   OverloadCandidateSelect Select = [&]() {
9871     if (!Description.empty())
9872       return ocs_described_template;
9873     return isTemplate ? ocs_template : ocs_non_template;
9874   }();
9875 
9876   OverloadCandidateKind Kind = [&]() {
9877     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9878       return oc_implicit_equality_comparison;
9879 
9880     if (CRK & CRK_Reversed)
9881       return oc_reversed_binary_operator;
9882 
9883     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9884       if (!Ctor->isImplicit()) {
9885         if (isa<ConstructorUsingShadowDecl>(Found))
9886           return oc_inherited_constructor;
9887         else
9888           return oc_constructor;
9889       }
9890 
9891       if (Ctor->isDefaultConstructor())
9892         return oc_implicit_default_constructor;
9893 
9894       if (Ctor->isMoveConstructor())
9895         return oc_implicit_move_constructor;
9896 
9897       assert(Ctor->isCopyConstructor() &&
9898              "unexpected sort of implicit constructor");
9899       return oc_implicit_copy_constructor;
9900     }
9901 
9902     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9903       // This actually gets spelled 'candidate function' for now, but
9904       // it doesn't hurt to split it out.
9905       if (!Meth->isImplicit())
9906         return oc_method;
9907 
9908       if (Meth->isMoveAssignmentOperator())
9909         return oc_implicit_move_assignment;
9910 
9911       if (Meth->isCopyAssignmentOperator())
9912         return oc_implicit_copy_assignment;
9913 
9914       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9915       return oc_method;
9916     }
9917 
9918     return oc_function;
9919   }();
9920 
9921   return std::make_pair(Kind, Select);
9922 }
9923 
9924 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9925   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9926   // set.
9927   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9928     S.Diag(FoundDecl->getLocation(),
9929            diag::note_ovl_candidate_inherited_constructor)
9930       << Shadow->getNominatedBaseClass();
9931 }
9932 
9933 } // end anonymous namespace
9934 
9935 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9936                                     const FunctionDecl *FD) {
9937   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9938     bool AlwaysTrue;
9939     if (EnableIf->getCond()->isValueDependent() ||
9940         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9941       return false;
9942     if (!AlwaysTrue)
9943       return false;
9944   }
9945   return true;
9946 }
9947 
9948 /// Returns true if we can take the address of the function.
9949 ///
9950 /// \param Complain - If true, we'll emit a diagnostic
9951 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9952 ///   we in overload resolution?
9953 /// \param Loc - The location of the statement we're complaining about. Ignored
9954 ///   if we're not complaining, or if we're in overload resolution.
9955 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9956                                               bool Complain,
9957                                               bool InOverloadResolution,
9958                                               SourceLocation Loc) {
9959   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9960     if (Complain) {
9961       if (InOverloadResolution)
9962         S.Diag(FD->getBeginLoc(),
9963                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9964       else
9965         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9966     }
9967     return false;
9968   }
9969 
9970   if (FD->getTrailingRequiresClause()) {
9971     ConstraintSatisfaction Satisfaction;
9972     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
9973       return false;
9974     if (!Satisfaction.IsSatisfied) {
9975       if (Complain) {
9976         if (InOverloadResolution)
9977           S.Diag(FD->getBeginLoc(),
9978                  diag::note_ovl_candidate_unsatisfied_constraints);
9979         else
9980           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9981               << FD;
9982         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9983       }
9984       return false;
9985     }
9986   }
9987 
9988   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9989     return P->hasAttr<PassObjectSizeAttr>();
9990   });
9991   if (I == FD->param_end())
9992     return true;
9993 
9994   if (Complain) {
9995     // Add one to ParamNo because it's user-facing
9996     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9997     if (InOverloadResolution)
9998       S.Diag(FD->getLocation(),
9999              diag::note_ovl_candidate_has_pass_object_size_params)
10000           << ParamNo;
10001     else
10002       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10003           << FD << ParamNo;
10004   }
10005   return false;
10006 }
10007 
10008 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10009                                                const FunctionDecl *FD) {
10010   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10011                                            /*InOverloadResolution=*/true,
10012                                            /*Loc=*/SourceLocation());
10013 }
10014 
10015 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10016                                              bool Complain,
10017                                              SourceLocation Loc) {
10018   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10019                                              /*InOverloadResolution=*/false,
10020                                              Loc);
10021 }
10022 
10023 // Notes the location of an overload candidate.
10024 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10025                                  OverloadCandidateRewriteKind RewriteKind,
10026                                  QualType DestType, bool TakingAddress) {
10027   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10028     return;
10029   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10030       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10031     return;
10032 
10033   std::string FnDesc;
10034   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10035       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10036   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10037                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10038                          << Fn << FnDesc;
10039 
10040   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10041   Diag(Fn->getLocation(), PD);
10042   MaybeEmitInheritedConstructorNote(*this, Found);
10043 }
10044 
10045 static void
10046 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10047   // Perhaps the ambiguity was caused by two atomic constraints that are
10048   // 'identical' but not equivalent:
10049   //
10050   // void foo() requires (sizeof(T) > 4) { } // #1
10051   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10052   //
10053   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10054   // #2 to subsume #1, but these constraint are not considered equivalent
10055   // according to the subsumption rules because they are not the same
10056   // source-level construct. This behavior is quite confusing and we should try
10057   // to help the user figure out what happened.
10058 
10059   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10060   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10061   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10062     if (!I->Function)
10063       continue;
10064     SmallVector<const Expr *, 3> AC;
10065     if (auto *Template = I->Function->getPrimaryTemplate())
10066       Template->getAssociatedConstraints(AC);
10067     else
10068       I->Function->getAssociatedConstraints(AC);
10069     if (AC.empty())
10070       continue;
10071     if (FirstCand == nullptr) {
10072       FirstCand = I->Function;
10073       FirstAC = AC;
10074     } else if (SecondCand == nullptr) {
10075       SecondCand = I->Function;
10076       SecondAC = AC;
10077     } else {
10078       // We have more than one pair of constrained functions - this check is
10079       // expensive and we'd rather not try to diagnose it.
10080       return;
10081     }
10082   }
10083   if (!SecondCand)
10084     return;
10085   // The diagnostic can only happen if there are associated constraints on
10086   // both sides (there needs to be some identical atomic constraint).
10087   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10088                                                       SecondCand, SecondAC))
10089     // Just show the user one diagnostic, they'll probably figure it out
10090     // from here.
10091     return;
10092 }
10093 
10094 // Notes the location of all overload candidates designated through
10095 // OverloadedExpr
10096 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10097                                      bool TakingAddress) {
10098   assert(OverloadedExpr->getType() == Context.OverloadTy);
10099 
10100   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10101   OverloadExpr *OvlExpr = Ovl.Expression;
10102 
10103   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10104                             IEnd = OvlExpr->decls_end();
10105        I != IEnd; ++I) {
10106     if (FunctionTemplateDecl *FunTmpl =
10107                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10108       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10109                             TakingAddress);
10110     } else if (FunctionDecl *Fun
10111                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10112       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10113     }
10114   }
10115 }
10116 
10117 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10118 /// "lead" diagnostic; it will be given two arguments, the source and
10119 /// target types of the conversion.
10120 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10121                                  Sema &S,
10122                                  SourceLocation CaretLoc,
10123                                  const PartialDiagnostic &PDiag) const {
10124   S.Diag(CaretLoc, PDiag)
10125     << Ambiguous.getFromType() << Ambiguous.getToType();
10126   // FIXME: The note limiting machinery is borrowed from
10127   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10128   // refactoring here.
10129   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10130   unsigned CandsShown = 0;
10131   AmbiguousConversionSequence::const_iterator I, E;
10132   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10133     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10134       break;
10135     ++CandsShown;
10136     S.NoteOverloadCandidate(I->first, I->second);
10137   }
10138   if (I != E)
10139     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10140 }
10141 
10142 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10143                                   unsigned I, bool TakingCandidateAddress) {
10144   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10145   assert(Conv.isBad());
10146   assert(Cand->Function && "for now, candidate must be a function");
10147   FunctionDecl *Fn = Cand->Function;
10148 
10149   // There's a conversion slot for the object argument if this is a
10150   // non-constructor method.  Note that 'I' corresponds the
10151   // conversion-slot index.
10152   bool isObjectArgument = false;
10153   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10154     if (I == 0)
10155       isObjectArgument = true;
10156     else
10157       I--;
10158   }
10159 
10160   std::string FnDesc;
10161   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10162       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10163                                 FnDesc);
10164 
10165   Expr *FromExpr = Conv.Bad.FromExpr;
10166   QualType FromTy = Conv.Bad.getFromType();
10167   QualType ToTy = Conv.Bad.getToType();
10168 
10169   if (FromTy == S.Context.OverloadTy) {
10170     assert(FromExpr && "overload set argument came from implicit argument?");
10171     Expr *E = FromExpr->IgnoreParens();
10172     if (isa<UnaryOperator>(E))
10173       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10174     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10175 
10176     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10177         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10178         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10179         << Name << I + 1;
10180     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10181     return;
10182   }
10183 
10184   // Do some hand-waving analysis to see if the non-viability is due
10185   // to a qualifier mismatch.
10186   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10187   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10188   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10189     CToTy = RT->getPointeeType();
10190   else {
10191     // TODO: detect and diagnose the full richness of const mismatches.
10192     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10193       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10194         CFromTy = FromPT->getPointeeType();
10195         CToTy = ToPT->getPointeeType();
10196       }
10197   }
10198 
10199   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10200       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10201     Qualifiers FromQs = CFromTy.getQualifiers();
10202     Qualifiers ToQs = CToTy.getQualifiers();
10203 
10204     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10205       if (isObjectArgument)
10206         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10207             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10208             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10209             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10210       else
10211         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10212             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10213             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10214             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10215             << ToTy->isReferenceType() << I + 1;
10216       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10217       return;
10218     }
10219 
10220     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10221       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10222           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10223           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10224           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10225           << (unsigned)isObjectArgument << I + 1;
10226       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10227       return;
10228     }
10229 
10230     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10231       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10232           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10233           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10234           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10235           << (unsigned)isObjectArgument << I + 1;
10236       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10237       return;
10238     }
10239 
10240     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10241       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10242           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10243           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10244           << FromQs.hasUnaligned() << I + 1;
10245       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10246       return;
10247     }
10248 
10249     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10250     assert(CVR && "unexpected qualifiers mismatch");
10251 
10252     if (isObjectArgument) {
10253       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10254           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10255           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10256           << (CVR - 1);
10257     } else {
10258       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10259           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10260           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10261           << (CVR - 1) << I + 1;
10262     }
10263     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10264     return;
10265   }
10266 
10267   // Special diagnostic for failure to convert an initializer list, since
10268   // telling the user that it has type void is not useful.
10269   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10270     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10271         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10272         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10273         << ToTy << (unsigned)isObjectArgument << I + 1;
10274     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10275     return;
10276   }
10277 
10278   // Diagnose references or pointers to incomplete types differently,
10279   // since it's far from impossible that the incompleteness triggered
10280   // the failure.
10281   QualType TempFromTy = FromTy.getNonReferenceType();
10282   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10283     TempFromTy = PTy->getPointeeType();
10284   if (TempFromTy->isIncompleteType()) {
10285     // Emit the generic diagnostic and, optionally, add the hints to it.
10286     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10287         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10288         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10289         << ToTy << (unsigned)isObjectArgument << I + 1
10290         << (unsigned)(Cand->Fix.Kind);
10291 
10292     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10293     return;
10294   }
10295 
10296   // Diagnose base -> derived pointer conversions.
10297   unsigned BaseToDerivedConversion = 0;
10298   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10299     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10300       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10301                                                FromPtrTy->getPointeeType()) &&
10302           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10303           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10304           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10305                           FromPtrTy->getPointeeType()))
10306         BaseToDerivedConversion = 1;
10307     }
10308   } else if (const ObjCObjectPointerType *FromPtrTy
10309                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10310     if (const ObjCObjectPointerType *ToPtrTy
10311                                         = ToTy->getAs<ObjCObjectPointerType>())
10312       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10313         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10314           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10315                                                 FromPtrTy->getPointeeType()) &&
10316               FromIface->isSuperClassOf(ToIface))
10317             BaseToDerivedConversion = 2;
10318   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10319     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10320         !FromTy->isIncompleteType() &&
10321         !ToRefTy->getPointeeType()->isIncompleteType() &&
10322         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10323       BaseToDerivedConversion = 3;
10324     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10325                ToTy.getNonReferenceType().getCanonicalType() ==
10326                FromTy.getNonReferenceType().getCanonicalType()) {
10327       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10328           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10329           << (unsigned)isObjectArgument << I + 1
10330           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10331       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10332       return;
10333     }
10334   }
10335 
10336   if (BaseToDerivedConversion) {
10337     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10338         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10339         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10340         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10341     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10342     return;
10343   }
10344 
10345   if (isa<ObjCObjectPointerType>(CFromTy) &&
10346       isa<PointerType>(CToTy)) {
10347       Qualifiers FromQs = CFromTy.getQualifiers();
10348       Qualifiers ToQs = CToTy.getQualifiers();
10349       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10350         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10351             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10352             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10353             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10354         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10355         return;
10356       }
10357   }
10358 
10359   if (TakingCandidateAddress &&
10360       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10361     return;
10362 
10363   // Emit the generic diagnostic and, optionally, add the hints to it.
10364   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10365   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10366         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10367         << ToTy << (unsigned)isObjectArgument << I + 1
10368         << (unsigned)(Cand->Fix.Kind);
10369 
10370   // If we can fix the conversion, suggest the FixIts.
10371   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10372        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10373     FDiag << *HI;
10374   S.Diag(Fn->getLocation(), FDiag);
10375 
10376   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10377 }
10378 
10379 /// Additional arity mismatch diagnosis specific to a function overload
10380 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10381 /// over a candidate in any candidate set.
10382 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10383                                unsigned NumArgs) {
10384   FunctionDecl *Fn = Cand->Function;
10385   unsigned MinParams = Fn->getMinRequiredArguments();
10386 
10387   // With invalid overloaded operators, it's possible that we think we
10388   // have an arity mismatch when in fact it looks like we have the
10389   // right number of arguments, because only overloaded operators have
10390   // the weird behavior of overloading member and non-member functions.
10391   // Just don't report anything.
10392   if (Fn->isInvalidDecl() &&
10393       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10394     return true;
10395 
10396   if (NumArgs < MinParams) {
10397     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10398            (Cand->FailureKind == ovl_fail_bad_deduction &&
10399             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10400   } else {
10401     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10402            (Cand->FailureKind == ovl_fail_bad_deduction &&
10403             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10404   }
10405 
10406   return false;
10407 }
10408 
10409 /// General arity mismatch diagnosis over a candidate in a candidate set.
10410 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10411                                   unsigned NumFormalArgs) {
10412   assert(isa<FunctionDecl>(D) &&
10413       "The templated declaration should at least be a function"
10414       " when diagnosing bad template argument deduction due to too many"
10415       " or too few arguments");
10416 
10417   FunctionDecl *Fn = cast<FunctionDecl>(D);
10418 
10419   // TODO: treat calls to a missing default constructor as a special case
10420   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10421   unsigned MinParams = Fn->getMinRequiredArguments();
10422 
10423   // at least / at most / exactly
10424   unsigned mode, modeCount;
10425   if (NumFormalArgs < MinParams) {
10426     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10427         FnTy->isTemplateVariadic())
10428       mode = 0; // "at least"
10429     else
10430       mode = 2; // "exactly"
10431     modeCount = MinParams;
10432   } else {
10433     if (MinParams != FnTy->getNumParams())
10434       mode = 1; // "at most"
10435     else
10436       mode = 2; // "exactly"
10437     modeCount = FnTy->getNumParams();
10438   }
10439 
10440   std::string Description;
10441   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10442       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10443 
10444   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10445     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10446         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10447         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10448   else
10449     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10450         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10451         << Description << mode << modeCount << NumFormalArgs;
10452 
10453   MaybeEmitInheritedConstructorNote(S, Found);
10454 }
10455 
10456 /// Arity mismatch diagnosis specific to a function overload candidate.
10457 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10458                                   unsigned NumFormalArgs) {
10459   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10460     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10461 }
10462 
10463 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10464   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10465     return TD;
10466   llvm_unreachable("Unsupported: Getting the described template declaration"
10467                    " for bad deduction diagnosis");
10468 }
10469 
10470 /// Diagnose a failed template-argument deduction.
10471 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10472                                  DeductionFailureInfo &DeductionFailure,
10473                                  unsigned NumArgs,
10474                                  bool TakingCandidateAddress) {
10475   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10476   NamedDecl *ParamD;
10477   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10478   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10479   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10480   switch (DeductionFailure.Result) {
10481   case Sema::TDK_Success:
10482     llvm_unreachable("TDK_success while diagnosing bad deduction");
10483 
10484   case Sema::TDK_Incomplete: {
10485     assert(ParamD && "no parameter found for incomplete deduction result");
10486     S.Diag(Templated->getLocation(),
10487            diag::note_ovl_candidate_incomplete_deduction)
10488         << ParamD->getDeclName();
10489     MaybeEmitInheritedConstructorNote(S, Found);
10490     return;
10491   }
10492 
10493   case Sema::TDK_IncompletePack: {
10494     assert(ParamD && "no parameter found for incomplete deduction result");
10495     S.Diag(Templated->getLocation(),
10496            diag::note_ovl_candidate_incomplete_deduction_pack)
10497         << ParamD->getDeclName()
10498         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10499         << *DeductionFailure.getFirstArg();
10500     MaybeEmitInheritedConstructorNote(S, Found);
10501     return;
10502   }
10503 
10504   case Sema::TDK_Underqualified: {
10505     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10506     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10507 
10508     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10509 
10510     // Param will have been canonicalized, but it should just be a
10511     // qualified version of ParamD, so move the qualifiers to that.
10512     QualifierCollector Qs;
10513     Qs.strip(Param);
10514     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10515     assert(S.Context.hasSameType(Param, NonCanonParam));
10516 
10517     // Arg has also been canonicalized, but there's nothing we can do
10518     // about that.  It also doesn't matter as much, because it won't
10519     // have any template parameters in it (because deduction isn't
10520     // done on dependent types).
10521     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10522 
10523     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10524         << ParamD->getDeclName() << Arg << NonCanonParam;
10525     MaybeEmitInheritedConstructorNote(S, Found);
10526     return;
10527   }
10528 
10529   case Sema::TDK_Inconsistent: {
10530     assert(ParamD && "no parameter found for inconsistent deduction result");
10531     int which = 0;
10532     if (isa<TemplateTypeParmDecl>(ParamD))
10533       which = 0;
10534     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10535       // Deduction might have failed because we deduced arguments of two
10536       // different types for a non-type template parameter.
10537       // FIXME: Use a different TDK value for this.
10538       QualType T1 =
10539           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10540       QualType T2 =
10541           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10542       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10543         S.Diag(Templated->getLocation(),
10544                diag::note_ovl_candidate_inconsistent_deduction_types)
10545           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10546           << *DeductionFailure.getSecondArg() << T2;
10547         MaybeEmitInheritedConstructorNote(S, Found);
10548         return;
10549       }
10550 
10551       which = 1;
10552     } else {
10553       which = 2;
10554     }
10555 
10556     // Tweak the diagnostic if the problem is that we deduced packs of
10557     // different arities. We'll print the actual packs anyway in case that
10558     // includes additional useful information.
10559     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10560         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10561         DeductionFailure.getFirstArg()->pack_size() !=
10562             DeductionFailure.getSecondArg()->pack_size()) {
10563       which = 3;
10564     }
10565 
10566     S.Diag(Templated->getLocation(),
10567            diag::note_ovl_candidate_inconsistent_deduction)
10568         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10569         << *DeductionFailure.getSecondArg();
10570     MaybeEmitInheritedConstructorNote(S, Found);
10571     return;
10572   }
10573 
10574   case Sema::TDK_InvalidExplicitArguments:
10575     assert(ParamD && "no parameter found for invalid explicit arguments");
10576     if (ParamD->getDeclName())
10577       S.Diag(Templated->getLocation(),
10578              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10579           << ParamD->getDeclName();
10580     else {
10581       int index = 0;
10582       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10583         index = TTP->getIndex();
10584       else if (NonTypeTemplateParmDecl *NTTP
10585                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10586         index = NTTP->getIndex();
10587       else
10588         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10589       S.Diag(Templated->getLocation(),
10590              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10591           << (index + 1);
10592     }
10593     MaybeEmitInheritedConstructorNote(S, Found);
10594     return;
10595 
10596   case Sema::TDK_ConstraintsNotSatisfied: {
10597     // Format the template argument list into the argument string.
10598     SmallString<128> TemplateArgString;
10599     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10600     TemplateArgString = " ";
10601     TemplateArgString += S.getTemplateArgumentBindingsText(
10602         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10603     if (TemplateArgString.size() == 1)
10604       TemplateArgString.clear();
10605     S.Diag(Templated->getLocation(),
10606            diag::note_ovl_candidate_unsatisfied_constraints)
10607         << TemplateArgString;
10608 
10609     S.DiagnoseUnsatisfiedConstraint(
10610         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10611     return;
10612   }
10613   case Sema::TDK_TooManyArguments:
10614   case Sema::TDK_TooFewArguments:
10615     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10616     return;
10617 
10618   case Sema::TDK_InstantiationDepth:
10619     S.Diag(Templated->getLocation(),
10620            diag::note_ovl_candidate_instantiation_depth);
10621     MaybeEmitInheritedConstructorNote(S, Found);
10622     return;
10623 
10624   case Sema::TDK_SubstitutionFailure: {
10625     // Format the template argument list into the argument string.
10626     SmallString<128> TemplateArgString;
10627     if (TemplateArgumentList *Args =
10628             DeductionFailure.getTemplateArgumentList()) {
10629       TemplateArgString = " ";
10630       TemplateArgString += S.getTemplateArgumentBindingsText(
10631           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10632       if (TemplateArgString.size() == 1)
10633         TemplateArgString.clear();
10634     }
10635 
10636     // If this candidate was disabled by enable_if, say so.
10637     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10638     if (PDiag && PDiag->second.getDiagID() ==
10639           diag::err_typename_nested_not_found_enable_if) {
10640       // FIXME: Use the source range of the condition, and the fully-qualified
10641       //        name of the enable_if template. These are both present in PDiag.
10642       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10643         << "'enable_if'" << TemplateArgString;
10644       return;
10645     }
10646 
10647     // We found a specific requirement that disabled the enable_if.
10648     if (PDiag && PDiag->second.getDiagID() ==
10649         diag::err_typename_nested_not_found_requirement) {
10650       S.Diag(Templated->getLocation(),
10651              diag::note_ovl_candidate_disabled_by_requirement)
10652         << PDiag->second.getStringArg(0) << TemplateArgString;
10653       return;
10654     }
10655 
10656     // Format the SFINAE diagnostic into the argument string.
10657     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10658     //        formatted message in another diagnostic.
10659     SmallString<128> SFINAEArgString;
10660     SourceRange R;
10661     if (PDiag) {
10662       SFINAEArgString = ": ";
10663       R = SourceRange(PDiag->first, PDiag->first);
10664       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10665     }
10666 
10667     S.Diag(Templated->getLocation(),
10668            diag::note_ovl_candidate_substitution_failure)
10669         << TemplateArgString << SFINAEArgString << R;
10670     MaybeEmitInheritedConstructorNote(S, Found);
10671     return;
10672   }
10673 
10674   case Sema::TDK_DeducedMismatch:
10675   case Sema::TDK_DeducedMismatchNested: {
10676     // Format the template argument list into the argument string.
10677     SmallString<128> TemplateArgString;
10678     if (TemplateArgumentList *Args =
10679             DeductionFailure.getTemplateArgumentList()) {
10680       TemplateArgString = " ";
10681       TemplateArgString += S.getTemplateArgumentBindingsText(
10682           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10683       if (TemplateArgString.size() == 1)
10684         TemplateArgString.clear();
10685     }
10686 
10687     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10688         << (*DeductionFailure.getCallArgIndex() + 1)
10689         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10690         << TemplateArgString
10691         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10692     break;
10693   }
10694 
10695   case Sema::TDK_NonDeducedMismatch: {
10696     // FIXME: Provide a source location to indicate what we couldn't match.
10697     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10698     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10699     if (FirstTA.getKind() == TemplateArgument::Template &&
10700         SecondTA.getKind() == TemplateArgument::Template) {
10701       TemplateName FirstTN = FirstTA.getAsTemplate();
10702       TemplateName SecondTN = SecondTA.getAsTemplate();
10703       if (FirstTN.getKind() == TemplateName::Template &&
10704           SecondTN.getKind() == TemplateName::Template) {
10705         if (FirstTN.getAsTemplateDecl()->getName() ==
10706             SecondTN.getAsTemplateDecl()->getName()) {
10707           // FIXME: This fixes a bad diagnostic where both templates are named
10708           // the same.  This particular case is a bit difficult since:
10709           // 1) It is passed as a string to the diagnostic printer.
10710           // 2) The diagnostic printer only attempts to find a better
10711           //    name for types, not decls.
10712           // Ideally, this should folded into the diagnostic printer.
10713           S.Diag(Templated->getLocation(),
10714                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10715               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10716           return;
10717         }
10718       }
10719     }
10720 
10721     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10722         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10723       return;
10724 
10725     // FIXME: For generic lambda parameters, check if the function is a lambda
10726     // call operator, and if so, emit a prettier and more informative
10727     // diagnostic that mentions 'auto' and lambda in addition to
10728     // (or instead of?) the canonical template type parameters.
10729     S.Diag(Templated->getLocation(),
10730            diag::note_ovl_candidate_non_deduced_mismatch)
10731         << FirstTA << SecondTA;
10732     return;
10733   }
10734   // TODO: diagnose these individually, then kill off
10735   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10736   case Sema::TDK_MiscellaneousDeductionFailure:
10737     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10738     MaybeEmitInheritedConstructorNote(S, Found);
10739     return;
10740   case Sema::TDK_CUDATargetMismatch:
10741     S.Diag(Templated->getLocation(),
10742            diag::note_cuda_ovl_candidate_target_mismatch);
10743     return;
10744   }
10745 }
10746 
10747 /// Diagnose a failed template-argument deduction, for function calls.
10748 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10749                                  unsigned NumArgs,
10750                                  bool TakingCandidateAddress) {
10751   unsigned TDK = Cand->DeductionFailure.Result;
10752   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10753     if (CheckArityMismatch(S, Cand, NumArgs))
10754       return;
10755   }
10756   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10757                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10758 }
10759 
10760 /// CUDA: diagnose an invalid call across targets.
10761 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10762   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10763   FunctionDecl *Callee = Cand->Function;
10764 
10765   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10766                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10767 
10768   std::string FnDesc;
10769   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10770       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10771                                 Cand->getRewriteKind(), FnDesc);
10772 
10773   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10774       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10775       << FnDesc /* Ignored */
10776       << CalleeTarget << CallerTarget;
10777 
10778   // This could be an implicit constructor for which we could not infer the
10779   // target due to a collsion. Diagnose that case.
10780   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10781   if (Meth != nullptr && Meth->isImplicit()) {
10782     CXXRecordDecl *ParentClass = Meth->getParent();
10783     Sema::CXXSpecialMember CSM;
10784 
10785     switch (FnKindPair.first) {
10786     default:
10787       return;
10788     case oc_implicit_default_constructor:
10789       CSM = Sema::CXXDefaultConstructor;
10790       break;
10791     case oc_implicit_copy_constructor:
10792       CSM = Sema::CXXCopyConstructor;
10793       break;
10794     case oc_implicit_move_constructor:
10795       CSM = Sema::CXXMoveConstructor;
10796       break;
10797     case oc_implicit_copy_assignment:
10798       CSM = Sema::CXXCopyAssignment;
10799       break;
10800     case oc_implicit_move_assignment:
10801       CSM = Sema::CXXMoveAssignment;
10802       break;
10803     };
10804 
10805     bool ConstRHS = false;
10806     if (Meth->getNumParams()) {
10807       if (const ReferenceType *RT =
10808               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10809         ConstRHS = RT->getPointeeType().isConstQualified();
10810       }
10811     }
10812 
10813     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10814                                               /* ConstRHS */ ConstRHS,
10815                                               /* Diagnose */ true);
10816   }
10817 }
10818 
10819 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10820   FunctionDecl *Callee = Cand->Function;
10821   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10822 
10823   S.Diag(Callee->getLocation(),
10824          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10825       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10826 }
10827 
10828 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10829   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10830   assert(ES.isExplicit() && "not an explicit candidate");
10831 
10832   unsigned Kind;
10833   switch (Cand->Function->getDeclKind()) {
10834   case Decl::Kind::CXXConstructor:
10835     Kind = 0;
10836     break;
10837   case Decl::Kind::CXXConversion:
10838     Kind = 1;
10839     break;
10840   case Decl::Kind::CXXDeductionGuide:
10841     Kind = Cand->Function->isImplicit() ? 0 : 2;
10842     break;
10843   default:
10844     llvm_unreachable("invalid Decl");
10845   }
10846 
10847   // Note the location of the first (in-class) declaration; a redeclaration
10848   // (particularly an out-of-class definition) will typically lack the
10849   // 'explicit' specifier.
10850   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10851   FunctionDecl *First = Cand->Function->getFirstDecl();
10852   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10853     First = Pattern->getFirstDecl();
10854 
10855   S.Diag(First->getLocation(),
10856          diag::note_ovl_candidate_explicit)
10857       << Kind << (ES.getExpr() ? 1 : 0)
10858       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10859 }
10860 
10861 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10862   FunctionDecl *Callee = Cand->Function;
10863 
10864   S.Diag(Callee->getLocation(),
10865          diag::note_ovl_candidate_disabled_by_extension)
10866     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10867 }
10868 
10869 /// Generates a 'note' diagnostic for an overload candidate.  We've
10870 /// already generated a primary error at the call site.
10871 ///
10872 /// It really does need to be a single diagnostic with its caret
10873 /// pointed at the candidate declaration.  Yes, this creates some
10874 /// major challenges of technical writing.  Yes, this makes pointing
10875 /// out problems with specific arguments quite awkward.  It's still
10876 /// better than generating twenty screens of text for every failed
10877 /// overload.
10878 ///
10879 /// It would be great to be able to express per-candidate problems
10880 /// more richly for those diagnostic clients that cared, but we'd
10881 /// still have to be just as careful with the default diagnostics.
10882 /// \param CtorDestAS Addr space of object being constructed (for ctor
10883 /// candidates only).
10884 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10885                                   unsigned NumArgs,
10886                                   bool TakingCandidateAddress,
10887                                   LangAS CtorDestAS = LangAS::Default) {
10888   FunctionDecl *Fn = Cand->Function;
10889 
10890   // Note deleted candidates, but only if they're viable.
10891   if (Cand->Viable) {
10892     if (Fn->isDeleted()) {
10893       std::string FnDesc;
10894       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10895           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10896                                     Cand->getRewriteKind(), FnDesc);
10897 
10898       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10899           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10900           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10901       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10902       return;
10903     }
10904 
10905     // We don't really have anything else to say about viable candidates.
10906     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10907     return;
10908   }
10909 
10910   switch (Cand->FailureKind) {
10911   case ovl_fail_too_many_arguments:
10912   case ovl_fail_too_few_arguments:
10913     return DiagnoseArityMismatch(S, Cand, NumArgs);
10914 
10915   case ovl_fail_bad_deduction:
10916     return DiagnoseBadDeduction(S, Cand, NumArgs,
10917                                 TakingCandidateAddress);
10918 
10919   case ovl_fail_illegal_constructor: {
10920     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10921       << (Fn->getPrimaryTemplate() ? 1 : 0);
10922     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10923     return;
10924   }
10925 
10926   case ovl_fail_object_addrspace_mismatch: {
10927     Qualifiers QualsForPrinting;
10928     QualsForPrinting.setAddressSpace(CtorDestAS);
10929     S.Diag(Fn->getLocation(),
10930            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10931         << QualsForPrinting;
10932     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10933     return;
10934   }
10935 
10936   case ovl_fail_trivial_conversion:
10937   case ovl_fail_bad_final_conversion:
10938   case ovl_fail_final_conversion_not_exact:
10939     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10940 
10941   case ovl_fail_bad_conversion: {
10942     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10943     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10944       if (Cand->Conversions[I].isBad())
10945         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10946 
10947     // FIXME: this currently happens when we're called from SemaInit
10948     // when user-conversion overload fails.  Figure out how to handle
10949     // those conditions and diagnose them well.
10950     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10951   }
10952 
10953   case ovl_fail_bad_target:
10954     return DiagnoseBadTarget(S, Cand);
10955 
10956   case ovl_fail_enable_if:
10957     return DiagnoseFailedEnableIfAttr(S, Cand);
10958 
10959   case ovl_fail_explicit:
10960     return DiagnoseFailedExplicitSpec(S, Cand);
10961 
10962   case ovl_fail_ext_disabled:
10963     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10964 
10965   case ovl_fail_inhctor_slice:
10966     // It's generally not interesting to note copy/move constructors here.
10967     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10968       return;
10969     S.Diag(Fn->getLocation(),
10970            diag::note_ovl_candidate_inherited_constructor_slice)
10971       << (Fn->getPrimaryTemplate() ? 1 : 0)
10972       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10973     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10974     return;
10975 
10976   case ovl_fail_addr_not_available: {
10977     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10978     (void)Available;
10979     assert(!Available);
10980     break;
10981   }
10982   case ovl_non_default_multiversion_function:
10983     // Do nothing, these should simply be ignored.
10984     break;
10985 
10986   case ovl_fail_constraints_not_satisfied: {
10987     std::string FnDesc;
10988     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10989         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10990                                   Cand->getRewriteKind(), FnDesc);
10991 
10992     S.Diag(Fn->getLocation(),
10993            diag::note_ovl_candidate_constraints_not_satisfied)
10994         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10995         << FnDesc /* Ignored */;
10996     ConstraintSatisfaction Satisfaction;
10997     if (S.CheckFunctionConstraints(Fn, Satisfaction))
10998       break;
10999     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11000   }
11001   }
11002 }
11003 
11004 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11005   // Desugar the type of the surrogate down to a function type,
11006   // retaining as many typedefs as possible while still showing
11007   // the function type (and, therefore, its parameter types).
11008   QualType FnType = Cand->Surrogate->getConversionType();
11009   bool isLValueReference = false;
11010   bool isRValueReference = false;
11011   bool isPointer = false;
11012   if (const LValueReferenceType *FnTypeRef =
11013         FnType->getAs<LValueReferenceType>()) {
11014     FnType = FnTypeRef->getPointeeType();
11015     isLValueReference = true;
11016   } else if (const RValueReferenceType *FnTypeRef =
11017                FnType->getAs<RValueReferenceType>()) {
11018     FnType = FnTypeRef->getPointeeType();
11019     isRValueReference = true;
11020   }
11021   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11022     FnType = FnTypePtr->getPointeeType();
11023     isPointer = true;
11024   }
11025   // Desugar down to a function type.
11026   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11027   // Reconstruct the pointer/reference as appropriate.
11028   if (isPointer) FnType = S.Context.getPointerType(FnType);
11029   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11030   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11031 
11032   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11033     << FnType;
11034 }
11035 
11036 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11037                                          SourceLocation OpLoc,
11038                                          OverloadCandidate *Cand) {
11039   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11040   std::string TypeStr("operator");
11041   TypeStr += Opc;
11042   TypeStr += "(";
11043   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11044   if (Cand->Conversions.size() == 1) {
11045     TypeStr += ")";
11046     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11047   } else {
11048     TypeStr += ", ";
11049     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11050     TypeStr += ")";
11051     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11052   }
11053 }
11054 
11055 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11056                                          OverloadCandidate *Cand) {
11057   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11058     if (ICS.isBad()) break; // all meaningless after first invalid
11059     if (!ICS.isAmbiguous()) continue;
11060 
11061     ICS.DiagnoseAmbiguousConversion(
11062         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11063   }
11064 }
11065 
11066 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11067   if (Cand->Function)
11068     return Cand->Function->getLocation();
11069   if (Cand->IsSurrogate)
11070     return Cand->Surrogate->getLocation();
11071   return SourceLocation();
11072 }
11073 
11074 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11075   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11076   case Sema::TDK_Success:
11077   case Sema::TDK_NonDependentConversionFailure:
11078     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11079 
11080   case Sema::TDK_Invalid:
11081   case Sema::TDK_Incomplete:
11082   case Sema::TDK_IncompletePack:
11083     return 1;
11084 
11085   case Sema::TDK_Underqualified:
11086   case Sema::TDK_Inconsistent:
11087     return 2;
11088 
11089   case Sema::TDK_SubstitutionFailure:
11090   case Sema::TDK_DeducedMismatch:
11091   case Sema::TDK_ConstraintsNotSatisfied:
11092   case Sema::TDK_DeducedMismatchNested:
11093   case Sema::TDK_NonDeducedMismatch:
11094   case Sema::TDK_MiscellaneousDeductionFailure:
11095   case Sema::TDK_CUDATargetMismatch:
11096     return 3;
11097 
11098   case Sema::TDK_InstantiationDepth:
11099     return 4;
11100 
11101   case Sema::TDK_InvalidExplicitArguments:
11102     return 5;
11103 
11104   case Sema::TDK_TooManyArguments:
11105   case Sema::TDK_TooFewArguments:
11106     return 6;
11107   }
11108   llvm_unreachable("Unhandled deduction result");
11109 }
11110 
11111 namespace {
11112 struct CompareOverloadCandidatesForDisplay {
11113   Sema &S;
11114   SourceLocation Loc;
11115   size_t NumArgs;
11116   OverloadCandidateSet::CandidateSetKind CSK;
11117 
11118   CompareOverloadCandidatesForDisplay(
11119       Sema &S, SourceLocation Loc, size_t NArgs,
11120       OverloadCandidateSet::CandidateSetKind CSK)
11121       : S(S), NumArgs(NArgs), CSK(CSK) {}
11122 
11123   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11124     // If there are too many or too few arguments, that's the high-order bit we
11125     // want to sort by, even if the immediate failure kind was something else.
11126     if (C->FailureKind == ovl_fail_too_many_arguments ||
11127         C->FailureKind == ovl_fail_too_few_arguments)
11128       return static_cast<OverloadFailureKind>(C->FailureKind);
11129 
11130     if (C->Function) {
11131       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11132         return ovl_fail_too_many_arguments;
11133       if (NumArgs < C->Function->getMinRequiredArguments())
11134         return ovl_fail_too_few_arguments;
11135     }
11136 
11137     return static_cast<OverloadFailureKind>(C->FailureKind);
11138   }
11139 
11140   bool operator()(const OverloadCandidate *L,
11141                   const OverloadCandidate *R) {
11142     // Fast-path this check.
11143     if (L == R) return false;
11144 
11145     // Order first by viability.
11146     if (L->Viable) {
11147       if (!R->Viable) return true;
11148 
11149       // TODO: introduce a tri-valued comparison for overload
11150       // candidates.  Would be more worthwhile if we had a sort
11151       // that could exploit it.
11152       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11153         return true;
11154       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11155         return false;
11156     } else if (R->Viable)
11157       return false;
11158 
11159     assert(L->Viable == R->Viable);
11160 
11161     // Criteria by which we can sort non-viable candidates:
11162     if (!L->Viable) {
11163       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11164       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11165 
11166       // 1. Arity mismatches come after other candidates.
11167       if (LFailureKind == ovl_fail_too_many_arguments ||
11168           LFailureKind == ovl_fail_too_few_arguments) {
11169         if (RFailureKind == ovl_fail_too_many_arguments ||
11170             RFailureKind == ovl_fail_too_few_arguments) {
11171           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11172           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11173           if (LDist == RDist) {
11174             if (LFailureKind == RFailureKind)
11175               // Sort non-surrogates before surrogates.
11176               return !L->IsSurrogate && R->IsSurrogate;
11177             // Sort candidates requiring fewer parameters than there were
11178             // arguments given after candidates requiring more parameters
11179             // than there were arguments given.
11180             return LFailureKind == ovl_fail_too_many_arguments;
11181           }
11182           return LDist < RDist;
11183         }
11184         return false;
11185       }
11186       if (RFailureKind == ovl_fail_too_many_arguments ||
11187           RFailureKind == ovl_fail_too_few_arguments)
11188         return true;
11189 
11190       // 2. Bad conversions come first and are ordered by the number
11191       // of bad conversions and quality of good conversions.
11192       if (LFailureKind == ovl_fail_bad_conversion) {
11193         if (RFailureKind != ovl_fail_bad_conversion)
11194           return true;
11195 
11196         // The conversion that can be fixed with a smaller number of changes,
11197         // comes first.
11198         unsigned numLFixes = L->Fix.NumConversionsFixed;
11199         unsigned numRFixes = R->Fix.NumConversionsFixed;
11200         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11201         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11202         if (numLFixes != numRFixes) {
11203           return numLFixes < numRFixes;
11204         }
11205 
11206         // If there's any ordering between the defined conversions...
11207         // FIXME: this might not be transitive.
11208         assert(L->Conversions.size() == R->Conversions.size());
11209 
11210         int leftBetter = 0;
11211         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11212         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11213           switch (CompareImplicitConversionSequences(S, Loc,
11214                                                      L->Conversions[I],
11215                                                      R->Conversions[I])) {
11216           case ImplicitConversionSequence::Better:
11217             leftBetter++;
11218             break;
11219 
11220           case ImplicitConversionSequence::Worse:
11221             leftBetter--;
11222             break;
11223 
11224           case ImplicitConversionSequence::Indistinguishable:
11225             break;
11226           }
11227         }
11228         if (leftBetter > 0) return true;
11229         if (leftBetter < 0) return false;
11230 
11231       } else if (RFailureKind == ovl_fail_bad_conversion)
11232         return false;
11233 
11234       if (LFailureKind == ovl_fail_bad_deduction) {
11235         if (RFailureKind != ovl_fail_bad_deduction)
11236           return true;
11237 
11238         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11239           return RankDeductionFailure(L->DeductionFailure)
11240                < RankDeductionFailure(R->DeductionFailure);
11241       } else if (RFailureKind == ovl_fail_bad_deduction)
11242         return false;
11243 
11244       // TODO: others?
11245     }
11246 
11247     // Sort everything else by location.
11248     SourceLocation LLoc = GetLocationForCandidate(L);
11249     SourceLocation RLoc = GetLocationForCandidate(R);
11250 
11251     // Put candidates without locations (e.g. builtins) at the end.
11252     if (LLoc.isInvalid()) return false;
11253     if (RLoc.isInvalid()) return true;
11254 
11255     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11256   }
11257 };
11258 }
11259 
11260 /// CompleteNonViableCandidate - Normally, overload resolution only
11261 /// computes up to the first bad conversion. Produces the FixIt set if
11262 /// possible.
11263 static void
11264 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11265                            ArrayRef<Expr *> Args,
11266                            OverloadCandidateSet::CandidateSetKind CSK) {
11267   assert(!Cand->Viable);
11268 
11269   // Don't do anything on failures other than bad conversion.
11270   if (Cand->FailureKind != ovl_fail_bad_conversion)
11271     return;
11272 
11273   // We only want the FixIts if all the arguments can be corrected.
11274   bool Unfixable = false;
11275   // Use a implicit copy initialization to check conversion fixes.
11276   Cand->Fix.setConversionChecker(TryCopyInitialization);
11277 
11278   // Attempt to fix the bad conversion.
11279   unsigned ConvCount = Cand->Conversions.size();
11280   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11281        ++ConvIdx) {
11282     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11283     if (Cand->Conversions[ConvIdx].isInitialized() &&
11284         Cand->Conversions[ConvIdx].isBad()) {
11285       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11286       break;
11287     }
11288   }
11289 
11290   // FIXME: this should probably be preserved from the overload
11291   // operation somehow.
11292   bool SuppressUserConversions = false;
11293 
11294   unsigned ConvIdx = 0;
11295   unsigned ArgIdx = 0;
11296   ArrayRef<QualType> ParamTypes;
11297   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11298 
11299   if (Cand->IsSurrogate) {
11300     QualType ConvType
11301       = Cand->Surrogate->getConversionType().getNonReferenceType();
11302     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11303       ConvType = ConvPtrType->getPointeeType();
11304     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11305     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11306     ConvIdx = 1;
11307   } else if (Cand->Function) {
11308     ParamTypes =
11309         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11310     if (isa<CXXMethodDecl>(Cand->Function) &&
11311         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11312       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11313       ConvIdx = 1;
11314       if (CSK == OverloadCandidateSet::CSK_Operator &&
11315           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11316         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11317         ArgIdx = 1;
11318     }
11319   } else {
11320     // Builtin operator.
11321     assert(ConvCount <= 3);
11322     ParamTypes = Cand->BuiltinParamTypes;
11323   }
11324 
11325   // Fill in the rest of the conversions.
11326   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11327        ConvIdx != ConvCount;
11328        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11329     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11330     if (Cand->Conversions[ConvIdx].isInitialized()) {
11331       // We've already checked this conversion.
11332     } else if (ParamIdx < ParamTypes.size()) {
11333       if (ParamTypes[ParamIdx]->isDependentType())
11334         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11335             Args[ArgIdx]->getType());
11336       else {
11337         Cand->Conversions[ConvIdx] =
11338             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11339                                   SuppressUserConversions,
11340                                   /*InOverloadResolution=*/true,
11341                                   /*AllowObjCWritebackConversion=*/
11342                                   S.getLangOpts().ObjCAutoRefCount);
11343         // Store the FixIt in the candidate if it exists.
11344         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11345           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11346       }
11347     } else
11348       Cand->Conversions[ConvIdx].setEllipsis();
11349   }
11350 }
11351 
11352 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11353     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11354     SourceLocation OpLoc,
11355     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11356   // Sort the candidates by viability and position.  Sorting directly would
11357   // be prohibitive, so we make a set of pointers and sort those.
11358   SmallVector<OverloadCandidate*, 32> Cands;
11359   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11360   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11361     if (!Filter(*Cand))
11362       continue;
11363     switch (OCD) {
11364     case OCD_AllCandidates:
11365       if (!Cand->Viable) {
11366         if (!Cand->Function && !Cand->IsSurrogate) {
11367           // This a non-viable builtin candidate.  We do not, in general,
11368           // want to list every possible builtin candidate.
11369           continue;
11370         }
11371         CompleteNonViableCandidate(S, Cand, Args, Kind);
11372       }
11373       break;
11374 
11375     case OCD_ViableCandidates:
11376       if (!Cand->Viable)
11377         continue;
11378       break;
11379 
11380     case OCD_AmbiguousCandidates:
11381       if (!Cand->Best)
11382         continue;
11383       break;
11384     }
11385 
11386     Cands.push_back(Cand);
11387   }
11388 
11389   llvm::stable_sort(
11390       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11391 
11392   return Cands;
11393 }
11394 
11395 /// When overload resolution fails, prints diagnostic messages containing the
11396 /// candidates in the candidate set.
11397 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11398     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11399     StringRef Opc, SourceLocation OpLoc,
11400     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11401 
11402   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11403 
11404   S.Diag(PD.first, PD.second);
11405 
11406   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11407 
11408   if (OCD == OCD_AmbiguousCandidates)
11409     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11410 }
11411 
11412 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11413                                           ArrayRef<OverloadCandidate *> Cands,
11414                                           StringRef Opc, SourceLocation OpLoc) {
11415   bool ReportedAmbiguousConversions = false;
11416 
11417   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11418   unsigned CandsShown = 0;
11419   auto I = Cands.begin(), E = Cands.end();
11420   for (; I != E; ++I) {
11421     OverloadCandidate *Cand = *I;
11422 
11423     // Set an arbitrary limit on the number of candidate functions we'll spam
11424     // the user with.  FIXME: This limit should depend on details of the
11425     // candidate list.
11426     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11427       break;
11428     }
11429     ++CandsShown;
11430 
11431     if (Cand->Function)
11432       NoteFunctionCandidate(S, Cand, Args.size(),
11433                             /*TakingCandidateAddress=*/false, DestAS);
11434     else if (Cand->IsSurrogate)
11435       NoteSurrogateCandidate(S, Cand);
11436     else {
11437       assert(Cand->Viable &&
11438              "Non-viable built-in candidates are not added to Cands.");
11439       // Generally we only see ambiguities including viable builtin
11440       // operators if overload resolution got screwed up by an
11441       // ambiguous user-defined conversion.
11442       //
11443       // FIXME: It's quite possible for different conversions to see
11444       // different ambiguities, though.
11445       if (!ReportedAmbiguousConversions) {
11446         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11447         ReportedAmbiguousConversions = true;
11448       }
11449 
11450       // If this is a viable builtin, print it.
11451       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11452     }
11453   }
11454 
11455   if (I != E)
11456     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11457 }
11458 
11459 static SourceLocation
11460 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11461   return Cand->Specialization ? Cand->Specialization->getLocation()
11462                               : SourceLocation();
11463 }
11464 
11465 namespace {
11466 struct CompareTemplateSpecCandidatesForDisplay {
11467   Sema &S;
11468   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11469 
11470   bool operator()(const TemplateSpecCandidate *L,
11471                   const TemplateSpecCandidate *R) {
11472     // Fast-path this check.
11473     if (L == R)
11474       return false;
11475 
11476     // Assuming that both candidates are not matches...
11477 
11478     // Sort by the ranking of deduction failures.
11479     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11480       return RankDeductionFailure(L->DeductionFailure) <
11481              RankDeductionFailure(R->DeductionFailure);
11482 
11483     // Sort everything else by location.
11484     SourceLocation LLoc = GetLocationForCandidate(L);
11485     SourceLocation RLoc = GetLocationForCandidate(R);
11486 
11487     // Put candidates without locations (e.g. builtins) at the end.
11488     if (LLoc.isInvalid())
11489       return false;
11490     if (RLoc.isInvalid())
11491       return true;
11492 
11493     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11494   }
11495 };
11496 }
11497 
11498 /// Diagnose a template argument deduction failure.
11499 /// We are treating these failures as overload failures due to bad
11500 /// deductions.
11501 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11502                                                  bool ForTakingAddress) {
11503   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11504                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11505 }
11506 
11507 void TemplateSpecCandidateSet::destroyCandidates() {
11508   for (iterator i = begin(), e = end(); i != e; ++i) {
11509     i->DeductionFailure.Destroy();
11510   }
11511 }
11512 
11513 void TemplateSpecCandidateSet::clear() {
11514   destroyCandidates();
11515   Candidates.clear();
11516 }
11517 
11518 /// NoteCandidates - When no template specialization match is found, prints
11519 /// diagnostic messages containing the non-matching specializations that form
11520 /// the candidate set.
11521 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11522 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11523 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11524   // Sort the candidates by position (assuming no candidate is a match).
11525   // Sorting directly would be prohibitive, so we make a set of pointers
11526   // and sort those.
11527   SmallVector<TemplateSpecCandidate *, 32> Cands;
11528   Cands.reserve(size());
11529   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11530     if (Cand->Specialization)
11531       Cands.push_back(Cand);
11532     // Otherwise, this is a non-matching builtin candidate.  We do not,
11533     // in general, want to list every possible builtin candidate.
11534   }
11535 
11536   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11537 
11538   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11539   // for generalization purposes (?).
11540   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11541 
11542   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11543   unsigned CandsShown = 0;
11544   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11545     TemplateSpecCandidate *Cand = *I;
11546 
11547     // Set an arbitrary limit on the number of candidates we'll spam
11548     // the user with.  FIXME: This limit should depend on details of the
11549     // candidate list.
11550     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11551       break;
11552     ++CandsShown;
11553 
11554     assert(Cand->Specialization &&
11555            "Non-matching built-in candidates are not added to Cands.");
11556     Cand->NoteDeductionFailure(S, ForTakingAddress);
11557   }
11558 
11559   if (I != E)
11560     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11561 }
11562 
11563 // [PossiblyAFunctionType]  -->   [Return]
11564 // NonFunctionType --> NonFunctionType
11565 // R (A) --> R(A)
11566 // R (*)(A) --> R (A)
11567 // R (&)(A) --> R (A)
11568 // R (S::*)(A) --> R (A)
11569 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11570   QualType Ret = PossiblyAFunctionType;
11571   if (const PointerType *ToTypePtr =
11572     PossiblyAFunctionType->getAs<PointerType>())
11573     Ret = ToTypePtr->getPointeeType();
11574   else if (const ReferenceType *ToTypeRef =
11575     PossiblyAFunctionType->getAs<ReferenceType>())
11576     Ret = ToTypeRef->getPointeeType();
11577   else if (const MemberPointerType *MemTypePtr =
11578     PossiblyAFunctionType->getAs<MemberPointerType>())
11579     Ret = MemTypePtr->getPointeeType();
11580   Ret =
11581     Context.getCanonicalType(Ret).getUnqualifiedType();
11582   return Ret;
11583 }
11584 
11585 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11586                                  bool Complain = true) {
11587   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11588       S.DeduceReturnType(FD, Loc, Complain))
11589     return true;
11590 
11591   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11592   if (S.getLangOpts().CPlusPlus17 &&
11593       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11594       !S.ResolveExceptionSpec(Loc, FPT))
11595     return true;
11596 
11597   return false;
11598 }
11599 
11600 namespace {
11601 // A helper class to help with address of function resolution
11602 // - allows us to avoid passing around all those ugly parameters
11603 class AddressOfFunctionResolver {
11604   Sema& S;
11605   Expr* SourceExpr;
11606   const QualType& TargetType;
11607   QualType TargetFunctionType; // Extracted function type from target type
11608 
11609   bool Complain;
11610   //DeclAccessPair& ResultFunctionAccessPair;
11611   ASTContext& Context;
11612 
11613   bool TargetTypeIsNonStaticMemberFunction;
11614   bool FoundNonTemplateFunction;
11615   bool StaticMemberFunctionFromBoundPointer;
11616   bool HasComplained;
11617 
11618   OverloadExpr::FindResult OvlExprInfo;
11619   OverloadExpr *OvlExpr;
11620   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11621   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11622   TemplateSpecCandidateSet FailedCandidates;
11623 
11624 public:
11625   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11626                             const QualType &TargetType, bool Complain)
11627       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11628         Complain(Complain), Context(S.getASTContext()),
11629         TargetTypeIsNonStaticMemberFunction(
11630             !!TargetType->getAs<MemberPointerType>()),
11631         FoundNonTemplateFunction(false),
11632         StaticMemberFunctionFromBoundPointer(false),
11633         HasComplained(false),
11634         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11635         OvlExpr(OvlExprInfo.Expression),
11636         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11637     ExtractUnqualifiedFunctionTypeFromTargetType();
11638 
11639     if (TargetFunctionType->isFunctionType()) {
11640       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11641         if (!UME->isImplicitAccess() &&
11642             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11643           StaticMemberFunctionFromBoundPointer = true;
11644     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11645       DeclAccessPair dap;
11646       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11647               OvlExpr, false, &dap)) {
11648         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11649           if (!Method->isStatic()) {
11650             // If the target type is a non-function type and the function found
11651             // is a non-static member function, pretend as if that was the
11652             // target, it's the only possible type to end up with.
11653             TargetTypeIsNonStaticMemberFunction = true;
11654 
11655             // And skip adding the function if its not in the proper form.
11656             // We'll diagnose this due to an empty set of functions.
11657             if (!OvlExprInfo.HasFormOfMemberPointer)
11658               return;
11659           }
11660 
11661         Matches.push_back(std::make_pair(dap, Fn));
11662       }
11663       return;
11664     }
11665 
11666     if (OvlExpr->hasExplicitTemplateArgs())
11667       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11668 
11669     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11670       // C++ [over.over]p4:
11671       //   If more than one function is selected, [...]
11672       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11673         if (FoundNonTemplateFunction)
11674           EliminateAllTemplateMatches();
11675         else
11676           EliminateAllExceptMostSpecializedTemplate();
11677       }
11678     }
11679 
11680     if (S.getLangOpts().CUDA && Matches.size() > 1)
11681       EliminateSuboptimalCudaMatches();
11682   }
11683 
11684   bool hasComplained() const { return HasComplained; }
11685 
11686 private:
11687   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11688     QualType Discard;
11689     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11690            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11691   }
11692 
11693   /// \return true if A is considered a better overload candidate for the
11694   /// desired type than B.
11695   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11696     // If A doesn't have exactly the correct type, we don't want to classify it
11697     // as "better" than anything else. This way, the user is required to
11698     // disambiguate for us if there are multiple candidates and no exact match.
11699     return candidateHasExactlyCorrectType(A) &&
11700            (!candidateHasExactlyCorrectType(B) ||
11701             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11702   }
11703 
11704   /// \return true if we were able to eliminate all but one overload candidate,
11705   /// false otherwise.
11706   bool eliminiateSuboptimalOverloadCandidates() {
11707     // Same algorithm as overload resolution -- one pass to pick the "best",
11708     // another pass to be sure that nothing is better than the best.
11709     auto Best = Matches.begin();
11710     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11711       if (isBetterCandidate(I->second, Best->second))
11712         Best = I;
11713 
11714     const FunctionDecl *BestFn = Best->second;
11715     auto IsBestOrInferiorToBest = [this, BestFn](
11716         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11717       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11718     };
11719 
11720     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11721     // option, so we can potentially give the user a better error
11722     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11723       return false;
11724     Matches[0] = *Best;
11725     Matches.resize(1);
11726     return true;
11727   }
11728 
11729   bool isTargetTypeAFunction() const {
11730     return TargetFunctionType->isFunctionType();
11731   }
11732 
11733   // [ToType]     [Return]
11734 
11735   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11736   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11737   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11738   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11739     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11740   }
11741 
11742   // return true if any matching specializations were found
11743   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11744                                    const DeclAccessPair& CurAccessFunPair) {
11745     if (CXXMethodDecl *Method
11746               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11747       // Skip non-static function templates when converting to pointer, and
11748       // static when converting to member pointer.
11749       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11750         return false;
11751     }
11752     else if (TargetTypeIsNonStaticMemberFunction)
11753       return false;
11754 
11755     // C++ [over.over]p2:
11756     //   If the name is a function template, template argument deduction is
11757     //   done (14.8.2.2), and if the argument deduction succeeds, the
11758     //   resulting template argument list is used to generate a single
11759     //   function template specialization, which is added to the set of
11760     //   overloaded functions considered.
11761     FunctionDecl *Specialization = nullptr;
11762     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11763     if (Sema::TemplateDeductionResult Result
11764           = S.DeduceTemplateArguments(FunctionTemplate,
11765                                       &OvlExplicitTemplateArgs,
11766                                       TargetFunctionType, Specialization,
11767                                       Info, /*IsAddressOfFunction*/true)) {
11768       // Make a note of the failed deduction for diagnostics.
11769       FailedCandidates.addCandidate()
11770           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11771                MakeDeductionFailureInfo(Context, Result, Info));
11772       return false;
11773     }
11774 
11775     // Template argument deduction ensures that we have an exact match or
11776     // compatible pointer-to-function arguments that would be adjusted by ICS.
11777     // This function template specicalization works.
11778     assert(S.isSameOrCompatibleFunctionType(
11779               Context.getCanonicalType(Specialization->getType()),
11780               Context.getCanonicalType(TargetFunctionType)));
11781 
11782     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11783       return false;
11784 
11785     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11786     return true;
11787   }
11788 
11789   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11790                                       const DeclAccessPair& CurAccessFunPair) {
11791     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11792       // Skip non-static functions when converting to pointer, and static
11793       // when converting to member pointer.
11794       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11795         return false;
11796     }
11797     else if (TargetTypeIsNonStaticMemberFunction)
11798       return false;
11799 
11800     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11801       if (S.getLangOpts().CUDA)
11802         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11803           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11804             return false;
11805       if (FunDecl->isMultiVersion()) {
11806         const auto *TA = FunDecl->getAttr<TargetAttr>();
11807         if (TA && !TA->isDefaultVersion())
11808           return false;
11809       }
11810 
11811       // If any candidate has a placeholder return type, trigger its deduction
11812       // now.
11813       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11814                                Complain)) {
11815         HasComplained |= Complain;
11816         return false;
11817       }
11818 
11819       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11820         return false;
11821 
11822       // If we're in C, we need to support types that aren't exactly identical.
11823       if (!S.getLangOpts().CPlusPlus ||
11824           candidateHasExactlyCorrectType(FunDecl)) {
11825         Matches.push_back(std::make_pair(
11826             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11827         FoundNonTemplateFunction = true;
11828         return true;
11829       }
11830     }
11831 
11832     return false;
11833   }
11834 
11835   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11836     bool Ret = false;
11837 
11838     // If the overload expression doesn't have the form of a pointer to
11839     // member, don't try to convert it to a pointer-to-member type.
11840     if (IsInvalidFormOfPointerToMemberFunction())
11841       return false;
11842 
11843     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11844                                E = OvlExpr->decls_end();
11845          I != E; ++I) {
11846       // Look through any using declarations to find the underlying function.
11847       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11848 
11849       // C++ [over.over]p3:
11850       //   Non-member functions and static member functions match
11851       //   targets of type "pointer-to-function" or "reference-to-function."
11852       //   Nonstatic member functions match targets of
11853       //   type "pointer-to-member-function."
11854       // Note that according to DR 247, the containing class does not matter.
11855       if (FunctionTemplateDecl *FunctionTemplate
11856                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11857         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11858           Ret = true;
11859       }
11860       // If we have explicit template arguments supplied, skip non-templates.
11861       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11862                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11863         Ret = true;
11864     }
11865     assert(Ret || Matches.empty());
11866     return Ret;
11867   }
11868 
11869   void EliminateAllExceptMostSpecializedTemplate() {
11870     //   [...] and any given function template specialization F1 is
11871     //   eliminated if the set contains a second function template
11872     //   specialization whose function template is more specialized
11873     //   than the function template of F1 according to the partial
11874     //   ordering rules of 14.5.5.2.
11875 
11876     // The algorithm specified above is quadratic. We instead use a
11877     // two-pass algorithm (similar to the one used to identify the
11878     // best viable function in an overload set) that identifies the
11879     // best function template (if it exists).
11880 
11881     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11882     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11883       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11884 
11885     // TODO: It looks like FailedCandidates does not serve much purpose
11886     // here, since the no_viable diagnostic has index 0.
11887     UnresolvedSetIterator Result = S.getMostSpecialized(
11888         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11889         SourceExpr->getBeginLoc(), S.PDiag(),
11890         S.PDiag(diag::err_addr_ovl_ambiguous)
11891             << Matches[0].second->getDeclName(),
11892         S.PDiag(diag::note_ovl_candidate)
11893             << (unsigned)oc_function << (unsigned)ocs_described_template,
11894         Complain, TargetFunctionType);
11895 
11896     if (Result != MatchesCopy.end()) {
11897       // Make it the first and only element
11898       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11899       Matches[0].second = cast<FunctionDecl>(*Result);
11900       Matches.resize(1);
11901     } else
11902       HasComplained |= Complain;
11903   }
11904 
11905   void EliminateAllTemplateMatches() {
11906     //   [...] any function template specializations in the set are
11907     //   eliminated if the set also contains a non-template function, [...]
11908     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11909       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11910         ++I;
11911       else {
11912         Matches[I] = Matches[--N];
11913         Matches.resize(N);
11914       }
11915     }
11916   }
11917 
11918   void EliminateSuboptimalCudaMatches() {
11919     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11920   }
11921 
11922 public:
11923   void ComplainNoMatchesFound() const {
11924     assert(Matches.empty());
11925     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11926         << OvlExpr->getName() << TargetFunctionType
11927         << OvlExpr->getSourceRange();
11928     if (FailedCandidates.empty())
11929       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11930                                   /*TakingAddress=*/true);
11931     else {
11932       // We have some deduction failure messages. Use them to diagnose
11933       // the function templates, and diagnose the non-template candidates
11934       // normally.
11935       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11936                                  IEnd = OvlExpr->decls_end();
11937            I != IEnd; ++I)
11938         if (FunctionDecl *Fun =
11939                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11940           if (!functionHasPassObjectSizeParams(Fun))
11941             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11942                                     /*TakingAddress=*/true);
11943       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11944     }
11945   }
11946 
11947   bool IsInvalidFormOfPointerToMemberFunction() const {
11948     return TargetTypeIsNonStaticMemberFunction &&
11949       !OvlExprInfo.HasFormOfMemberPointer;
11950   }
11951 
11952   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11953       // TODO: Should we condition this on whether any functions might
11954       // have matched, or is it more appropriate to do that in callers?
11955       // TODO: a fixit wouldn't hurt.
11956       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11957         << TargetType << OvlExpr->getSourceRange();
11958   }
11959 
11960   bool IsStaticMemberFunctionFromBoundPointer() const {
11961     return StaticMemberFunctionFromBoundPointer;
11962   }
11963 
11964   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11965     S.Diag(OvlExpr->getBeginLoc(),
11966            diag::err_invalid_form_pointer_member_function)
11967         << OvlExpr->getSourceRange();
11968   }
11969 
11970   void ComplainOfInvalidConversion() const {
11971     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11972         << OvlExpr->getName() << TargetType;
11973   }
11974 
11975   void ComplainMultipleMatchesFound() const {
11976     assert(Matches.size() > 1);
11977     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11978         << OvlExpr->getName() << OvlExpr->getSourceRange();
11979     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11980                                 /*TakingAddress=*/true);
11981   }
11982 
11983   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11984 
11985   int getNumMatches() const { return Matches.size(); }
11986 
11987   FunctionDecl* getMatchingFunctionDecl() const {
11988     if (Matches.size() != 1) return nullptr;
11989     return Matches[0].second;
11990   }
11991 
11992   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11993     if (Matches.size() != 1) return nullptr;
11994     return &Matches[0].first;
11995   }
11996 };
11997 }
11998 
11999 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12000 /// an overloaded function (C++ [over.over]), where @p From is an
12001 /// expression with overloaded function type and @p ToType is the type
12002 /// we're trying to resolve to. For example:
12003 ///
12004 /// @code
12005 /// int f(double);
12006 /// int f(int);
12007 ///
12008 /// int (*pfd)(double) = f; // selects f(double)
12009 /// @endcode
12010 ///
12011 /// This routine returns the resulting FunctionDecl if it could be
12012 /// resolved, and NULL otherwise. When @p Complain is true, this
12013 /// routine will emit diagnostics if there is an error.
12014 FunctionDecl *
12015 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12016                                          QualType TargetType,
12017                                          bool Complain,
12018                                          DeclAccessPair &FoundResult,
12019                                          bool *pHadMultipleCandidates) {
12020   assert(AddressOfExpr->getType() == Context.OverloadTy);
12021 
12022   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12023                                      Complain);
12024   int NumMatches = Resolver.getNumMatches();
12025   FunctionDecl *Fn = nullptr;
12026   bool ShouldComplain = Complain && !Resolver.hasComplained();
12027   if (NumMatches == 0 && ShouldComplain) {
12028     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12029       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12030     else
12031       Resolver.ComplainNoMatchesFound();
12032   }
12033   else if (NumMatches > 1 && ShouldComplain)
12034     Resolver.ComplainMultipleMatchesFound();
12035   else if (NumMatches == 1) {
12036     Fn = Resolver.getMatchingFunctionDecl();
12037     assert(Fn);
12038     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12039       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12040     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12041     if (Complain) {
12042       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12043         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12044       else
12045         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12046     }
12047   }
12048 
12049   if (pHadMultipleCandidates)
12050     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12051   return Fn;
12052 }
12053 
12054 /// Given an expression that refers to an overloaded function, try to
12055 /// resolve that function to a single function that can have its address taken.
12056 /// This will modify `Pair` iff it returns non-null.
12057 ///
12058 /// This routine can only succeed if from all of the candidates in the overload
12059 /// set for SrcExpr that can have their addresses taken, there is one candidate
12060 /// that is more constrained than the rest.
12061 FunctionDecl *
12062 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12063   OverloadExpr::FindResult R = OverloadExpr::find(E);
12064   OverloadExpr *Ovl = R.Expression;
12065   bool IsResultAmbiguous = false;
12066   FunctionDecl *Result = nullptr;
12067   DeclAccessPair DAP;
12068   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12069 
12070   auto CheckMoreConstrained =
12071       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12072         SmallVector<const Expr *, 1> AC1, AC2;
12073         FD1->getAssociatedConstraints(AC1);
12074         FD2->getAssociatedConstraints(AC2);
12075         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12076         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12077           return None;
12078         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12079           return None;
12080         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12081           return None;
12082         return AtLeastAsConstrained1;
12083       };
12084 
12085   // Don't use the AddressOfResolver because we're specifically looking for
12086   // cases where we have one overload candidate that lacks
12087   // enable_if/pass_object_size/...
12088   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12089     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12090     if (!FD)
12091       return nullptr;
12092 
12093     if (!checkAddressOfFunctionIsAvailable(FD))
12094       continue;
12095 
12096     // We have more than one result - see if it is more constrained than the
12097     // previous one.
12098     if (Result) {
12099       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12100                                                                         Result);
12101       if (!MoreConstrainedThanPrevious) {
12102         IsResultAmbiguous = true;
12103         AmbiguousDecls.push_back(FD);
12104         continue;
12105       }
12106       if (!*MoreConstrainedThanPrevious)
12107         continue;
12108       // FD is more constrained - replace Result with it.
12109     }
12110     IsResultAmbiguous = false;
12111     DAP = I.getPair();
12112     Result = FD;
12113   }
12114 
12115   if (IsResultAmbiguous)
12116     return nullptr;
12117 
12118   if (Result) {
12119     SmallVector<const Expr *, 1> ResultAC;
12120     // We skipped over some ambiguous declarations which might be ambiguous with
12121     // the selected result.
12122     for (FunctionDecl *Skipped : AmbiguousDecls)
12123       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12124         return nullptr;
12125     Pair = DAP;
12126   }
12127   return Result;
12128 }
12129 
12130 /// Given an overloaded function, tries to turn it into a non-overloaded
12131 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12132 /// will perform access checks, diagnose the use of the resultant decl, and, if
12133 /// requested, potentially perform a function-to-pointer decay.
12134 ///
12135 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12136 /// Otherwise, returns true. This may emit diagnostics and return true.
12137 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12138     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12139   Expr *E = SrcExpr.get();
12140   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12141 
12142   DeclAccessPair DAP;
12143   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12144   if (!Found || Found->isCPUDispatchMultiVersion() ||
12145       Found->isCPUSpecificMultiVersion())
12146     return false;
12147 
12148   // Emitting multiple diagnostics for a function that is both inaccessible and
12149   // unavailable is consistent with our behavior elsewhere. So, always check
12150   // for both.
12151   DiagnoseUseOfDecl(Found, E->getExprLoc());
12152   CheckAddressOfMemberAccess(E, DAP);
12153   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12154   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12155     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12156   else
12157     SrcExpr = Fixed;
12158   return true;
12159 }
12160 
12161 /// Given an expression that refers to an overloaded function, try to
12162 /// resolve that overloaded function expression down to a single function.
12163 ///
12164 /// This routine can only resolve template-ids that refer to a single function
12165 /// template, where that template-id refers to a single template whose template
12166 /// arguments are either provided by the template-id or have defaults,
12167 /// as described in C++0x [temp.arg.explicit]p3.
12168 ///
12169 /// If no template-ids are found, no diagnostics are emitted and NULL is
12170 /// returned.
12171 FunctionDecl *
12172 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12173                                                   bool Complain,
12174                                                   DeclAccessPair *FoundResult) {
12175   // C++ [over.over]p1:
12176   //   [...] [Note: any redundant set of parentheses surrounding the
12177   //   overloaded function name is ignored (5.1). ]
12178   // C++ [over.over]p1:
12179   //   [...] The overloaded function name can be preceded by the &
12180   //   operator.
12181 
12182   // If we didn't actually find any template-ids, we're done.
12183   if (!ovl->hasExplicitTemplateArgs())
12184     return nullptr;
12185 
12186   TemplateArgumentListInfo ExplicitTemplateArgs;
12187   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12188   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12189 
12190   // Look through all of the overloaded functions, searching for one
12191   // whose type matches exactly.
12192   FunctionDecl *Matched = nullptr;
12193   for (UnresolvedSetIterator I = ovl->decls_begin(),
12194          E = ovl->decls_end(); I != E; ++I) {
12195     // C++0x [temp.arg.explicit]p3:
12196     //   [...] In contexts where deduction is done and fails, or in contexts
12197     //   where deduction is not done, if a template argument list is
12198     //   specified and it, along with any default template arguments,
12199     //   identifies a single function template specialization, then the
12200     //   template-id is an lvalue for the function template specialization.
12201     FunctionTemplateDecl *FunctionTemplate
12202       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12203 
12204     // C++ [over.over]p2:
12205     //   If the name is a function template, template argument deduction is
12206     //   done (14.8.2.2), and if the argument deduction succeeds, the
12207     //   resulting template argument list is used to generate a single
12208     //   function template specialization, which is added to the set of
12209     //   overloaded functions considered.
12210     FunctionDecl *Specialization = nullptr;
12211     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12212     if (TemplateDeductionResult Result
12213           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12214                                     Specialization, Info,
12215                                     /*IsAddressOfFunction*/true)) {
12216       // Make a note of the failed deduction for diagnostics.
12217       // TODO: Actually use the failed-deduction info?
12218       FailedCandidates.addCandidate()
12219           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12220                MakeDeductionFailureInfo(Context, Result, Info));
12221       continue;
12222     }
12223 
12224     assert(Specialization && "no specialization and no error?");
12225 
12226     // Multiple matches; we can't resolve to a single declaration.
12227     if (Matched) {
12228       if (Complain) {
12229         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12230           << ovl->getName();
12231         NoteAllOverloadCandidates(ovl);
12232       }
12233       return nullptr;
12234     }
12235 
12236     Matched = Specialization;
12237     if (FoundResult) *FoundResult = I.getPair();
12238   }
12239 
12240   if (Matched &&
12241       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12242     return nullptr;
12243 
12244   return Matched;
12245 }
12246 
12247 // Resolve and fix an overloaded expression that can be resolved
12248 // because it identifies a single function template specialization.
12249 //
12250 // Last three arguments should only be supplied if Complain = true
12251 //
12252 // Return true if it was logically possible to so resolve the
12253 // expression, regardless of whether or not it succeeded.  Always
12254 // returns true if 'complain' is set.
12255 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12256                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12257                       bool complain, SourceRange OpRangeForComplaining,
12258                                            QualType DestTypeForComplaining,
12259                                             unsigned DiagIDForComplaining) {
12260   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12261 
12262   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12263 
12264   DeclAccessPair found;
12265   ExprResult SingleFunctionExpression;
12266   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12267                            ovl.Expression, /*complain*/ false, &found)) {
12268     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12269       SrcExpr = ExprError();
12270       return true;
12271     }
12272 
12273     // It is only correct to resolve to an instance method if we're
12274     // resolving a form that's permitted to be a pointer to member.
12275     // Otherwise we'll end up making a bound member expression, which
12276     // is illegal in all the contexts we resolve like this.
12277     if (!ovl.HasFormOfMemberPointer &&
12278         isa<CXXMethodDecl>(fn) &&
12279         cast<CXXMethodDecl>(fn)->isInstance()) {
12280       if (!complain) return false;
12281 
12282       Diag(ovl.Expression->getExprLoc(),
12283            diag::err_bound_member_function)
12284         << 0 << ovl.Expression->getSourceRange();
12285 
12286       // TODO: I believe we only end up here if there's a mix of
12287       // static and non-static candidates (otherwise the expression
12288       // would have 'bound member' type, not 'overload' type).
12289       // Ideally we would note which candidate was chosen and why
12290       // the static candidates were rejected.
12291       SrcExpr = ExprError();
12292       return true;
12293     }
12294 
12295     // Fix the expression to refer to 'fn'.
12296     SingleFunctionExpression =
12297         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12298 
12299     // If desired, do function-to-pointer decay.
12300     if (doFunctionPointerConverion) {
12301       SingleFunctionExpression =
12302         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12303       if (SingleFunctionExpression.isInvalid()) {
12304         SrcExpr = ExprError();
12305         return true;
12306       }
12307     }
12308   }
12309 
12310   if (!SingleFunctionExpression.isUsable()) {
12311     if (complain) {
12312       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12313         << ovl.Expression->getName()
12314         << DestTypeForComplaining
12315         << OpRangeForComplaining
12316         << ovl.Expression->getQualifierLoc().getSourceRange();
12317       NoteAllOverloadCandidates(SrcExpr.get());
12318 
12319       SrcExpr = ExprError();
12320       return true;
12321     }
12322 
12323     return false;
12324   }
12325 
12326   SrcExpr = SingleFunctionExpression;
12327   return true;
12328 }
12329 
12330 /// Add a single candidate to the overload set.
12331 static void AddOverloadedCallCandidate(Sema &S,
12332                                        DeclAccessPair FoundDecl,
12333                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12334                                        ArrayRef<Expr *> Args,
12335                                        OverloadCandidateSet &CandidateSet,
12336                                        bool PartialOverloading,
12337                                        bool KnownValid) {
12338   NamedDecl *Callee = FoundDecl.getDecl();
12339   if (isa<UsingShadowDecl>(Callee))
12340     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12341 
12342   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12343     if (ExplicitTemplateArgs) {
12344       assert(!KnownValid && "Explicit template arguments?");
12345       return;
12346     }
12347     // Prevent ill-formed function decls to be added as overload candidates.
12348     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12349       return;
12350 
12351     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12352                            /*SuppressUserConversions=*/false,
12353                            PartialOverloading);
12354     return;
12355   }
12356 
12357   if (FunctionTemplateDecl *FuncTemplate
12358       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12359     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12360                                    ExplicitTemplateArgs, Args, CandidateSet,
12361                                    /*SuppressUserConversions=*/false,
12362                                    PartialOverloading);
12363     return;
12364   }
12365 
12366   assert(!KnownValid && "unhandled case in overloaded call candidate");
12367 }
12368 
12369 /// Add the overload candidates named by callee and/or found by argument
12370 /// dependent lookup to the given overload set.
12371 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12372                                        ArrayRef<Expr *> Args,
12373                                        OverloadCandidateSet &CandidateSet,
12374                                        bool PartialOverloading) {
12375 
12376 #ifndef NDEBUG
12377   // Verify that ArgumentDependentLookup is consistent with the rules
12378   // in C++0x [basic.lookup.argdep]p3:
12379   //
12380   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12381   //   and let Y be the lookup set produced by argument dependent
12382   //   lookup (defined as follows). If X contains
12383   //
12384   //     -- a declaration of a class member, or
12385   //
12386   //     -- a block-scope function declaration that is not a
12387   //        using-declaration, or
12388   //
12389   //     -- a declaration that is neither a function or a function
12390   //        template
12391   //
12392   //   then Y is empty.
12393 
12394   if (ULE->requiresADL()) {
12395     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12396            E = ULE->decls_end(); I != E; ++I) {
12397       assert(!(*I)->getDeclContext()->isRecord());
12398       assert(isa<UsingShadowDecl>(*I) ||
12399              !(*I)->getDeclContext()->isFunctionOrMethod());
12400       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12401     }
12402   }
12403 #endif
12404 
12405   // It would be nice to avoid this copy.
12406   TemplateArgumentListInfo TABuffer;
12407   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12408   if (ULE->hasExplicitTemplateArgs()) {
12409     ULE->copyTemplateArgumentsInto(TABuffer);
12410     ExplicitTemplateArgs = &TABuffer;
12411   }
12412 
12413   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12414          E = ULE->decls_end(); I != E; ++I)
12415     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12416                                CandidateSet, PartialOverloading,
12417                                /*KnownValid*/ true);
12418 
12419   if (ULE->requiresADL())
12420     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12421                                          Args, ExplicitTemplateArgs,
12422                                          CandidateSet, PartialOverloading);
12423 }
12424 
12425 /// Determine whether a declaration with the specified name could be moved into
12426 /// a different namespace.
12427 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12428   switch (Name.getCXXOverloadedOperator()) {
12429   case OO_New: case OO_Array_New:
12430   case OO_Delete: case OO_Array_Delete:
12431     return false;
12432 
12433   default:
12434     return true;
12435   }
12436 }
12437 
12438 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12439 /// template, where the non-dependent name was declared after the template
12440 /// was defined. This is common in code written for a compilers which do not
12441 /// correctly implement two-stage name lookup.
12442 ///
12443 /// Returns true if a viable candidate was found and a diagnostic was issued.
12444 static bool
12445 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12446                        const CXXScopeSpec &SS, LookupResult &R,
12447                        OverloadCandidateSet::CandidateSetKind CSK,
12448                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12449                        ArrayRef<Expr *> Args,
12450                        bool *DoDiagnoseEmptyLookup = nullptr) {
12451   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12452     return false;
12453 
12454   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12455     if (DC->isTransparentContext())
12456       continue;
12457 
12458     SemaRef.LookupQualifiedName(R, DC);
12459 
12460     if (!R.empty()) {
12461       R.suppressDiagnostics();
12462 
12463       if (isa<CXXRecordDecl>(DC)) {
12464         // Don't diagnose names we find in classes; we get much better
12465         // diagnostics for these from DiagnoseEmptyLookup.
12466         R.clear();
12467         if (DoDiagnoseEmptyLookup)
12468           *DoDiagnoseEmptyLookup = true;
12469         return false;
12470       }
12471 
12472       OverloadCandidateSet Candidates(FnLoc, CSK);
12473       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12474         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12475                                    ExplicitTemplateArgs, Args,
12476                                    Candidates, false, /*KnownValid*/ false);
12477 
12478       OverloadCandidateSet::iterator Best;
12479       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12480         // No viable functions. Don't bother the user with notes for functions
12481         // which don't work and shouldn't be found anyway.
12482         R.clear();
12483         return false;
12484       }
12485 
12486       // Find the namespaces where ADL would have looked, and suggest
12487       // declaring the function there instead.
12488       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12489       Sema::AssociatedClassSet AssociatedClasses;
12490       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12491                                                  AssociatedNamespaces,
12492                                                  AssociatedClasses);
12493       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12494       if (canBeDeclaredInNamespace(R.getLookupName())) {
12495         DeclContext *Std = SemaRef.getStdNamespace();
12496         for (Sema::AssociatedNamespaceSet::iterator
12497                it = AssociatedNamespaces.begin(),
12498                end = AssociatedNamespaces.end(); it != end; ++it) {
12499           // Never suggest declaring a function within namespace 'std'.
12500           if (Std && Std->Encloses(*it))
12501             continue;
12502 
12503           // Never suggest declaring a function within a namespace with a
12504           // reserved name, like __gnu_cxx.
12505           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12506           if (NS &&
12507               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12508             continue;
12509 
12510           SuggestedNamespaces.insert(*it);
12511         }
12512       }
12513 
12514       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12515         << R.getLookupName();
12516       if (SuggestedNamespaces.empty()) {
12517         SemaRef.Diag(Best->Function->getLocation(),
12518                      diag::note_not_found_by_two_phase_lookup)
12519           << R.getLookupName() << 0;
12520       } else if (SuggestedNamespaces.size() == 1) {
12521         SemaRef.Diag(Best->Function->getLocation(),
12522                      diag::note_not_found_by_two_phase_lookup)
12523           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12524       } else {
12525         // FIXME: It would be useful to list the associated namespaces here,
12526         // but the diagnostics infrastructure doesn't provide a way to produce
12527         // a localized representation of a list of items.
12528         SemaRef.Diag(Best->Function->getLocation(),
12529                      diag::note_not_found_by_two_phase_lookup)
12530           << R.getLookupName() << 2;
12531       }
12532 
12533       // Try to recover by calling this function.
12534       return true;
12535     }
12536 
12537     R.clear();
12538   }
12539 
12540   return false;
12541 }
12542 
12543 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12544 /// template, where the non-dependent operator was declared after the template
12545 /// was defined.
12546 ///
12547 /// Returns true if a viable candidate was found and a diagnostic was issued.
12548 static bool
12549 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12550                                SourceLocation OpLoc,
12551                                ArrayRef<Expr *> Args) {
12552   DeclarationName OpName =
12553     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12554   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12555   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12556                                 OverloadCandidateSet::CSK_Operator,
12557                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12558 }
12559 
12560 namespace {
12561 class BuildRecoveryCallExprRAII {
12562   Sema &SemaRef;
12563 public:
12564   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12565     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12566     SemaRef.IsBuildingRecoveryCallExpr = true;
12567   }
12568 
12569   ~BuildRecoveryCallExprRAII() {
12570     SemaRef.IsBuildingRecoveryCallExpr = false;
12571   }
12572 };
12573 
12574 }
12575 
12576 /// Attempts to recover from a call where no functions were found.
12577 ///
12578 /// Returns true if new candidates were found.
12579 static ExprResult
12580 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12581                       UnresolvedLookupExpr *ULE,
12582                       SourceLocation LParenLoc,
12583                       MutableArrayRef<Expr *> Args,
12584                       SourceLocation RParenLoc,
12585                       bool EmptyLookup, bool AllowTypoCorrection) {
12586   // Do not try to recover if it is already building a recovery call.
12587   // This stops infinite loops for template instantiations like
12588   //
12589   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12590   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12591   //
12592   if (SemaRef.IsBuildingRecoveryCallExpr)
12593     return ExprError();
12594   BuildRecoveryCallExprRAII RCE(SemaRef);
12595 
12596   CXXScopeSpec SS;
12597   SS.Adopt(ULE->getQualifierLoc());
12598   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12599 
12600   TemplateArgumentListInfo TABuffer;
12601   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12602   if (ULE->hasExplicitTemplateArgs()) {
12603     ULE->copyTemplateArgumentsInto(TABuffer);
12604     ExplicitTemplateArgs = &TABuffer;
12605   }
12606 
12607   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12608                  Sema::LookupOrdinaryName);
12609   bool DoDiagnoseEmptyLookup = EmptyLookup;
12610   if (!DiagnoseTwoPhaseLookup(
12611           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12612           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12613     NoTypoCorrectionCCC NoTypoValidator{};
12614     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12615                                                 ExplicitTemplateArgs != nullptr,
12616                                                 dyn_cast<MemberExpr>(Fn));
12617     CorrectionCandidateCallback &Validator =
12618         AllowTypoCorrection
12619             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12620             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12621     if (!DoDiagnoseEmptyLookup ||
12622         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12623                                     Args))
12624       return ExprError();
12625   }
12626 
12627   assert(!R.empty() && "lookup results empty despite recovery");
12628 
12629   // If recovery created an ambiguity, just bail out.
12630   if (R.isAmbiguous()) {
12631     R.suppressDiagnostics();
12632     return ExprError();
12633   }
12634 
12635   // Build an implicit member call if appropriate.  Just drop the
12636   // casts and such from the call, we don't really care.
12637   ExprResult NewFn = ExprError();
12638   if ((*R.begin())->isCXXClassMember())
12639     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12640                                                     ExplicitTemplateArgs, S);
12641   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12642     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12643                                         ExplicitTemplateArgs);
12644   else
12645     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12646 
12647   if (NewFn.isInvalid())
12648     return ExprError();
12649 
12650   // This shouldn't cause an infinite loop because we're giving it
12651   // an expression with viable lookup results, which should never
12652   // end up here.
12653   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12654                                MultiExprArg(Args.data(), Args.size()),
12655                                RParenLoc);
12656 }
12657 
12658 /// Constructs and populates an OverloadedCandidateSet from
12659 /// the given function.
12660 /// \returns true when an the ExprResult output parameter has been set.
12661 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12662                                   UnresolvedLookupExpr *ULE,
12663                                   MultiExprArg Args,
12664                                   SourceLocation RParenLoc,
12665                                   OverloadCandidateSet *CandidateSet,
12666                                   ExprResult *Result) {
12667 #ifndef NDEBUG
12668   if (ULE->requiresADL()) {
12669     // To do ADL, we must have found an unqualified name.
12670     assert(!ULE->getQualifier() && "qualified name with ADL");
12671 
12672     // We don't perform ADL for implicit declarations of builtins.
12673     // Verify that this was correctly set up.
12674     FunctionDecl *F;
12675     if (ULE->decls_begin() != ULE->decls_end() &&
12676         ULE->decls_begin() + 1 == ULE->decls_end() &&
12677         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12678         F->getBuiltinID() && F->isImplicit())
12679       llvm_unreachable("performing ADL for builtin");
12680 
12681     // We don't perform ADL in C.
12682     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12683   }
12684 #endif
12685 
12686   UnbridgedCastsSet UnbridgedCasts;
12687   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12688     *Result = ExprError();
12689     return true;
12690   }
12691 
12692   // Add the functions denoted by the callee to the set of candidate
12693   // functions, including those from argument-dependent lookup.
12694   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12695 
12696   if (getLangOpts().MSVCCompat &&
12697       CurContext->isDependentContext() && !isSFINAEContext() &&
12698       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12699 
12700     OverloadCandidateSet::iterator Best;
12701     if (CandidateSet->empty() ||
12702         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12703             OR_No_Viable_Function) {
12704       // In Microsoft mode, if we are inside a template class member function
12705       // then create a type dependent CallExpr. The goal is to postpone name
12706       // lookup to instantiation time to be able to search into type dependent
12707       // base classes.
12708       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12709                                       VK_RValue, RParenLoc);
12710       CE->setTypeDependent(true);
12711       CE->setValueDependent(true);
12712       CE->setInstantiationDependent(true);
12713       *Result = CE;
12714       return true;
12715     }
12716   }
12717 
12718   if (CandidateSet->empty())
12719     return false;
12720 
12721   UnbridgedCasts.restore();
12722   return false;
12723 }
12724 
12725 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12726 /// the completed call expression. If overload resolution fails, emits
12727 /// diagnostics and returns ExprError()
12728 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12729                                            UnresolvedLookupExpr *ULE,
12730                                            SourceLocation LParenLoc,
12731                                            MultiExprArg Args,
12732                                            SourceLocation RParenLoc,
12733                                            Expr *ExecConfig,
12734                                            OverloadCandidateSet *CandidateSet,
12735                                            OverloadCandidateSet::iterator *Best,
12736                                            OverloadingResult OverloadResult,
12737                                            bool AllowTypoCorrection) {
12738   if (CandidateSet->empty())
12739     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12740                                  RParenLoc, /*EmptyLookup=*/true,
12741                                  AllowTypoCorrection);
12742 
12743   switch (OverloadResult) {
12744   case OR_Success: {
12745     FunctionDecl *FDecl = (*Best)->Function;
12746     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12747     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12748       return ExprError();
12749     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12750     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12751                                          ExecConfig, /*IsExecConfig=*/false,
12752                                          (*Best)->IsADLCandidate);
12753   }
12754 
12755   case OR_No_Viable_Function: {
12756     // Try to recover by looking for viable functions which the user might
12757     // have meant to call.
12758     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12759                                                 Args, RParenLoc,
12760                                                 /*EmptyLookup=*/false,
12761                                                 AllowTypoCorrection);
12762     if (!Recovery.isInvalid())
12763       return Recovery;
12764 
12765     // If the user passes in a function that we can't take the address of, we
12766     // generally end up emitting really bad error messages. Here, we attempt to
12767     // emit better ones.
12768     for (const Expr *Arg : Args) {
12769       if (!Arg->getType()->isFunctionType())
12770         continue;
12771       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12772         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12773         if (FD &&
12774             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12775                                                        Arg->getExprLoc()))
12776           return ExprError();
12777       }
12778     }
12779 
12780     CandidateSet->NoteCandidates(
12781         PartialDiagnosticAt(
12782             Fn->getBeginLoc(),
12783             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12784                 << ULE->getName() << Fn->getSourceRange()),
12785         SemaRef, OCD_AllCandidates, Args);
12786     break;
12787   }
12788 
12789   case OR_Ambiguous:
12790     CandidateSet->NoteCandidates(
12791         PartialDiagnosticAt(Fn->getBeginLoc(),
12792                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12793                                 << ULE->getName() << Fn->getSourceRange()),
12794         SemaRef, OCD_AmbiguousCandidates, Args);
12795     break;
12796 
12797   case OR_Deleted: {
12798     CandidateSet->NoteCandidates(
12799         PartialDiagnosticAt(Fn->getBeginLoc(),
12800                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12801                                 << ULE->getName() << Fn->getSourceRange()),
12802         SemaRef, OCD_AllCandidates, Args);
12803 
12804     // We emitted an error for the unavailable/deleted function call but keep
12805     // the call in the AST.
12806     FunctionDecl *FDecl = (*Best)->Function;
12807     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12808     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12809                                          ExecConfig, /*IsExecConfig=*/false,
12810                                          (*Best)->IsADLCandidate);
12811   }
12812   }
12813 
12814   // Overload resolution failed.
12815   return ExprError();
12816 }
12817 
12818 static void markUnaddressableCandidatesUnviable(Sema &S,
12819                                                 OverloadCandidateSet &CS) {
12820   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12821     if (I->Viable &&
12822         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12823       I->Viable = false;
12824       I->FailureKind = ovl_fail_addr_not_available;
12825     }
12826   }
12827 }
12828 
12829 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12830 /// (which eventually refers to the declaration Func) and the call
12831 /// arguments Args/NumArgs, attempt to resolve the function call down
12832 /// to a specific function. If overload resolution succeeds, returns
12833 /// the call expression produced by overload resolution.
12834 /// Otherwise, emits diagnostics and returns ExprError.
12835 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12836                                          UnresolvedLookupExpr *ULE,
12837                                          SourceLocation LParenLoc,
12838                                          MultiExprArg Args,
12839                                          SourceLocation RParenLoc,
12840                                          Expr *ExecConfig,
12841                                          bool AllowTypoCorrection,
12842                                          bool CalleesAddressIsTaken) {
12843   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12844                                     OverloadCandidateSet::CSK_Normal);
12845   ExprResult result;
12846 
12847   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12848                              &result))
12849     return result;
12850 
12851   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12852   // functions that aren't addressible are considered unviable.
12853   if (CalleesAddressIsTaken)
12854     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12855 
12856   OverloadCandidateSet::iterator Best;
12857   OverloadingResult OverloadResult =
12858       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12859 
12860   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12861                                   ExecConfig, &CandidateSet, &Best,
12862                                   OverloadResult, AllowTypoCorrection);
12863 }
12864 
12865 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12866   return Functions.size() > 1 ||
12867     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12868 }
12869 
12870 /// Create a unary operation that may resolve to an overloaded
12871 /// operator.
12872 ///
12873 /// \param OpLoc The location of the operator itself (e.g., '*').
12874 ///
12875 /// \param Opc The UnaryOperatorKind that describes this operator.
12876 ///
12877 /// \param Fns The set of non-member functions that will be
12878 /// considered by overload resolution. The caller needs to build this
12879 /// set based on the context using, e.g.,
12880 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12881 /// set should not contain any member functions; those will be added
12882 /// by CreateOverloadedUnaryOp().
12883 ///
12884 /// \param Input The input argument.
12885 ExprResult
12886 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12887                               const UnresolvedSetImpl &Fns,
12888                               Expr *Input, bool PerformADL) {
12889   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12890   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12891   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12892   // TODO: provide better source location info.
12893   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12894 
12895   if (checkPlaceholderForOverload(*this, Input))
12896     return ExprError();
12897 
12898   Expr *Args[2] = { Input, nullptr };
12899   unsigned NumArgs = 1;
12900 
12901   // For post-increment and post-decrement, add the implicit '0' as
12902   // the second argument, so that we know this is a post-increment or
12903   // post-decrement.
12904   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12905     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12906     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12907                                      SourceLocation());
12908     NumArgs = 2;
12909   }
12910 
12911   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12912 
12913   if (Input->isTypeDependent()) {
12914     if (Fns.empty())
12915       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12916                                          VK_RValue, OK_Ordinary, OpLoc, false);
12917 
12918     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12919     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12920         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12921         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12922     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12923                                        Context.DependentTy, VK_RValue, OpLoc,
12924                                        FPOptions());
12925   }
12926 
12927   // Build an empty overload set.
12928   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12929 
12930   // Add the candidates from the given function set.
12931   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12932 
12933   // Add operator candidates that are member functions.
12934   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12935 
12936   // Add candidates from ADL.
12937   if (PerformADL) {
12938     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12939                                          /*ExplicitTemplateArgs*/nullptr,
12940                                          CandidateSet);
12941   }
12942 
12943   // Add builtin operator candidates.
12944   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12945 
12946   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12947 
12948   // Perform overload resolution.
12949   OverloadCandidateSet::iterator Best;
12950   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12951   case OR_Success: {
12952     // We found a built-in operator or an overloaded operator.
12953     FunctionDecl *FnDecl = Best->Function;
12954 
12955     if (FnDecl) {
12956       Expr *Base = nullptr;
12957       // We matched an overloaded operator. Build a call to that
12958       // operator.
12959 
12960       // Convert the arguments.
12961       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12962         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12963 
12964         ExprResult InputRes =
12965           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12966                                               Best->FoundDecl, Method);
12967         if (InputRes.isInvalid())
12968           return ExprError();
12969         Base = Input = InputRes.get();
12970       } else {
12971         // Convert the arguments.
12972         ExprResult InputInit
12973           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12974                                                       Context,
12975                                                       FnDecl->getParamDecl(0)),
12976                                       SourceLocation(),
12977                                       Input);
12978         if (InputInit.isInvalid())
12979           return ExprError();
12980         Input = InputInit.get();
12981       }
12982 
12983       // Build the actual expression node.
12984       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12985                                                 Base, HadMultipleCandidates,
12986                                                 OpLoc);
12987       if (FnExpr.isInvalid())
12988         return ExprError();
12989 
12990       // Determine the result type.
12991       QualType ResultTy = FnDecl->getReturnType();
12992       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12993       ResultTy = ResultTy.getNonLValueExprType(Context);
12994 
12995       Args[0] = Input;
12996       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12997           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12998           FPOptions(), Best->IsADLCandidate);
12999 
13000       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13001         return ExprError();
13002 
13003       if (CheckFunctionCall(FnDecl, TheCall,
13004                             FnDecl->getType()->castAs<FunctionProtoType>()))
13005         return ExprError();
13006       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13007     } else {
13008       // We matched a built-in operator. Convert the arguments, then
13009       // break out so that we will build the appropriate built-in
13010       // operator node.
13011       ExprResult InputRes = PerformImplicitConversion(
13012           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13013           CCK_ForBuiltinOverloadedOp);
13014       if (InputRes.isInvalid())
13015         return ExprError();
13016       Input = InputRes.get();
13017       break;
13018     }
13019   }
13020 
13021   case OR_No_Viable_Function:
13022     // This is an erroneous use of an operator which can be overloaded by
13023     // a non-member function. Check for non-member operators which were
13024     // defined too late to be candidates.
13025     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13026       // FIXME: Recover by calling the found function.
13027       return ExprError();
13028 
13029     // No viable function; fall through to handling this as a
13030     // built-in operator, which will produce an error message for us.
13031     break;
13032 
13033   case OR_Ambiguous:
13034     CandidateSet.NoteCandidates(
13035         PartialDiagnosticAt(OpLoc,
13036                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13037                                 << UnaryOperator::getOpcodeStr(Opc)
13038                                 << Input->getType() << Input->getSourceRange()),
13039         *this, OCD_AmbiguousCandidates, ArgsArray,
13040         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13041     return ExprError();
13042 
13043   case OR_Deleted:
13044     CandidateSet.NoteCandidates(
13045         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13046                                        << UnaryOperator::getOpcodeStr(Opc)
13047                                        << Input->getSourceRange()),
13048         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13049         OpLoc);
13050     return ExprError();
13051   }
13052 
13053   // Either we found no viable overloaded operator or we matched a
13054   // built-in operator. In either case, fall through to trying to
13055   // build a built-in operation.
13056   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13057 }
13058 
13059 /// Perform lookup for an overloaded binary operator.
13060 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13061                                  OverloadedOperatorKind Op,
13062                                  const UnresolvedSetImpl &Fns,
13063                                  ArrayRef<Expr *> Args, bool PerformADL) {
13064   SourceLocation OpLoc = CandidateSet.getLocation();
13065 
13066   OverloadedOperatorKind ExtraOp =
13067       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13068           ? getRewrittenOverloadedOperator(Op)
13069           : OO_None;
13070 
13071   // Add the candidates from the given function set. This also adds the
13072   // rewritten candidates using these functions if necessary.
13073   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13074 
13075   // Add operator candidates that are member functions.
13076   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13077   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13078     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13079                                 OverloadCandidateParamOrder::Reversed);
13080 
13081   // In C++20, also add any rewritten member candidates.
13082   if (ExtraOp) {
13083     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13084     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13085       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13086                                   CandidateSet,
13087                                   OverloadCandidateParamOrder::Reversed);
13088   }
13089 
13090   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13091   // performed for an assignment operator (nor for operator[] nor operator->,
13092   // which don't get here).
13093   if (Op != OO_Equal && PerformADL) {
13094     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13095     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13096                                          /*ExplicitTemplateArgs*/ nullptr,
13097                                          CandidateSet);
13098     if (ExtraOp) {
13099       DeclarationName ExtraOpName =
13100           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13101       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13102                                            /*ExplicitTemplateArgs*/ nullptr,
13103                                            CandidateSet);
13104     }
13105   }
13106 
13107   // Add builtin operator candidates.
13108   //
13109   // FIXME: We don't add any rewritten candidates here. This is strictly
13110   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13111   // resulting in our selecting a rewritten builtin candidate. For example:
13112   //
13113   //   enum class E { e };
13114   //   bool operator!=(E, E) requires false;
13115   //   bool k = E::e != E::e;
13116   //
13117   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13118   // it seems unreasonable to consider rewritten builtin candidates. A core
13119   // issue has been filed proposing to removed this requirement.
13120   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13121 }
13122 
13123 /// Create a binary operation that may resolve to an overloaded
13124 /// operator.
13125 ///
13126 /// \param OpLoc The location of the operator itself (e.g., '+').
13127 ///
13128 /// \param Opc The BinaryOperatorKind that describes this operator.
13129 ///
13130 /// \param Fns The set of non-member functions that will be
13131 /// considered by overload resolution. The caller needs to build this
13132 /// set based on the context using, e.g.,
13133 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13134 /// set should not contain any member functions; those will be added
13135 /// by CreateOverloadedBinOp().
13136 ///
13137 /// \param LHS Left-hand argument.
13138 /// \param RHS Right-hand argument.
13139 /// \param PerformADL Whether to consider operator candidates found by ADL.
13140 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13141 ///        C++20 operator rewrites.
13142 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13143 ///        the function in question. Such a function is never a candidate in
13144 ///        our overload resolution. This also enables synthesizing a three-way
13145 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13146 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13147                                        BinaryOperatorKind Opc,
13148                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13149                                        Expr *RHS, bool PerformADL,
13150                                        bool AllowRewrittenCandidates,
13151                                        FunctionDecl *DefaultedFn) {
13152   Expr *Args[2] = { LHS, RHS };
13153   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13154 
13155   if (!getLangOpts().CPlusPlus2a)
13156     AllowRewrittenCandidates = false;
13157 
13158   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13159 
13160   // If either side is type-dependent, create an appropriate dependent
13161   // expression.
13162   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13163     if (Fns.empty()) {
13164       // If there are no functions to store, just build a dependent
13165       // BinaryOperator or CompoundAssignment.
13166       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13167         return new (Context) BinaryOperator(
13168             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13169             OpLoc, FPFeatures);
13170 
13171       return new (Context) CompoundAssignOperator(
13172           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13173           Context.DependentTy, Context.DependentTy, OpLoc,
13174           FPFeatures);
13175     }
13176 
13177     // FIXME: save results of ADL from here?
13178     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13179     // TODO: provide better source location info in DNLoc component.
13180     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13181     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13182     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13183         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13184         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13185     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13186                                        Context.DependentTy, VK_RValue, OpLoc,
13187                                        FPFeatures);
13188   }
13189 
13190   // Always do placeholder-like conversions on the RHS.
13191   if (checkPlaceholderForOverload(*this, Args[1]))
13192     return ExprError();
13193 
13194   // Do placeholder-like conversion on the LHS; note that we should
13195   // not get here with a PseudoObject LHS.
13196   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13197   if (checkPlaceholderForOverload(*this, Args[0]))
13198     return ExprError();
13199 
13200   // If this is the assignment operator, we only perform overload resolution
13201   // if the left-hand side is a class or enumeration type. This is actually
13202   // a hack. The standard requires that we do overload resolution between the
13203   // various built-in candidates, but as DR507 points out, this can lead to
13204   // problems. So we do it this way, which pretty much follows what GCC does.
13205   // Note that we go the traditional code path for compound assignment forms.
13206   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13207     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13208 
13209   // If this is the .* operator, which is not overloadable, just
13210   // create a built-in binary operator.
13211   if (Opc == BO_PtrMemD)
13212     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13213 
13214   // Build the overload set.
13215   OverloadCandidateSet CandidateSet(
13216       OpLoc, OverloadCandidateSet::CSK_Operator,
13217       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13218   if (DefaultedFn)
13219     CandidateSet.exclude(DefaultedFn);
13220   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13221 
13222   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13223 
13224   // Perform overload resolution.
13225   OverloadCandidateSet::iterator Best;
13226   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13227     case OR_Success: {
13228       // We found a built-in operator or an overloaded operator.
13229       FunctionDecl *FnDecl = Best->Function;
13230 
13231       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13232       if (IsReversed)
13233         std::swap(Args[0], Args[1]);
13234 
13235       if (FnDecl) {
13236         Expr *Base = nullptr;
13237         // We matched an overloaded operator. Build a call to that
13238         // operator.
13239 
13240         OverloadedOperatorKind ChosenOp =
13241             FnDecl->getDeclName().getCXXOverloadedOperator();
13242 
13243         // C++2a [over.match.oper]p9:
13244         //   If a rewritten operator== candidate is selected by overload
13245         //   resolution for an operator@, its return type shall be cv bool
13246         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13247             !FnDecl->getReturnType()->isBooleanType()) {
13248           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13249               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13250               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13251           Diag(FnDecl->getLocation(), diag::note_declared_at);
13252           return ExprError();
13253         }
13254 
13255         if (AllowRewrittenCandidates && !IsReversed &&
13256             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13257           // We could have reversed this operator, but didn't. Check if the
13258           // reversed form was a viable candidate, and if so, if it had a
13259           // better conversion for either parameter. If so, this call is
13260           // formally ambiguous, and allowing it is an extension.
13261           for (OverloadCandidate &Cand : CandidateSet) {
13262             if (Cand.Viable && Cand.Function == FnDecl &&
13263                 Cand.RewriteKind & CRK_Reversed) {
13264               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13265                 if (CompareImplicitConversionSequences(
13266                         *this, OpLoc, Cand.Conversions[ArgIdx],
13267                         Best->Conversions[ArgIdx]) ==
13268                     ImplicitConversionSequence::Better) {
13269                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13270                       << BinaryOperator::getOpcodeStr(Opc)
13271                       << Args[0]->getType() << Args[1]->getType()
13272                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13273                   Diag(FnDecl->getLocation(),
13274                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13275                 }
13276               }
13277               break;
13278             }
13279           }
13280         }
13281 
13282         // Convert the arguments.
13283         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13284           // Best->Access is only meaningful for class members.
13285           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13286 
13287           ExprResult Arg1 =
13288             PerformCopyInitialization(
13289               InitializedEntity::InitializeParameter(Context,
13290                                                      FnDecl->getParamDecl(0)),
13291               SourceLocation(), Args[1]);
13292           if (Arg1.isInvalid())
13293             return ExprError();
13294 
13295           ExprResult Arg0 =
13296             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13297                                                 Best->FoundDecl, Method);
13298           if (Arg0.isInvalid())
13299             return ExprError();
13300           Base = Args[0] = Arg0.getAs<Expr>();
13301           Args[1] = RHS = Arg1.getAs<Expr>();
13302         } else {
13303           // Convert the arguments.
13304           ExprResult Arg0 = PerformCopyInitialization(
13305             InitializedEntity::InitializeParameter(Context,
13306                                                    FnDecl->getParamDecl(0)),
13307             SourceLocation(), Args[0]);
13308           if (Arg0.isInvalid())
13309             return ExprError();
13310 
13311           ExprResult Arg1 =
13312             PerformCopyInitialization(
13313               InitializedEntity::InitializeParameter(Context,
13314                                                      FnDecl->getParamDecl(1)),
13315               SourceLocation(), Args[1]);
13316           if (Arg1.isInvalid())
13317             return ExprError();
13318           Args[0] = LHS = Arg0.getAs<Expr>();
13319           Args[1] = RHS = Arg1.getAs<Expr>();
13320         }
13321 
13322         // Build the actual expression node.
13323         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13324                                                   Best->FoundDecl, Base,
13325                                                   HadMultipleCandidates, OpLoc);
13326         if (FnExpr.isInvalid())
13327           return ExprError();
13328 
13329         // Determine the result type.
13330         QualType ResultTy = FnDecl->getReturnType();
13331         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13332         ResultTy = ResultTy.getNonLValueExprType(Context);
13333 
13334         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13335             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13336             FPFeatures, Best->IsADLCandidate);
13337 
13338         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13339                                 FnDecl))
13340           return ExprError();
13341 
13342         ArrayRef<const Expr *> ArgsArray(Args, 2);
13343         const Expr *ImplicitThis = nullptr;
13344         // Cut off the implicit 'this'.
13345         if (isa<CXXMethodDecl>(FnDecl)) {
13346           ImplicitThis = ArgsArray[0];
13347           ArgsArray = ArgsArray.slice(1);
13348         }
13349 
13350         // Check for a self move.
13351         if (Op == OO_Equal)
13352           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13353 
13354         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13355                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13356                   VariadicDoesNotApply);
13357 
13358         ExprResult R = MaybeBindToTemporary(TheCall);
13359         if (R.isInvalid())
13360           return ExprError();
13361 
13362         // For a rewritten candidate, we've already reversed the arguments
13363         // if needed. Perform the rest of the rewrite now.
13364         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13365             (Op == OO_Spaceship && IsReversed)) {
13366           if (Op == OO_ExclaimEqual) {
13367             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13368             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13369           } else {
13370             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13371             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13372             Expr *ZeroLiteral =
13373                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13374 
13375             Sema::CodeSynthesisContext Ctx;
13376             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13377             Ctx.Entity = FnDecl;
13378             pushCodeSynthesisContext(Ctx);
13379 
13380             R = CreateOverloadedBinOp(
13381                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13382                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13383                 /*AllowRewrittenCandidates=*/false);
13384 
13385             popCodeSynthesisContext();
13386           }
13387           if (R.isInvalid())
13388             return ExprError();
13389         } else {
13390           assert(ChosenOp == Op && "unexpected operator name");
13391         }
13392 
13393         // Make a note in the AST if we did any rewriting.
13394         if (Best->RewriteKind != CRK_None)
13395           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13396 
13397         return CheckForImmediateInvocation(R, FnDecl);
13398       } else {
13399         // We matched a built-in operator. Convert the arguments, then
13400         // break out so that we will build the appropriate built-in
13401         // operator node.
13402         ExprResult ArgsRes0 = PerformImplicitConversion(
13403             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13404             AA_Passing, CCK_ForBuiltinOverloadedOp);
13405         if (ArgsRes0.isInvalid())
13406           return ExprError();
13407         Args[0] = ArgsRes0.get();
13408 
13409         ExprResult ArgsRes1 = PerformImplicitConversion(
13410             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13411             AA_Passing, CCK_ForBuiltinOverloadedOp);
13412         if (ArgsRes1.isInvalid())
13413           return ExprError();
13414         Args[1] = ArgsRes1.get();
13415         break;
13416       }
13417     }
13418 
13419     case OR_No_Viable_Function: {
13420       // C++ [over.match.oper]p9:
13421       //   If the operator is the operator , [...] and there are no
13422       //   viable functions, then the operator is assumed to be the
13423       //   built-in operator and interpreted according to clause 5.
13424       if (Opc == BO_Comma)
13425         break;
13426 
13427       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13428       // compare result using '==' and '<'.
13429       if (DefaultedFn && Opc == BO_Cmp) {
13430         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13431                                                           Args[1], DefaultedFn);
13432         if (E.isInvalid() || E.isUsable())
13433           return E;
13434       }
13435 
13436       // For class as left operand for assignment or compound assignment
13437       // operator do not fall through to handling in built-in, but report that
13438       // no overloaded assignment operator found
13439       ExprResult Result = ExprError();
13440       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13441       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13442                                                    Args, OpLoc);
13443       if (Args[0]->getType()->isRecordType() &&
13444           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13445         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13446              << BinaryOperator::getOpcodeStr(Opc)
13447              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13448         if (Args[0]->getType()->isIncompleteType()) {
13449           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13450             << Args[0]->getType()
13451             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13452         }
13453       } else {
13454         // This is an erroneous use of an operator which can be overloaded by
13455         // a non-member function. Check for non-member operators which were
13456         // defined too late to be candidates.
13457         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13458           // FIXME: Recover by calling the found function.
13459           return ExprError();
13460 
13461         // No viable function; try to create a built-in operation, which will
13462         // produce an error. Then, show the non-viable candidates.
13463         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13464       }
13465       assert(Result.isInvalid() &&
13466              "C++ binary operator overloading is missing candidates!");
13467       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13468       return Result;
13469     }
13470 
13471     case OR_Ambiguous:
13472       CandidateSet.NoteCandidates(
13473           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13474                                          << BinaryOperator::getOpcodeStr(Opc)
13475                                          << Args[0]->getType()
13476                                          << Args[1]->getType()
13477                                          << Args[0]->getSourceRange()
13478                                          << Args[1]->getSourceRange()),
13479           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13480           OpLoc);
13481       return ExprError();
13482 
13483     case OR_Deleted:
13484       if (isImplicitlyDeleted(Best->Function)) {
13485         FunctionDecl *DeletedFD = Best->Function;
13486         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13487         if (DFK.isSpecialMember()) {
13488           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13489             << Args[0]->getType() << DFK.asSpecialMember();
13490         } else {
13491           assert(DFK.isComparison());
13492           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13493             << Args[0]->getType() << DeletedFD;
13494         }
13495 
13496         // The user probably meant to call this special member. Just
13497         // explain why it's deleted.
13498         NoteDeletedFunction(DeletedFD);
13499         return ExprError();
13500       }
13501       CandidateSet.NoteCandidates(
13502           PartialDiagnosticAt(
13503               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13504                          << getOperatorSpelling(Best->Function->getDeclName()
13505                                                     .getCXXOverloadedOperator())
13506                          << Args[0]->getSourceRange()
13507                          << Args[1]->getSourceRange()),
13508           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13509           OpLoc);
13510       return ExprError();
13511   }
13512 
13513   // We matched a built-in operator; build it.
13514   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13515 }
13516 
13517 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13518     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13519     FunctionDecl *DefaultedFn) {
13520   const ComparisonCategoryInfo *Info =
13521       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13522   // If we're not producing a known comparison category type, we can't
13523   // synthesize a three-way comparison. Let the caller diagnose this.
13524   if (!Info)
13525     return ExprResult((Expr*)nullptr);
13526 
13527   // If we ever want to perform this synthesis more generally, we will need to
13528   // apply the temporary materialization conversion to the operands.
13529   assert(LHS->isGLValue() && RHS->isGLValue() &&
13530          "cannot use prvalue expressions more than once");
13531   Expr *OrigLHS = LHS;
13532   Expr *OrigRHS = RHS;
13533 
13534   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13535   // each of them multiple times below.
13536   LHS = new (Context)
13537       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13538                       LHS->getObjectKind(), LHS);
13539   RHS = new (Context)
13540       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13541                       RHS->getObjectKind(), RHS);
13542 
13543   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13544                                         DefaultedFn);
13545   if (Eq.isInvalid())
13546     return ExprError();
13547 
13548   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13549                                           true, DefaultedFn);
13550   if (Less.isInvalid())
13551     return ExprError();
13552 
13553   ExprResult Greater;
13554   if (Info->isPartial()) {
13555     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13556                                     DefaultedFn);
13557     if (Greater.isInvalid())
13558       return ExprError();
13559   }
13560 
13561   // Form the list of comparisons we're going to perform.
13562   struct Comparison {
13563     ExprResult Cmp;
13564     ComparisonCategoryResult Result;
13565   } Comparisons[4] =
13566   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13567                           : ComparisonCategoryResult::Equivalent},
13568     {Less, ComparisonCategoryResult::Less},
13569     {Greater, ComparisonCategoryResult::Greater},
13570     {ExprResult(), ComparisonCategoryResult::Unordered},
13571   };
13572 
13573   int I = Info->isPartial() ? 3 : 2;
13574 
13575   // Combine the comparisons with suitable conditional expressions.
13576   ExprResult Result;
13577   for (; I >= 0; --I) {
13578     // Build a reference to the comparison category constant.
13579     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13580     // FIXME: Missing a constant for a comparison category. Diagnose this?
13581     if (!VI)
13582       return ExprResult((Expr*)nullptr);
13583     ExprResult ThisResult =
13584         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13585     if (ThisResult.isInvalid())
13586       return ExprError();
13587 
13588     // Build a conditional unless this is the final case.
13589     if (Result.get()) {
13590       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13591                                   ThisResult.get(), Result.get());
13592       if (Result.isInvalid())
13593         return ExprError();
13594     } else {
13595       Result = ThisResult;
13596     }
13597   }
13598 
13599   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13600   // bind the OpaqueValueExprs before they're (repeatedly) used.
13601   Expr *SyntacticForm = new (Context)
13602       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13603                      Result.get()->getValueKind(),
13604                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13605   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13606   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13607 }
13608 
13609 ExprResult
13610 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13611                                          SourceLocation RLoc,
13612                                          Expr *Base, Expr *Idx) {
13613   Expr *Args[2] = { Base, Idx };
13614   DeclarationName OpName =
13615       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13616 
13617   // If either side is type-dependent, create an appropriate dependent
13618   // expression.
13619   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13620 
13621     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13622     // CHECKME: no 'operator' keyword?
13623     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13624     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13625     UnresolvedLookupExpr *Fn
13626       = UnresolvedLookupExpr::Create(Context, NamingClass,
13627                                      NestedNameSpecifierLoc(), OpNameInfo,
13628                                      /*ADL*/ true, /*Overloaded*/ false,
13629                                      UnresolvedSetIterator(),
13630                                      UnresolvedSetIterator());
13631     // Can't add any actual overloads yet
13632 
13633     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13634                                        Context.DependentTy, VK_RValue, RLoc,
13635                                        FPOptions());
13636   }
13637 
13638   // Handle placeholders on both operands.
13639   if (checkPlaceholderForOverload(*this, Args[0]))
13640     return ExprError();
13641   if (checkPlaceholderForOverload(*this, Args[1]))
13642     return ExprError();
13643 
13644   // Build an empty overload set.
13645   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13646 
13647   // Subscript can only be overloaded as a member function.
13648 
13649   // Add operator candidates that are member functions.
13650   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13651 
13652   // Add builtin operator candidates.
13653   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13654 
13655   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13656 
13657   // Perform overload resolution.
13658   OverloadCandidateSet::iterator Best;
13659   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13660     case OR_Success: {
13661       // We found a built-in operator or an overloaded operator.
13662       FunctionDecl *FnDecl = Best->Function;
13663 
13664       if (FnDecl) {
13665         // We matched an overloaded operator. Build a call to that
13666         // operator.
13667 
13668         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13669 
13670         // Convert the arguments.
13671         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13672         ExprResult Arg0 =
13673           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13674                                               Best->FoundDecl, Method);
13675         if (Arg0.isInvalid())
13676           return ExprError();
13677         Args[0] = Arg0.get();
13678 
13679         // Convert the arguments.
13680         ExprResult InputInit
13681           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13682                                                       Context,
13683                                                       FnDecl->getParamDecl(0)),
13684                                       SourceLocation(),
13685                                       Args[1]);
13686         if (InputInit.isInvalid())
13687           return ExprError();
13688 
13689         Args[1] = InputInit.getAs<Expr>();
13690 
13691         // Build the actual expression node.
13692         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13693         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13694         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13695                                                   Best->FoundDecl,
13696                                                   Base,
13697                                                   HadMultipleCandidates,
13698                                                   OpLocInfo.getLoc(),
13699                                                   OpLocInfo.getInfo());
13700         if (FnExpr.isInvalid())
13701           return ExprError();
13702 
13703         // Determine the result type
13704         QualType ResultTy = FnDecl->getReturnType();
13705         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13706         ResultTy = ResultTy.getNonLValueExprType(Context);
13707 
13708         CXXOperatorCallExpr *TheCall =
13709             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13710                                         Args, ResultTy, VK, RLoc, FPOptions());
13711 
13712         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13713           return ExprError();
13714 
13715         if (CheckFunctionCall(Method, TheCall,
13716                               Method->getType()->castAs<FunctionProtoType>()))
13717           return ExprError();
13718 
13719         return MaybeBindToTemporary(TheCall);
13720       } else {
13721         // We matched a built-in operator. Convert the arguments, then
13722         // break out so that we will build the appropriate built-in
13723         // operator node.
13724         ExprResult ArgsRes0 = PerformImplicitConversion(
13725             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13726             AA_Passing, CCK_ForBuiltinOverloadedOp);
13727         if (ArgsRes0.isInvalid())
13728           return ExprError();
13729         Args[0] = ArgsRes0.get();
13730 
13731         ExprResult ArgsRes1 = PerformImplicitConversion(
13732             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13733             AA_Passing, CCK_ForBuiltinOverloadedOp);
13734         if (ArgsRes1.isInvalid())
13735           return ExprError();
13736         Args[1] = ArgsRes1.get();
13737 
13738         break;
13739       }
13740     }
13741 
13742     case OR_No_Viable_Function: {
13743       PartialDiagnostic PD = CandidateSet.empty()
13744           ? (PDiag(diag::err_ovl_no_oper)
13745              << Args[0]->getType() << /*subscript*/ 0
13746              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13747           : (PDiag(diag::err_ovl_no_viable_subscript)
13748              << Args[0]->getType() << Args[0]->getSourceRange()
13749              << Args[1]->getSourceRange());
13750       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13751                                   OCD_AllCandidates, Args, "[]", LLoc);
13752       return ExprError();
13753     }
13754 
13755     case OR_Ambiguous:
13756       CandidateSet.NoteCandidates(
13757           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13758                                         << "[]" << Args[0]->getType()
13759                                         << Args[1]->getType()
13760                                         << Args[0]->getSourceRange()
13761                                         << Args[1]->getSourceRange()),
13762           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13763       return ExprError();
13764 
13765     case OR_Deleted:
13766       CandidateSet.NoteCandidates(
13767           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13768                                         << "[]" << Args[0]->getSourceRange()
13769                                         << Args[1]->getSourceRange()),
13770           *this, OCD_AllCandidates, Args, "[]", LLoc);
13771       return ExprError();
13772     }
13773 
13774   // We matched a built-in operator; build it.
13775   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13776 }
13777 
13778 /// BuildCallToMemberFunction - Build a call to a member
13779 /// function. MemExpr is the expression that refers to the member
13780 /// function (and includes the object parameter), Args/NumArgs are the
13781 /// arguments to the function call (not including the object
13782 /// parameter). The caller needs to validate that the member
13783 /// expression refers to a non-static member function or an overloaded
13784 /// member function.
13785 ExprResult
13786 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13787                                 SourceLocation LParenLoc,
13788                                 MultiExprArg Args,
13789                                 SourceLocation RParenLoc) {
13790   assert(MemExprE->getType() == Context.BoundMemberTy ||
13791          MemExprE->getType() == Context.OverloadTy);
13792 
13793   // Dig out the member expression. This holds both the object
13794   // argument and the member function we're referring to.
13795   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13796 
13797   // Determine whether this is a call to a pointer-to-member function.
13798   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13799     assert(op->getType() == Context.BoundMemberTy);
13800     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13801 
13802     QualType fnType =
13803       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13804 
13805     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13806     QualType resultType = proto->getCallResultType(Context);
13807     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13808 
13809     // Check that the object type isn't more qualified than the
13810     // member function we're calling.
13811     Qualifiers funcQuals = proto->getMethodQuals();
13812 
13813     QualType objectType = op->getLHS()->getType();
13814     if (op->getOpcode() == BO_PtrMemI)
13815       objectType = objectType->castAs<PointerType>()->getPointeeType();
13816     Qualifiers objectQuals = objectType.getQualifiers();
13817 
13818     Qualifiers difference = objectQuals - funcQuals;
13819     difference.removeObjCGCAttr();
13820     difference.removeAddressSpace();
13821     if (difference) {
13822       std::string qualsString = difference.getAsString();
13823       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13824         << fnType.getUnqualifiedType()
13825         << qualsString
13826         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13827     }
13828 
13829     CXXMemberCallExpr *call =
13830         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13831                                   valueKind, RParenLoc, proto->getNumParams());
13832 
13833     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13834                             call, nullptr))
13835       return ExprError();
13836 
13837     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13838       return ExprError();
13839 
13840     if (CheckOtherCall(call, proto))
13841       return ExprError();
13842 
13843     return MaybeBindToTemporary(call);
13844   }
13845 
13846   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13847     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13848                             RParenLoc);
13849 
13850   UnbridgedCastsSet UnbridgedCasts;
13851   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13852     return ExprError();
13853 
13854   MemberExpr *MemExpr;
13855   CXXMethodDecl *Method = nullptr;
13856   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13857   NestedNameSpecifier *Qualifier = nullptr;
13858   if (isa<MemberExpr>(NakedMemExpr)) {
13859     MemExpr = cast<MemberExpr>(NakedMemExpr);
13860     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13861     FoundDecl = MemExpr->getFoundDecl();
13862     Qualifier = MemExpr->getQualifier();
13863     UnbridgedCasts.restore();
13864   } else {
13865     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13866     Qualifier = UnresExpr->getQualifier();
13867 
13868     QualType ObjectType = UnresExpr->getBaseType();
13869     Expr::Classification ObjectClassification
13870       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13871                             : UnresExpr->getBase()->Classify(Context);
13872 
13873     // Add overload candidates
13874     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13875                                       OverloadCandidateSet::CSK_Normal);
13876 
13877     // FIXME: avoid copy.
13878     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13879     if (UnresExpr->hasExplicitTemplateArgs()) {
13880       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13881       TemplateArgs = &TemplateArgsBuffer;
13882     }
13883 
13884     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13885            E = UnresExpr->decls_end(); I != E; ++I) {
13886 
13887       NamedDecl *Func = *I;
13888       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13889       if (isa<UsingShadowDecl>(Func))
13890         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13891 
13892 
13893       // Microsoft supports direct constructor calls.
13894       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13895         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13896                              CandidateSet,
13897                              /*SuppressUserConversions*/ false);
13898       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13899         // If explicit template arguments were provided, we can't call a
13900         // non-template member function.
13901         if (TemplateArgs)
13902           continue;
13903 
13904         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13905                            ObjectClassification, Args, CandidateSet,
13906                            /*SuppressUserConversions=*/false);
13907       } else {
13908         AddMethodTemplateCandidate(
13909             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13910             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13911             /*SuppressUserConversions=*/false);
13912       }
13913     }
13914 
13915     DeclarationName DeclName = UnresExpr->getMemberName();
13916 
13917     UnbridgedCasts.restore();
13918 
13919     OverloadCandidateSet::iterator Best;
13920     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13921                                             Best)) {
13922     case OR_Success:
13923       Method = cast<CXXMethodDecl>(Best->Function);
13924       FoundDecl = Best->FoundDecl;
13925       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13926       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13927         return ExprError();
13928       // If FoundDecl is different from Method (such as if one is a template
13929       // and the other a specialization), make sure DiagnoseUseOfDecl is
13930       // called on both.
13931       // FIXME: This would be more comprehensively addressed by modifying
13932       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13933       // being used.
13934       if (Method != FoundDecl.getDecl() &&
13935                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13936         return ExprError();
13937       break;
13938 
13939     case OR_No_Viable_Function:
13940       CandidateSet.NoteCandidates(
13941           PartialDiagnosticAt(
13942               UnresExpr->getMemberLoc(),
13943               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13944                   << DeclName << MemExprE->getSourceRange()),
13945           *this, OCD_AllCandidates, Args);
13946       // FIXME: Leaking incoming expressions!
13947       return ExprError();
13948 
13949     case OR_Ambiguous:
13950       CandidateSet.NoteCandidates(
13951           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13952                               PDiag(diag::err_ovl_ambiguous_member_call)
13953                                   << DeclName << MemExprE->getSourceRange()),
13954           *this, OCD_AmbiguousCandidates, Args);
13955       // FIXME: Leaking incoming expressions!
13956       return ExprError();
13957 
13958     case OR_Deleted:
13959       CandidateSet.NoteCandidates(
13960           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13961                               PDiag(diag::err_ovl_deleted_member_call)
13962                                   << DeclName << MemExprE->getSourceRange()),
13963           *this, OCD_AllCandidates, Args);
13964       // FIXME: Leaking incoming expressions!
13965       return ExprError();
13966     }
13967 
13968     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13969 
13970     // If overload resolution picked a static member, build a
13971     // non-member call based on that function.
13972     if (Method->isStatic()) {
13973       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13974                                    RParenLoc);
13975     }
13976 
13977     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13978   }
13979 
13980   QualType ResultType = Method->getReturnType();
13981   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13982   ResultType = ResultType.getNonLValueExprType(Context);
13983 
13984   assert(Method && "Member call to something that isn't a method?");
13985   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13986   CXXMemberCallExpr *TheCall =
13987       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13988                                 RParenLoc, Proto->getNumParams());
13989 
13990   // Check for a valid return type.
13991   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13992                           TheCall, Method))
13993     return ExprError();
13994 
13995   // Convert the object argument (for a non-static member function call).
13996   // We only need to do this if there was actually an overload; otherwise
13997   // it was done at lookup.
13998   if (!Method->isStatic()) {
13999     ExprResult ObjectArg =
14000       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14001                                           FoundDecl, Method);
14002     if (ObjectArg.isInvalid())
14003       return ExprError();
14004     MemExpr->setBase(ObjectArg.get());
14005   }
14006 
14007   // Convert the rest of the arguments
14008   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14009                               RParenLoc))
14010     return ExprError();
14011 
14012   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14013 
14014   if (CheckFunctionCall(Method, TheCall, Proto))
14015     return ExprError();
14016 
14017   // In the case the method to call was not selected by the overloading
14018   // resolution process, we still need to handle the enable_if attribute. Do
14019   // that here, so it will not hide previous -- and more relevant -- errors.
14020   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14021     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14022       Diag(MemE->getMemberLoc(),
14023            diag::err_ovl_no_viable_member_function_in_call)
14024           << Method << Method->getSourceRange();
14025       Diag(Method->getLocation(),
14026            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14027           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14028       return ExprError();
14029     }
14030   }
14031 
14032   if ((isa<CXXConstructorDecl>(CurContext) ||
14033        isa<CXXDestructorDecl>(CurContext)) &&
14034       TheCall->getMethodDecl()->isPure()) {
14035     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14036 
14037     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14038         MemExpr->performsVirtualDispatch(getLangOpts())) {
14039       Diag(MemExpr->getBeginLoc(),
14040            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14041           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14042           << MD->getParent()->getDeclName();
14043 
14044       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14045       if (getLangOpts().AppleKext)
14046         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14047             << MD->getParent()->getDeclName() << MD->getDeclName();
14048     }
14049   }
14050 
14051   if (CXXDestructorDecl *DD =
14052           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14053     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14054     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14055     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14056                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14057                          MemExpr->getMemberLoc());
14058   }
14059 
14060   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14061                                      TheCall->getMethodDecl());
14062 }
14063 
14064 /// BuildCallToObjectOfClassType - Build a call to an object of class
14065 /// type (C++ [over.call.object]), which can end up invoking an
14066 /// overloaded function call operator (@c operator()) or performing a
14067 /// user-defined conversion on the object argument.
14068 ExprResult
14069 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14070                                    SourceLocation LParenLoc,
14071                                    MultiExprArg Args,
14072                                    SourceLocation RParenLoc) {
14073   if (checkPlaceholderForOverload(*this, Obj))
14074     return ExprError();
14075   ExprResult Object = Obj;
14076 
14077   UnbridgedCastsSet UnbridgedCasts;
14078   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14079     return ExprError();
14080 
14081   assert(Object.get()->getType()->isRecordType() &&
14082          "Requires object type argument");
14083 
14084   // C++ [over.call.object]p1:
14085   //  If the primary-expression E in the function call syntax
14086   //  evaluates to a class object of type "cv T", then the set of
14087   //  candidate functions includes at least the function call
14088   //  operators of T. The function call operators of T are obtained by
14089   //  ordinary lookup of the name operator() in the context of
14090   //  (E).operator().
14091   OverloadCandidateSet CandidateSet(LParenLoc,
14092                                     OverloadCandidateSet::CSK_Operator);
14093   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14094 
14095   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14096                           diag::err_incomplete_object_call, Object.get()))
14097     return true;
14098 
14099   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14100   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14101   LookupQualifiedName(R, Record->getDecl());
14102   R.suppressDiagnostics();
14103 
14104   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14105        Oper != OperEnd; ++Oper) {
14106     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14107                        Object.get()->Classify(Context), Args, CandidateSet,
14108                        /*SuppressUserConversion=*/false);
14109   }
14110 
14111   // C++ [over.call.object]p2:
14112   //   In addition, for each (non-explicit in C++0x) conversion function
14113   //   declared in T of the form
14114   //
14115   //        operator conversion-type-id () cv-qualifier;
14116   //
14117   //   where cv-qualifier is the same cv-qualification as, or a
14118   //   greater cv-qualification than, cv, and where conversion-type-id
14119   //   denotes the type "pointer to function of (P1,...,Pn) returning
14120   //   R", or the type "reference to pointer to function of
14121   //   (P1,...,Pn) returning R", or the type "reference to function
14122   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14123   //   is also considered as a candidate function. Similarly,
14124   //   surrogate call functions are added to the set of candidate
14125   //   functions for each conversion function declared in an
14126   //   accessible base class provided the function is not hidden
14127   //   within T by another intervening declaration.
14128   const auto &Conversions =
14129       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14130   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14131     NamedDecl *D = *I;
14132     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14133     if (isa<UsingShadowDecl>(D))
14134       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14135 
14136     // Skip over templated conversion functions; they aren't
14137     // surrogates.
14138     if (isa<FunctionTemplateDecl>(D))
14139       continue;
14140 
14141     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14142     if (!Conv->isExplicit()) {
14143       // Strip the reference type (if any) and then the pointer type (if
14144       // any) to get down to what might be a function type.
14145       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14146       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14147         ConvType = ConvPtrType->getPointeeType();
14148 
14149       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14150       {
14151         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14152                               Object.get(), Args, CandidateSet);
14153       }
14154     }
14155   }
14156 
14157   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14158 
14159   // Perform overload resolution.
14160   OverloadCandidateSet::iterator Best;
14161   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14162                                           Best)) {
14163   case OR_Success:
14164     // Overload resolution succeeded; we'll build the appropriate call
14165     // below.
14166     break;
14167 
14168   case OR_No_Viable_Function: {
14169     PartialDiagnostic PD =
14170         CandidateSet.empty()
14171             ? (PDiag(diag::err_ovl_no_oper)
14172                << Object.get()->getType() << /*call*/ 1
14173                << Object.get()->getSourceRange())
14174             : (PDiag(diag::err_ovl_no_viable_object_call)
14175                << Object.get()->getType() << Object.get()->getSourceRange());
14176     CandidateSet.NoteCandidates(
14177         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14178         OCD_AllCandidates, Args);
14179     break;
14180   }
14181   case OR_Ambiguous:
14182     CandidateSet.NoteCandidates(
14183         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14184                             PDiag(diag::err_ovl_ambiguous_object_call)
14185                                 << Object.get()->getType()
14186                                 << Object.get()->getSourceRange()),
14187         *this, OCD_AmbiguousCandidates, Args);
14188     break;
14189 
14190   case OR_Deleted:
14191     CandidateSet.NoteCandidates(
14192         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14193                             PDiag(diag::err_ovl_deleted_object_call)
14194                                 << Object.get()->getType()
14195                                 << Object.get()->getSourceRange()),
14196         *this, OCD_AllCandidates, Args);
14197     break;
14198   }
14199 
14200   if (Best == CandidateSet.end())
14201     return true;
14202 
14203   UnbridgedCasts.restore();
14204 
14205   if (Best->Function == nullptr) {
14206     // Since there is no function declaration, this is one of the
14207     // surrogate candidates. Dig out the conversion function.
14208     CXXConversionDecl *Conv
14209       = cast<CXXConversionDecl>(
14210                          Best->Conversions[0].UserDefined.ConversionFunction);
14211 
14212     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14213                               Best->FoundDecl);
14214     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14215       return ExprError();
14216     assert(Conv == Best->FoundDecl.getDecl() &&
14217              "Found Decl & conversion-to-functionptr should be same, right?!");
14218     // We selected one of the surrogate functions that converts the
14219     // object parameter to a function pointer. Perform the conversion
14220     // on the object argument, then let BuildCallExpr finish the job.
14221 
14222     // Create an implicit member expr to refer to the conversion operator.
14223     // and then call it.
14224     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14225                                              Conv, HadMultipleCandidates);
14226     if (Call.isInvalid())
14227       return ExprError();
14228     // Record usage of conversion in an implicit cast.
14229     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14230                                     CK_UserDefinedConversion, Call.get(),
14231                                     nullptr, VK_RValue);
14232 
14233     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14234   }
14235 
14236   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14237 
14238   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14239   // that calls this method, using Object for the implicit object
14240   // parameter and passing along the remaining arguments.
14241   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14242 
14243   // An error diagnostic has already been printed when parsing the declaration.
14244   if (Method->isInvalidDecl())
14245     return ExprError();
14246 
14247   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14248   unsigned NumParams = Proto->getNumParams();
14249 
14250   DeclarationNameInfo OpLocInfo(
14251                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14252   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14253   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14254                                            Obj, HadMultipleCandidates,
14255                                            OpLocInfo.getLoc(),
14256                                            OpLocInfo.getInfo());
14257   if (NewFn.isInvalid())
14258     return true;
14259 
14260   // The number of argument slots to allocate in the call. If we have default
14261   // arguments we need to allocate space for them as well. We additionally
14262   // need one more slot for the object parameter.
14263   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14264 
14265   // Build the full argument list for the method call (the implicit object
14266   // parameter is placed at the beginning of the list).
14267   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14268 
14269   bool IsError = false;
14270 
14271   // Initialize the implicit object parameter.
14272   ExprResult ObjRes =
14273     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14274                                         Best->FoundDecl, Method);
14275   if (ObjRes.isInvalid())
14276     IsError = true;
14277   else
14278     Object = ObjRes;
14279   MethodArgs[0] = Object.get();
14280 
14281   // Check the argument types.
14282   for (unsigned i = 0; i != NumParams; i++) {
14283     Expr *Arg;
14284     if (i < Args.size()) {
14285       Arg = Args[i];
14286 
14287       // Pass the argument.
14288 
14289       ExprResult InputInit
14290         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14291                                                     Context,
14292                                                     Method->getParamDecl(i)),
14293                                     SourceLocation(), Arg);
14294 
14295       IsError |= InputInit.isInvalid();
14296       Arg = InputInit.getAs<Expr>();
14297     } else {
14298       ExprResult DefArg
14299         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14300       if (DefArg.isInvalid()) {
14301         IsError = true;
14302         break;
14303       }
14304 
14305       Arg = DefArg.getAs<Expr>();
14306     }
14307 
14308     MethodArgs[i + 1] = Arg;
14309   }
14310 
14311   // If this is a variadic call, handle args passed through "...".
14312   if (Proto->isVariadic()) {
14313     // Promote the arguments (C99 6.5.2.2p7).
14314     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14315       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14316                                                         nullptr);
14317       IsError |= Arg.isInvalid();
14318       MethodArgs[i + 1] = Arg.get();
14319     }
14320   }
14321 
14322   if (IsError)
14323     return true;
14324 
14325   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14326 
14327   // Once we've built TheCall, all of the expressions are properly owned.
14328   QualType ResultTy = Method->getReturnType();
14329   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14330   ResultTy = ResultTy.getNonLValueExprType(Context);
14331 
14332   CXXOperatorCallExpr *TheCall =
14333       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14334                                   ResultTy, VK, RParenLoc, FPOptions());
14335 
14336   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14337     return true;
14338 
14339   if (CheckFunctionCall(Method, TheCall, Proto))
14340     return true;
14341 
14342   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14343 }
14344 
14345 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14346 ///  (if one exists), where @c Base is an expression of class type and
14347 /// @c Member is the name of the member we're trying to find.
14348 ExprResult
14349 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14350                                bool *NoArrowOperatorFound) {
14351   assert(Base->getType()->isRecordType() &&
14352          "left-hand side must have class type");
14353 
14354   if (checkPlaceholderForOverload(*this, Base))
14355     return ExprError();
14356 
14357   SourceLocation Loc = Base->getExprLoc();
14358 
14359   // C++ [over.ref]p1:
14360   //
14361   //   [...] An expression x->m is interpreted as (x.operator->())->m
14362   //   for a class object x of type T if T::operator->() exists and if
14363   //   the operator is selected as the best match function by the
14364   //   overload resolution mechanism (13.3).
14365   DeclarationName OpName =
14366     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14367   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14368 
14369   if (RequireCompleteType(Loc, Base->getType(),
14370                           diag::err_typecheck_incomplete_tag, Base))
14371     return ExprError();
14372 
14373   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14374   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14375   R.suppressDiagnostics();
14376 
14377   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14378        Oper != OperEnd; ++Oper) {
14379     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14380                        None, CandidateSet, /*SuppressUserConversion=*/false);
14381   }
14382 
14383   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14384 
14385   // Perform overload resolution.
14386   OverloadCandidateSet::iterator Best;
14387   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14388   case OR_Success:
14389     // Overload resolution succeeded; we'll build the call below.
14390     break;
14391 
14392   case OR_No_Viable_Function: {
14393     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14394     if (CandidateSet.empty()) {
14395       QualType BaseType = Base->getType();
14396       if (NoArrowOperatorFound) {
14397         // Report this specific error to the caller instead of emitting a
14398         // diagnostic, as requested.
14399         *NoArrowOperatorFound = true;
14400         return ExprError();
14401       }
14402       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14403         << BaseType << Base->getSourceRange();
14404       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14405         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14406           << FixItHint::CreateReplacement(OpLoc, ".");
14407       }
14408     } else
14409       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14410         << "operator->" << Base->getSourceRange();
14411     CandidateSet.NoteCandidates(*this, Base, Cands);
14412     return ExprError();
14413   }
14414   case OR_Ambiguous:
14415     CandidateSet.NoteCandidates(
14416         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14417                                        << "->" << Base->getType()
14418                                        << Base->getSourceRange()),
14419         *this, OCD_AmbiguousCandidates, Base);
14420     return ExprError();
14421 
14422   case OR_Deleted:
14423     CandidateSet.NoteCandidates(
14424         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14425                                        << "->" << Base->getSourceRange()),
14426         *this, OCD_AllCandidates, Base);
14427     return ExprError();
14428   }
14429 
14430   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14431 
14432   // Convert the object parameter.
14433   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14434   ExprResult BaseResult =
14435     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14436                                         Best->FoundDecl, Method);
14437   if (BaseResult.isInvalid())
14438     return ExprError();
14439   Base = BaseResult.get();
14440 
14441   // Build the operator call.
14442   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14443                                             Base, HadMultipleCandidates, OpLoc);
14444   if (FnExpr.isInvalid())
14445     return ExprError();
14446 
14447   QualType ResultTy = Method->getReturnType();
14448   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14449   ResultTy = ResultTy.getNonLValueExprType(Context);
14450   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14451       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14452 
14453   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14454     return ExprError();
14455 
14456   if (CheckFunctionCall(Method, TheCall,
14457                         Method->getType()->castAs<FunctionProtoType>()))
14458     return ExprError();
14459 
14460   return MaybeBindToTemporary(TheCall);
14461 }
14462 
14463 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14464 /// a literal operator described by the provided lookup results.
14465 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14466                                           DeclarationNameInfo &SuffixInfo,
14467                                           ArrayRef<Expr*> Args,
14468                                           SourceLocation LitEndLoc,
14469                                        TemplateArgumentListInfo *TemplateArgs) {
14470   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14471 
14472   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14473                                     OverloadCandidateSet::CSK_Normal);
14474   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14475                                  TemplateArgs);
14476 
14477   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14478 
14479   // Perform overload resolution. This will usually be trivial, but might need
14480   // to perform substitutions for a literal operator template.
14481   OverloadCandidateSet::iterator Best;
14482   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14483   case OR_Success:
14484   case OR_Deleted:
14485     break;
14486 
14487   case OR_No_Viable_Function:
14488     CandidateSet.NoteCandidates(
14489         PartialDiagnosticAt(UDSuffixLoc,
14490                             PDiag(diag::err_ovl_no_viable_function_in_call)
14491                                 << R.getLookupName()),
14492         *this, OCD_AllCandidates, Args);
14493     return ExprError();
14494 
14495   case OR_Ambiguous:
14496     CandidateSet.NoteCandidates(
14497         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14498                                                 << R.getLookupName()),
14499         *this, OCD_AmbiguousCandidates, Args);
14500     return ExprError();
14501   }
14502 
14503   FunctionDecl *FD = Best->Function;
14504   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14505                                         nullptr, HadMultipleCandidates,
14506                                         SuffixInfo.getLoc(),
14507                                         SuffixInfo.getInfo());
14508   if (Fn.isInvalid())
14509     return true;
14510 
14511   // Check the argument types. This should almost always be a no-op, except
14512   // that array-to-pointer decay is applied to string literals.
14513   Expr *ConvArgs[2];
14514   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14515     ExprResult InputInit = PerformCopyInitialization(
14516       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14517       SourceLocation(), Args[ArgIdx]);
14518     if (InputInit.isInvalid())
14519       return true;
14520     ConvArgs[ArgIdx] = InputInit.get();
14521   }
14522 
14523   QualType ResultTy = FD->getReturnType();
14524   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14525   ResultTy = ResultTy.getNonLValueExprType(Context);
14526 
14527   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14528       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14529       VK, LitEndLoc, UDSuffixLoc);
14530 
14531   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14532     return ExprError();
14533 
14534   if (CheckFunctionCall(FD, UDL, nullptr))
14535     return ExprError();
14536 
14537   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14538 }
14539 
14540 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14541 /// given LookupResult is non-empty, it is assumed to describe a member which
14542 /// will be invoked. Otherwise, the function will be found via argument
14543 /// dependent lookup.
14544 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14545 /// otherwise CallExpr is set to ExprError() and some non-success value
14546 /// is returned.
14547 Sema::ForRangeStatus
14548 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14549                                 SourceLocation RangeLoc,
14550                                 const DeclarationNameInfo &NameInfo,
14551                                 LookupResult &MemberLookup,
14552                                 OverloadCandidateSet *CandidateSet,
14553                                 Expr *Range, ExprResult *CallExpr) {
14554   Scope *S = nullptr;
14555 
14556   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14557   if (!MemberLookup.empty()) {
14558     ExprResult MemberRef =
14559         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14560                                  /*IsPtr=*/false, CXXScopeSpec(),
14561                                  /*TemplateKWLoc=*/SourceLocation(),
14562                                  /*FirstQualifierInScope=*/nullptr,
14563                                  MemberLookup,
14564                                  /*TemplateArgs=*/nullptr, S);
14565     if (MemberRef.isInvalid()) {
14566       *CallExpr = ExprError();
14567       return FRS_DiagnosticIssued;
14568     }
14569     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14570     if (CallExpr->isInvalid()) {
14571       *CallExpr = ExprError();
14572       return FRS_DiagnosticIssued;
14573     }
14574   } else {
14575     UnresolvedSet<0> FoundNames;
14576     UnresolvedLookupExpr *Fn =
14577       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14578                                    NestedNameSpecifierLoc(), NameInfo,
14579                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14580                                    FoundNames.begin(), FoundNames.end());
14581 
14582     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14583                                                     CandidateSet, CallExpr);
14584     if (CandidateSet->empty() || CandidateSetError) {
14585       *CallExpr = ExprError();
14586       return FRS_NoViableFunction;
14587     }
14588     OverloadCandidateSet::iterator Best;
14589     OverloadingResult OverloadResult =
14590         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14591 
14592     if (OverloadResult == OR_No_Viable_Function) {
14593       *CallExpr = ExprError();
14594       return FRS_NoViableFunction;
14595     }
14596     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14597                                          Loc, nullptr, CandidateSet, &Best,
14598                                          OverloadResult,
14599                                          /*AllowTypoCorrection=*/false);
14600     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14601       *CallExpr = ExprError();
14602       return FRS_DiagnosticIssued;
14603     }
14604   }
14605   return FRS_Success;
14606 }
14607 
14608 
14609 /// FixOverloadedFunctionReference - E is an expression that refers to
14610 /// a C++ overloaded function (possibly with some parentheses and
14611 /// perhaps a '&' around it). We have resolved the overloaded function
14612 /// to the function declaration Fn, so patch up the expression E to
14613 /// refer (possibly indirectly) to Fn. Returns the new expr.
14614 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14615                                            FunctionDecl *Fn) {
14616   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14617     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14618                                                    Found, Fn);
14619     if (SubExpr == PE->getSubExpr())
14620       return PE;
14621 
14622     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14623   }
14624 
14625   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14626     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14627                                                    Found, Fn);
14628     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14629                                SubExpr->getType()) &&
14630            "Implicit cast type cannot be determined from overload");
14631     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14632     if (SubExpr == ICE->getSubExpr())
14633       return ICE;
14634 
14635     return ImplicitCastExpr::Create(Context, ICE->getType(),
14636                                     ICE->getCastKind(),
14637                                     SubExpr, nullptr,
14638                                     ICE->getValueKind());
14639   }
14640 
14641   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14642     if (!GSE->isResultDependent()) {
14643       Expr *SubExpr =
14644           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14645       if (SubExpr == GSE->getResultExpr())
14646         return GSE;
14647 
14648       // Replace the resulting type information before rebuilding the generic
14649       // selection expression.
14650       ArrayRef<Expr *> A = GSE->getAssocExprs();
14651       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14652       unsigned ResultIdx = GSE->getResultIndex();
14653       AssocExprs[ResultIdx] = SubExpr;
14654 
14655       return GenericSelectionExpr::Create(
14656           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14657           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14658           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14659           ResultIdx);
14660     }
14661     // Rather than fall through to the unreachable, return the original generic
14662     // selection expression.
14663     return GSE;
14664   }
14665 
14666   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14667     assert(UnOp->getOpcode() == UO_AddrOf &&
14668            "Can only take the address of an overloaded function");
14669     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14670       if (Method->isStatic()) {
14671         // Do nothing: static member functions aren't any different
14672         // from non-member functions.
14673       } else {
14674         // Fix the subexpression, which really has to be an
14675         // UnresolvedLookupExpr holding an overloaded member function
14676         // or template.
14677         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14678                                                        Found, Fn);
14679         if (SubExpr == UnOp->getSubExpr())
14680           return UnOp;
14681 
14682         assert(isa<DeclRefExpr>(SubExpr)
14683                && "fixed to something other than a decl ref");
14684         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14685                && "fixed to a member ref with no nested name qualifier");
14686 
14687         // We have taken the address of a pointer to member
14688         // function. Perform the computation here so that we get the
14689         // appropriate pointer to member type.
14690         QualType ClassType
14691           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14692         QualType MemPtrType
14693           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14694         // Under the MS ABI, lock down the inheritance model now.
14695         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14696           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14697 
14698         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14699                                            VK_RValue, OK_Ordinary,
14700                                            UnOp->getOperatorLoc(), false);
14701       }
14702     }
14703     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14704                                                    Found, Fn);
14705     if (SubExpr == UnOp->getSubExpr())
14706       return UnOp;
14707 
14708     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14709                                      Context.getPointerType(SubExpr->getType()),
14710                                        VK_RValue, OK_Ordinary,
14711                                        UnOp->getOperatorLoc(), false);
14712   }
14713 
14714   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14715     // FIXME: avoid copy.
14716     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14717     if (ULE->hasExplicitTemplateArgs()) {
14718       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14719       TemplateArgs = &TemplateArgsBuffer;
14720     }
14721 
14722     DeclRefExpr *DRE =
14723         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14724                          ULE->getQualifierLoc(), Found.getDecl(),
14725                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14726     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14727     return DRE;
14728   }
14729 
14730   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14731     // FIXME: avoid copy.
14732     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14733     if (MemExpr->hasExplicitTemplateArgs()) {
14734       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14735       TemplateArgs = &TemplateArgsBuffer;
14736     }
14737 
14738     Expr *Base;
14739 
14740     // If we're filling in a static method where we used to have an
14741     // implicit member access, rewrite to a simple decl ref.
14742     if (MemExpr->isImplicitAccess()) {
14743       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14744         DeclRefExpr *DRE = BuildDeclRefExpr(
14745             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14746             MemExpr->getQualifierLoc(), Found.getDecl(),
14747             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14748         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14749         return DRE;
14750       } else {
14751         SourceLocation Loc = MemExpr->getMemberLoc();
14752         if (MemExpr->getQualifier())
14753           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14754         Base =
14755             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14756       }
14757     } else
14758       Base = MemExpr->getBase();
14759 
14760     ExprValueKind valueKind;
14761     QualType type;
14762     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14763       valueKind = VK_LValue;
14764       type = Fn->getType();
14765     } else {
14766       valueKind = VK_RValue;
14767       type = Context.BoundMemberTy;
14768     }
14769 
14770     return BuildMemberExpr(
14771         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14772         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14773         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14774         type, valueKind, OK_Ordinary, TemplateArgs);
14775   }
14776 
14777   llvm_unreachable("Invalid reference to overloaded function");
14778 }
14779 
14780 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14781                                                 DeclAccessPair Found,
14782                                                 FunctionDecl *Fn) {
14783   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14784 }
14785