1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_OCL_Scalar_Widening,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isMemberPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
261                                              const Expr *Converted) {
262   // We can have cleanups wrapping the converted expression; these need to be
263   // preserved so that destructors run if necessary.
264   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
265     Expr *Inner =
266         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
267     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
268                                     EWC->getObjects());
269   }
270 
271   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
272     switch (ICE->getCastKind()) {
273     case CK_NoOp:
274     case CK_IntegralCast:
275     case CK_IntegralToBoolean:
276     case CK_IntegralToFloating:
277     case CK_BooleanToSignedIntegral:
278     case CK_FloatingToIntegral:
279     case CK_FloatingToBoolean:
280     case CK_FloatingCast:
281       Converted = ICE->getSubExpr();
282       continue;
283 
284     default:
285       return Converted;
286     }
287   }
288 
289   return Converted;
290 }
291 
292 /// Check if this standard conversion sequence represents a narrowing
293 /// conversion, according to C++11 [dcl.init.list]p7.
294 ///
295 /// \param Ctx  The AST context.
296 /// \param Converted  The result of applying this standard conversion sequence.
297 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
298 ///        value of the expression prior to the narrowing conversion.
299 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
300 ///        type of the expression prior to the narrowing conversion.
301 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
302 ///        from floating point types to integral types should be ignored.
303 NarrowingKind StandardConversionSequence::getNarrowingKind(
304     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
305     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
306   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
307 
308   // C++11 [dcl.init.list]p7:
309   //   A narrowing conversion is an implicit conversion ...
310   QualType FromType = getToType(0);
311   QualType ToType = getToType(1);
312 
313   // A conversion to an enumeration type is narrowing if the conversion to
314   // the underlying type is narrowing. This only arises for expressions of
315   // the form 'Enum{init}'.
316   if (auto *ET = ToType->getAs<EnumType>())
317     ToType = ET->getDecl()->getIntegerType();
318 
319   switch (Second) {
320   // 'bool' is an integral type; dispatch to the right place to handle it.
321   case ICK_Boolean_Conversion:
322     if (FromType->isRealFloatingType())
323       goto FloatingIntegralConversion;
324     if (FromType->isIntegralOrUnscopedEnumerationType())
325       goto IntegralConversion;
326     // Boolean conversions can be from pointers and pointers to members
327     // [conv.bool], and those aren't considered narrowing conversions.
328     return NK_Not_Narrowing;
329 
330   // -- from a floating-point type to an integer type, or
331   //
332   // -- from an integer type or unscoped enumeration type to a floating-point
333   //    type, except where the source is a constant expression and the actual
334   //    value after conversion will fit into the target type and will produce
335   //    the original value when converted back to the original type, or
336   case ICK_Floating_Integral:
337   FloatingIntegralConversion:
338     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
339       return NK_Type_Narrowing;
340     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
341                ToType->isRealFloatingType()) {
342       if (IgnoreFloatToIntegralConversion)
343         return NK_Not_Narrowing;
344       llvm::APSInt IntConstantValue;
345       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
346       assert(Initializer && "Unknown conversion expression");
347 
348       // If it's value-dependent, we can't tell whether it's narrowing.
349       if (Initializer->isValueDependent())
350         return NK_Dependent_Narrowing;
351 
352       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
353         // Convert the integer to the floating type.
354         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
355         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
356                                 llvm::APFloat::rmNearestTiesToEven);
357         // And back.
358         llvm::APSInt ConvertedValue = IntConstantValue;
359         bool ignored;
360         Result.convertToInteger(ConvertedValue,
361                                 llvm::APFloat::rmTowardZero, &ignored);
362         // If the resulting value is different, this was a narrowing conversion.
363         if (IntConstantValue != ConvertedValue) {
364           ConstantValue = APValue(IntConstantValue);
365           ConstantType = Initializer->getType();
366           return NK_Constant_Narrowing;
367         }
368       } else {
369         // Variables are always narrowings.
370         return NK_Variable_Narrowing;
371       }
372     }
373     return NK_Not_Narrowing;
374 
375   // -- from long double to double or float, or from double to float, except
376   //    where the source is a constant expression and the actual value after
377   //    conversion is within the range of values that can be represented (even
378   //    if it cannot be represented exactly), or
379   case ICK_Floating_Conversion:
380     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
381         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
382       // FromType is larger than ToType.
383       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
384 
385       // If it's value-dependent, we can't tell whether it's narrowing.
386       if (Initializer->isValueDependent())
387         return NK_Dependent_Narrowing;
388 
389       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
390         // Constant!
391         assert(ConstantValue.isFloat());
392         llvm::APFloat FloatVal = ConstantValue.getFloat();
393         // Convert the source value into the target type.
394         bool ignored;
395         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
396           Ctx.getFloatTypeSemantics(ToType),
397           llvm::APFloat::rmNearestTiesToEven, &ignored);
398         // If there was no overflow, the source value is within the range of
399         // values that can be represented.
400         if (ConvertStatus & llvm::APFloat::opOverflow) {
401           ConstantType = Initializer->getType();
402           return NK_Constant_Narrowing;
403         }
404       } else {
405         return NK_Variable_Narrowing;
406       }
407     }
408     return NK_Not_Narrowing;
409 
410   // -- from an integer type or unscoped enumeration type to an integer type
411   //    that cannot represent all the values of the original type, except where
412   //    the source is a constant expression and the actual value after
413   //    conversion will fit into the target type and will produce the original
414   //    value when converted back to the original type.
415   case ICK_Integral_Conversion:
416   IntegralConversion: {
417     assert(FromType->isIntegralOrUnscopedEnumerationType());
418     assert(ToType->isIntegralOrUnscopedEnumerationType());
419     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
420     const unsigned FromWidth = Ctx.getIntWidth(FromType);
421     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
422     const unsigned ToWidth = Ctx.getIntWidth(ToType);
423 
424     if (FromWidth > ToWidth ||
425         (FromWidth == ToWidth && FromSigned != ToSigned) ||
426         (FromSigned && !ToSigned)) {
427       // Not all values of FromType can be represented in ToType.
428       llvm::APSInt InitializerValue;
429       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
430 
431       // If it's value-dependent, we can't tell whether it's narrowing.
432       if (Initializer->isValueDependent())
433         return NK_Dependent_Narrowing;
434 
435       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
436         // Such conversions on variables are always narrowing.
437         return NK_Variable_Narrowing;
438       }
439       bool Narrowing = false;
440       if (FromWidth < ToWidth) {
441         // Negative -> unsigned is narrowing. Otherwise, more bits is never
442         // narrowing.
443         if (InitializerValue.isSigned() && InitializerValue.isNegative())
444           Narrowing = true;
445       } else {
446         // Add a bit to the InitializerValue so we don't have to worry about
447         // signed vs. unsigned comparisons.
448         InitializerValue = InitializerValue.extend(
449           InitializerValue.getBitWidth() + 1);
450         // Convert the initializer to and from the target width and signed-ness.
451         llvm::APSInt ConvertedValue = InitializerValue;
452         ConvertedValue = ConvertedValue.trunc(ToWidth);
453         ConvertedValue.setIsSigned(ToSigned);
454         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
455         ConvertedValue.setIsSigned(InitializerValue.isSigned());
456         // If the result is different, this was a narrowing conversion.
457         if (ConvertedValue != InitializerValue)
458           Narrowing = true;
459       }
460       if (Narrowing) {
461         ConstantType = Initializer->getType();
462         ConstantValue = APValue(InitializerValue);
463         return NK_Constant_Narrowing;
464       }
465     }
466     return NK_Not_Narrowing;
467   }
468 
469   default:
470     // Other kinds of conversions are not narrowings.
471     return NK_Not_Narrowing;
472   }
473 }
474 
475 /// dump - Print this standard conversion sequence to standard
476 /// error. Useful for debugging overloading issues.
477 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
478   raw_ostream &OS = llvm::errs();
479   bool PrintedSomething = false;
480   if (First != ICK_Identity) {
481     OS << GetImplicitConversionName(First);
482     PrintedSomething = true;
483   }
484 
485   if (Second != ICK_Identity) {
486     if (PrintedSomething) {
487       OS << " -> ";
488     }
489     OS << GetImplicitConversionName(Second);
490 
491     if (CopyConstructor) {
492       OS << " (by copy constructor)";
493     } else if (DirectBinding) {
494       OS << " (direct reference binding)";
495     } else if (ReferenceBinding) {
496       OS << " (reference binding)";
497     }
498     PrintedSomething = true;
499   }
500 
501   if (Third != ICK_Identity) {
502     if (PrintedSomething) {
503       OS << " -> ";
504     }
505     OS << GetImplicitConversionName(Third);
506     PrintedSomething = true;
507   }
508 
509   if (!PrintedSomething) {
510     OS << "No conversions required";
511   }
512 }
513 
514 /// dump - Print this user-defined conversion sequence to standard
515 /// error. Useful for debugging overloading issues.
516 void UserDefinedConversionSequence::dump() const {
517   raw_ostream &OS = llvm::errs();
518   if (Before.First || Before.Second || Before.Third) {
519     Before.dump();
520     OS << " -> ";
521   }
522   if (ConversionFunction)
523     OS << '\'' << *ConversionFunction << '\'';
524   else
525     OS << "aggregate initialization";
526   if (After.First || After.Second || After.Third) {
527     OS << " -> ";
528     After.dump();
529   }
530 }
531 
532 /// dump - Print this implicit conversion sequence to standard
533 /// error. Useful for debugging overloading issues.
534 void ImplicitConversionSequence::dump() const {
535   raw_ostream &OS = llvm::errs();
536   if (isStdInitializerListElement())
537     OS << "Worst std::initializer_list element conversion: ";
538   switch (ConversionKind) {
539   case StandardConversion:
540     OS << "Standard conversion: ";
541     Standard.dump();
542     break;
543   case UserDefinedConversion:
544     OS << "User-defined conversion: ";
545     UserDefined.dump();
546     break;
547   case EllipsisConversion:
548     OS << "Ellipsis conversion";
549     break;
550   case AmbiguousConversion:
551     OS << "Ambiguous conversion";
552     break;
553   case BadConversion:
554     OS << "Bad conversion";
555     break;
556   }
557 
558   OS << "\n";
559 }
560 
561 void AmbiguousConversionSequence::construct() {
562   new (&conversions()) ConversionSet();
563 }
564 
565 void AmbiguousConversionSequence::destruct() {
566   conversions().~ConversionSet();
567 }
568 
569 void
570 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
571   FromTypePtr = O.FromTypePtr;
572   ToTypePtr = O.ToTypePtr;
573   new (&conversions()) ConversionSet(O.conversions());
574 }
575 
576 namespace {
577   // Structure used by DeductionFailureInfo to store
578   // template argument information.
579   struct DFIArguments {
580     TemplateArgument FirstArg;
581     TemplateArgument SecondArg;
582   };
583   // Structure used by DeductionFailureInfo to store
584   // template parameter and template argument information.
585   struct DFIParamWithArguments : DFIArguments {
586     TemplateParameter Param;
587   };
588   // Structure used by DeductionFailureInfo to store template argument
589   // information and the index of the problematic call argument.
590   struct DFIDeducedMismatchArgs : DFIArguments {
591     TemplateArgumentList *TemplateArgs;
592     unsigned CallArgIndex;
593   };
594 }
595 
596 /// Convert from Sema's representation of template deduction information
597 /// to the form used in overload-candidate information.
598 DeductionFailureInfo
599 clang::MakeDeductionFailureInfo(ASTContext &Context,
600                                 Sema::TemplateDeductionResult TDK,
601                                 TemplateDeductionInfo &Info) {
602   DeductionFailureInfo Result;
603   Result.Result = static_cast<unsigned>(TDK);
604   Result.HasDiagnostic = false;
605   switch (TDK) {
606   case Sema::TDK_Invalid:
607   case Sema::TDK_InstantiationDepth:
608   case Sema::TDK_TooManyArguments:
609   case Sema::TDK_TooFewArguments:
610   case Sema::TDK_MiscellaneousDeductionFailure:
611   case Sema::TDK_CUDATargetMismatch:
612     Result.Data = nullptr;
613     break;
614 
615   case Sema::TDK_Incomplete:
616   case Sema::TDK_InvalidExplicitArguments:
617     Result.Data = Info.Param.getOpaqueValue();
618     break;
619 
620   case Sema::TDK_DeducedMismatch:
621   case Sema::TDK_DeducedMismatchNested: {
622     // FIXME: Should allocate from normal heap so that we can free this later.
623     auto *Saved = new (Context) DFIDeducedMismatchArgs;
624     Saved->FirstArg = Info.FirstArg;
625     Saved->SecondArg = Info.SecondArg;
626     Saved->TemplateArgs = Info.take();
627     Saved->CallArgIndex = Info.CallArgIndex;
628     Result.Data = Saved;
629     break;
630   }
631 
632   case Sema::TDK_NonDeducedMismatch: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     DFIArguments *Saved = new (Context) DFIArguments;
635     Saved->FirstArg = Info.FirstArg;
636     Saved->SecondArg = Info.SecondArg;
637     Result.Data = Saved;
638     break;
639   }
640 
641   case Sema::TDK_IncompletePack:
642     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
643   case Sema::TDK_Inconsistent:
644   case Sema::TDK_Underqualified: {
645     // FIXME: Should allocate from normal heap so that we can free this later.
646     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
647     Saved->Param = Info.Param;
648     Saved->FirstArg = Info.FirstArg;
649     Saved->SecondArg = Info.SecondArg;
650     Result.Data = Saved;
651     break;
652   }
653 
654   case Sema::TDK_SubstitutionFailure:
655     Result.Data = Info.take();
656     if (Info.hasSFINAEDiagnostic()) {
657       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
658           SourceLocation(), PartialDiagnostic::NullDiagnostic());
659       Info.takeSFINAEDiagnostic(*Diag);
660       Result.HasDiagnostic = true;
661     }
662     break;
663 
664   case Sema::TDK_Success:
665   case Sema::TDK_NonDependentConversionFailure:
666     llvm_unreachable("not a deduction failure");
667   }
668 
669   return Result;
670 }
671 
672 void DeductionFailureInfo::Destroy() {
673   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674   case Sema::TDK_Success:
675   case Sema::TDK_Invalid:
676   case Sema::TDK_InstantiationDepth:
677   case Sema::TDK_Incomplete:
678   case Sema::TDK_TooManyArguments:
679   case Sema::TDK_TooFewArguments:
680   case Sema::TDK_InvalidExplicitArguments:
681   case Sema::TDK_CUDATargetMismatch:
682   case Sema::TDK_NonDependentConversionFailure:
683     break;
684 
685   case Sema::TDK_IncompletePack:
686   case Sema::TDK_Inconsistent:
687   case Sema::TDK_Underqualified:
688   case Sema::TDK_DeducedMismatch:
689   case Sema::TDK_DeducedMismatchNested:
690   case Sema::TDK_NonDeducedMismatch:
691     // FIXME: Destroy the data?
692     Data = nullptr;
693     break;
694 
695   case Sema::TDK_SubstitutionFailure:
696     // FIXME: Destroy the template argument list?
697     Data = nullptr;
698     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
699       Diag->~PartialDiagnosticAt();
700       HasDiagnostic = false;
701     }
702     break;
703 
704   // Unhandled
705   case Sema::TDK_MiscellaneousDeductionFailure:
706     break;
707   }
708 }
709 
710 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
711   if (HasDiagnostic)
712     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
713   return nullptr;
714 }
715 
716 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
717   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718   case Sema::TDK_Success:
719   case Sema::TDK_Invalid:
720   case Sema::TDK_InstantiationDepth:
721   case Sema::TDK_TooManyArguments:
722   case Sema::TDK_TooFewArguments:
723   case Sema::TDK_SubstitutionFailure:
724   case Sema::TDK_DeducedMismatch:
725   case Sema::TDK_DeducedMismatchNested:
726   case Sema::TDK_NonDeducedMismatch:
727   case Sema::TDK_CUDATargetMismatch:
728   case Sema::TDK_NonDependentConversionFailure:
729     return TemplateParameter();
730 
731   case Sema::TDK_Incomplete:
732   case Sema::TDK_InvalidExplicitArguments:
733     return TemplateParameter::getFromOpaqueValue(Data);
734 
735   case Sema::TDK_IncompletePack:
736   case Sema::TDK_Inconsistent:
737   case Sema::TDK_Underqualified:
738     return static_cast<DFIParamWithArguments*>(Data)->Param;
739 
740   // Unhandled
741   case Sema::TDK_MiscellaneousDeductionFailure:
742     break;
743   }
744 
745   return TemplateParameter();
746 }
747 
748 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
749   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
750   case Sema::TDK_Success:
751   case Sema::TDK_Invalid:
752   case Sema::TDK_InstantiationDepth:
753   case Sema::TDK_TooManyArguments:
754   case Sema::TDK_TooFewArguments:
755   case Sema::TDK_Incomplete:
756   case Sema::TDK_IncompletePack:
757   case Sema::TDK_InvalidExplicitArguments:
758   case Sema::TDK_Inconsistent:
759   case Sema::TDK_Underqualified:
760   case Sema::TDK_NonDeducedMismatch:
761   case Sema::TDK_CUDATargetMismatch:
762   case Sema::TDK_NonDependentConversionFailure:
763     return nullptr;
764 
765   case Sema::TDK_DeducedMismatch:
766   case Sema::TDK_DeducedMismatchNested:
767     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
768 
769   case Sema::TDK_SubstitutionFailure:
770     return static_cast<TemplateArgumentList*>(Data);
771 
772   // Unhandled
773   case Sema::TDK_MiscellaneousDeductionFailure:
774     break;
775   }
776 
777   return nullptr;
778 }
779 
780 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
781   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782   case Sema::TDK_Success:
783   case Sema::TDK_Invalid:
784   case Sema::TDK_InstantiationDepth:
785   case Sema::TDK_Incomplete:
786   case Sema::TDK_TooManyArguments:
787   case Sema::TDK_TooFewArguments:
788   case Sema::TDK_InvalidExplicitArguments:
789   case Sema::TDK_SubstitutionFailure:
790   case Sema::TDK_CUDATargetMismatch:
791   case Sema::TDK_NonDependentConversionFailure:
792     return nullptr;
793 
794   case Sema::TDK_IncompletePack:
795   case Sema::TDK_Inconsistent:
796   case Sema::TDK_Underqualified:
797   case Sema::TDK_DeducedMismatch:
798   case Sema::TDK_DeducedMismatchNested:
799   case Sema::TDK_NonDeducedMismatch:
800     return &static_cast<DFIArguments*>(Data)->FirstArg;
801 
802   // Unhandled
803   case Sema::TDK_MiscellaneousDeductionFailure:
804     break;
805   }
806 
807   return nullptr;
808 }
809 
810 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
811   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
812   case Sema::TDK_Success:
813   case Sema::TDK_Invalid:
814   case Sema::TDK_InstantiationDepth:
815   case Sema::TDK_Incomplete:
816   case Sema::TDK_IncompletePack:
817   case Sema::TDK_TooManyArguments:
818   case Sema::TDK_TooFewArguments:
819   case Sema::TDK_InvalidExplicitArguments:
820   case Sema::TDK_SubstitutionFailure:
821   case Sema::TDK_CUDATargetMismatch:
822   case Sema::TDK_NonDependentConversionFailure:
823     return nullptr;
824 
825   case Sema::TDK_Inconsistent:
826   case Sema::TDK_Underqualified:
827   case Sema::TDK_DeducedMismatch:
828   case Sema::TDK_DeducedMismatchNested:
829   case Sema::TDK_NonDeducedMismatch:
830     return &static_cast<DFIArguments*>(Data)->SecondArg;
831 
832   // Unhandled
833   case Sema::TDK_MiscellaneousDeductionFailure:
834     break;
835   }
836 
837   return nullptr;
838 }
839 
840 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
841   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
842   case Sema::TDK_DeducedMismatch:
843   case Sema::TDK_DeducedMismatchNested:
844     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
845 
846   default:
847     return llvm::None;
848   }
849 }
850 
851 void OverloadCandidateSet::destroyCandidates() {
852   for (iterator i = begin(), e = end(); i != e; ++i) {
853     for (auto &C : i->Conversions)
854       C.~ImplicitConversionSequence();
855     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
856       i->DeductionFailure.Destroy();
857   }
858 }
859 
860 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
861   destroyCandidates();
862   SlabAllocator.Reset();
863   NumInlineBytesUsed = 0;
864   Candidates.clear();
865   Functions.clear();
866   Kind = CSK;
867 }
868 
869 namespace {
870   class UnbridgedCastsSet {
871     struct Entry {
872       Expr **Addr;
873       Expr *Saved;
874     };
875     SmallVector<Entry, 2> Entries;
876 
877   public:
878     void save(Sema &S, Expr *&E) {
879       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
880       Entry entry = { &E, E };
881       Entries.push_back(entry);
882       E = S.stripARCUnbridgedCast(E);
883     }
884 
885     void restore() {
886       for (SmallVectorImpl<Entry>::iterator
887              i = Entries.begin(), e = Entries.end(); i != e; ++i)
888         *i->Addr = i->Saved;
889     }
890   };
891 }
892 
893 /// checkPlaceholderForOverload - Do any interesting placeholder-like
894 /// preprocessing on the given expression.
895 ///
896 /// \param unbridgedCasts a collection to which to add unbridged casts;
897 ///   without this, they will be immediately diagnosed as errors
898 ///
899 /// Return true on unrecoverable error.
900 static bool
901 checkPlaceholderForOverload(Sema &S, Expr *&E,
902                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
903   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
904     // We can't handle overloaded expressions here because overload
905     // resolution might reasonably tweak them.
906     if (placeholder->getKind() == BuiltinType::Overload) return false;
907 
908     // If the context potentially accepts unbridged ARC casts, strip
909     // the unbridged cast and add it to the collection for later restoration.
910     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
911         unbridgedCasts) {
912       unbridgedCasts->save(S, E);
913       return false;
914     }
915 
916     // Go ahead and check everything else.
917     ExprResult result = S.CheckPlaceholderExpr(E);
918     if (result.isInvalid())
919       return true;
920 
921     E = result.get();
922     return false;
923   }
924 
925   // Nothing to do.
926   return false;
927 }
928 
929 /// checkArgPlaceholdersForOverload - Check a set of call operands for
930 /// placeholders.
931 static bool checkArgPlaceholdersForOverload(Sema &S,
932                                             MultiExprArg Args,
933                                             UnbridgedCastsSet &unbridged) {
934   for (unsigned i = 0, e = Args.size(); i != e; ++i)
935     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
936       return true;
937 
938   return false;
939 }
940 
941 /// Determine whether the given New declaration is an overload of the
942 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
943 /// New and Old cannot be overloaded, e.g., if New has the same signature as
944 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
945 /// functions (or function templates) at all. When it does return Ovl_Match or
946 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
947 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
948 /// declaration.
949 ///
950 /// Example: Given the following input:
951 ///
952 ///   void f(int, float); // #1
953 ///   void f(int, int); // #2
954 ///   int f(int, int); // #3
955 ///
956 /// When we process #1, there is no previous declaration of "f", so IsOverload
957 /// will not be used.
958 ///
959 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
960 /// the parameter types, we see that #1 and #2 are overloaded (since they have
961 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
962 /// unchanged.
963 ///
964 /// When we process #3, Old is an overload set containing #1 and #2. We compare
965 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
966 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
967 /// functions are not part of the signature), IsOverload returns Ovl_Match and
968 /// MatchedDecl will be set to point to the FunctionDecl for #2.
969 ///
970 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
971 /// by a using declaration. The rules for whether to hide shadow declarations
972 /// ignore some properties which otherwise figure into a function template's
973 /// signature.
974 Sema::OverloadKind
975 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
976                     NamedDecl *&Match, bool NewIsUsingDecl) {
977   for (LookupResult::iterator I = Old.begin(), E = Old.end();
978          I != E; ++I) {
979     NamedDecl *OldD = *I;
980 
981     bool OldIsUsingDecl = false;
982     if (isa<UsingShadowDecl>(OldD)) {
983       OldIsUsingDecl = true;
984 
985       // We can always introduce two using declarations into the same
986       // context, even if they have identical signatures.
987       if (NewIsUsingDecl) continue;
988 
989       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
990     }
991 
992     // A using-declaration does not conflict with another declaration
993     // if one of them is hidden.
994     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
995       continue;
996 
997     // If either declaration was introduced by a using declaration,
998     // we'll need to use slightly different rules for matching.
999     // Essentially, these rules are the normal rules, except that
1000     // function templates hide function templates with different
1001     // return types or template parameter lists.
1002     bool UseMemberUsingDeclRules =
1003       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1004       !New->getFriendObjectKind();
1005 
1006     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1007       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1008         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1009           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1010           continue;
1011         }
1012 
1013         if (!isa<FunctionTemplateDecl>(OldD) &&
1014             !shouldLinkPossiblyHiddenDecl(*I, New))
1015           continue;
1016 
1017         Match = *I;
1018         return Ovl_Match;
1019       }
1020 
1021       // Builtins that have custom typechecking or have a reference should
1022       // not be overloadable or redeclarable.
1023       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1024         Match = *I;
1025         return Ovl_NonFunction;
1026       }
1027     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1028       // We can overload with these, which can show up when doing
1029       // redeclaration checks for UsingDecls.
1030       assert(Old.getLookupKind() == LookupUsingDeclName);
1031     } else if (isa<TagDecl>(OldD)) {
1032       // We can always overload with tags by hiding them.
1033     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1034       // Optimistically assume that an unresolved using decl will
1035       // overload; if it doesn't, we'll have to diagnose during
1036       // template instantiation.
1037       //
1038       // Exception: if the scope is dependent and this is not a class
1039       // member, the using declaration can only introduce an enumerator.
1040       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1041         Match = *I;
1042         return Ovl_NonFunction;
1043       }
1044     } else {
1045       // (C++ 13p1):
1046       //   Only function declarations can be overloaded; object and type
1047       //   declarations cannot be overloaded.
1048       Match = *I;
1049       return Ovl_NonFunction;
1050     }
1051   }
1052 
1053   // C++ [temp.friend]p1:
1054   //   For a friend function declaration that is not a template declaration:
1055   //    -- if the name of the friend is a qualified or unqualified template-id,
1056   //       [...], otherwise
1057   //    -- if the name of the friend is a qualified-id and a matching
1058   //       non-template function is found in the specified class or namespace,
1059   //       the friend declaration refers to that function, otherwise,
1060   //    -- if the name of the friend is a qualified-id and a matching function
1061   //       template is found in the specified class or namespace, the friend
1062   //       declaration refers to the deduced specialization of that function
1063   //       template, otherwise
1064   //    -- the name shall be an unqualified-id [...]
1065   // If we get here for a qualified friend declaration, we've just reached the
1066   // third bullet. If the type of the friend is dependent, skip this lookup
1067   // until instantiation.
1068   if (New->getFriendObjectKind() && New->getQualifier() &&
1069       !New->getDescribedFunctionTemplate() &&
1070       !New->getDependentSpecializationInfo() &&
1071       !New->getType()->isDependentType()) {
1072     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1073     TemplateSpecResult.addAllDecls(Old);
1074     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1075                                             /*QualifiedFriend*/true)) {
1076       New->setInvalidDecl();
1077       return Ovl_Overload;
1078     }
1079 
1080     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1081     return Ovl_Match;
1082   }
1083 
1084   return Ovl_Overload;
1085 }
1086 
1087 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1088                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1089   // C++ [basic.start.main]p2: This function shall not be overloaded.
1090   if (New->isMain())
1091     return false;
1092 
1093   // MSVCRT user defined entry points cannot be overloaded.
1094   if (New->isMSVCRTEntryPoint())
1095     return false;
1096 
1097   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1098   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1099 
1100   // C++ [temp.fct]p2:
1101   //   A function template can be overloaded with other function templates
1102   //   and with normal (non-template) functions.
1103   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1104     return true;
1105 
1106   // Is the function New an overload of the function Old?
1107   QualType OldQType = Context.getCanonicalType(Old->getType());
1108   QualType NewQType = Context.getCanonicalType(New->getType());
1109 
1110   // Compare the signatures (C++ 1.3.10) of the two functions to
1111   // determine whether they are overloads. If we find any mismatch
1112   // in the signature, they are overloads.
1113 
1114   // If either of these functions is a K&R-style function (no
1115   // prototype), then we consider them to have matching signatures.
1116   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1117       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1118     return false;
1119 
1120   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1121   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1122 
1123   // The signature of a function includes the types of its
1124   // parameters (C++ 1.3.10), which includes the presence or absence
1125   // of the ellipsis; see C++ DR 357).
1126   if (OldQType != NewQType &&
1127       (OldType->getNumParams() != NewType->getNumParams() ||
1128        OldType->isVariadic() != NewType->isVariadic() ||
1129        !FunctionParamTypesAreEqual(OldType, NewType)))
1130     return true;
1131 
1132   // C++ [temp.over.link]p4:
1133   //   The signature of a function template consists of its function
1134   //   signature, its return type and its template parameter list. The names
1135   //   of the template parameters are significant only for establishing the
1136   //   relationship between the template parameters and the rest of the
1137   //   signature.
1138   //
1139   // We check the return type and template parameter lists for function
1140   // templates first; the remaining checks follow.
1141   //
1142   // However, we don't consider either of these when deciding whether
1143   // a member introduced by a shadow declaration is hidden.
1144   if (!UseMemberUsingDeclRules && NewTemplate &&
1145       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1146                                        OldTemplate->getTemplateParameters(),
1147                                        false, TPL_TemplateMatch) ||
1148        !Context.hasSameType(Old->getDeclaredReturnType(),
1149                             New->getDeclaredReturnType())))
1150     return true;
1151 
1152   // If the function is a class member, its signature includes the
1153   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1154   //
1155   // As part of this, also check whether one of the member functions
1156   // is static, in which case they are not overloads (C++
1157   // 13.1p2). While not part of the definition of the signature,
1158   // this check is important to determine whether these functions
1159   // can be overloaded.
1160   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1161   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1162   if (OldMethod && NewMethod &&
1163       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1164     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1165       if (!UseMemberUsingDeclRules &&
1166           (OldMethod->getRefQualifier() == RQ_None ||
1167            NewMethod->getRefQualifier() == RQ_None)) {
1168         // C++0x [over.load]p2:
1169         //   - Member function declarations with the same name and the same
1170         //     parameter-type-list as well as member function template
1171         //     declarations with the same name, the same parameter-type-list, and
1172         //     the same template parameter lists cannot be overloaded if any of
1173         //     them, but not all, have a ref-qualifier (8.3.5).
1174         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1175           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1176         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1177       }
1178       return true;
1179     }
1180 
1181     // We may not have applied the implicit const for a constexpr member
1182     // function yet (because we haven't yet resolved whether this is a static
1183     // or non-static member function). Add it now, on the assumption that this
1184     // is a redeclaration of OldMethod.
1185     auto OldQuals = OldMethod->getMethodQualifiers();
1186     auto NewQuals = NewMethod->getMethodQualifiers();
1187     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1188         !isa<CXXConstructorDecl>(NewMethod))
1189       NewQuals.addConst();
1190     // We do not allow overloading based off of '__restrict'.
1191     OldQuals.removeRestrict();
1192     NewQuals.removeRestrict();
1193     if (OldQuals != NewQuals)
1194       return true;
1195   }
1196 
1197   // Though pass_object_size is placed on parameters and takes an argument, we
1198   // consider it to be a function-level modifier for the sake of function
1199   // identity. Either the function has one or more parameters with
1200   // pass_object_size or it doesn't.
1201   if (functionHasPassObjectSizeParams(New) !=
1202       functionHasPassObjectSizeParams(Old))
1203     return true;
1204 
1205   // enable_if attributes are an order-sensitive part of the signature.
1206   for (specific_attr_iterator<EnableIfAttr>
1207          NewI = New->specific_attr_begin<EnableIfAttr>(),
1208          NewE = New->specific_attr_end<EnableIfAttr>(),
1209          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1210          OldE = Old->specific_attr_end<EnableIfAttr>();
1211        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1212     if (NewI == NewE || OldI == OldE)
1213       return true;
1214     llvm::FoldingSetNodeID NewID, OldID;
1215     NewI->getCond()->Profile(NewID, Context, true);
1216     OldI->getCond()->Profile(OldID, Context, true);
1217     if (NewID != OldID)
1218       return true;
1219   }
1220 
1221   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1222     // Don't allow overloading of destructors.  (In theory we could, but it
1223     // would be a giant change to clang.)
1224     if (isa<CXXDestructorDecl>(New))
1225       return false;
1226 
1227     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1228                        OldTarget = IdentifyCUDATarget(Old);
1229     if (NewTarget == CFT_InvalidTarget)
1230       return false;
1231 
1232     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1233 
1234     // Allow overloading of functions with same signature and different CUDA
1235     // target attributes.
1236     return NewTarget != OldTarget;
1237   }
1238 
1239   // The signatures match; this is not an overload.
1240   return false;
1241 }
1242 
1243 /// Tries a user-defined conversion from From to ToType.
1244 ///
1245 /// Produces an implicit conversion sequence for when a standard conversion
1246 /// is not an option. See TryImplicitConversion for more information.
1247 static ImplicitConversionSequence
1248 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1249                          bool SuppressUserConversions,
1250                          bool AllowExplicit,
1251                          bool InOverloadResolution,
1252                          bool CStyle,
1253                          bool AllowObjCWritebackConversion,
1254                          bool AllowObjCConversionOnExplicit) {
1255   ImplicitConversionSequence ICS;
1256 
1257   if (SuppressUserConversions) {
1258     // We're not in the case above, so there is no conversion that
1259     // we can perform.
1260     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1261     return ICS;
1262   }
1263 
1264   // Attempt user-defined conversion.
1265   OverloadCandidateSet Conversions(From->getExprLoc(),
1266                                    OverloadCandidateSet::CSK_Normal);
1267   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1268                                   Conversions, AllowExplicit,
1269                                   AllowObjCConversionOnExplicit)) {
1270   case OR_Success:
1271   case OR_Deleted:
1272     ICS.setUserDefined();
1273     // C++ [over.ics.user]p4:
1274     //   A conversion of an expression of class type to the same class
1275     //   type is given Exact Match rank, and a conversion of an
1276     //   expression of class type to a base class of that type is
1277     //   given Conversion rank, in spite of the fact that a copy
1278     //   constructor (i.e., a user-defined conversion function) is
1279     //   called for those cases.
1280     if (CXXConstructorDecl *Constructor
1281           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1282       QualType FromCanon
1283         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1284       QualType ToCanon
1285         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1286       if (Constructor->isCopyConstructor() &&
1287           (FromCanon == ToCanon ||
1288            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1289         // Turn this into a "standard" conversion sequence, so that it
1290         // gets ranked with standard conversion sequences.
1291         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1292         ICS.setStandard();
1293         ICS.Standard.setAsIdentityConversion();
1294         ICS.Standard.setFromType(From->getType());
1295         ICS.Standard.setAllToTypes(ToType);
1296         ICS.Standard.CopyConstructor = Constructor;
1297         ICS.Standard.FoundCopyConstructor = Found;
1298         if (ToCanon != FromCanon)
1299           ICS.Standard.Second = ICK_Derived_To_Base;
1300       }
1301     }
1302     break;
1303 
1304   case OR_Ambiguous:
1305     ICS.setAmbiguous();
1306     ICS.Ambiguous.setFromType(From->getType());
1307     ICS.Ambiguous.setToType(ToType);
1308     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1309          Cand != Conversions.end(); ++Cand)
1310       if (Cand->Viable)
1311         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1312     break;
1313 
1314     // Fall through.
1315   case OR_No_Viable_Function:
1316     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1317     break;
1318   }
1319 
1320   return ICS;
1321 }
1322 
1323 /// TryImplicitConversion - Attempt to perform an implicit conversion
1324 /// from the given expression (Expr) to the given type (ToType). This
1325 /// function returns an implicit conversion sequence that can be used
1326 /// to perform the initialization. Given
1327 ///
1328 ///   void f(float f);
1329 ///   void g(int i) { f(i); }
1330 ///
1331 /// this routine would produce an implicit conversion sequence to
1332 /// describe the initialization of f from i, which will be a standard
1333 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1334 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1335 //
1336 /// Note that this routine only determines how the conversion can be
1337 /// performed; it does not actually perform the conversion. As such,
1338 /// it will not produce any diagnostics if no conversion is available,
1339 /// but will instead return an implicit conversion sequence of kind
1340 /// "BadConversion".
1341 ///
1342 /// If @p SuppressUserConversions, then user-defined conversions are
1343 /// not permitted.
1344 /// If @p AllowExplicit, then explicit user-defined conversions are
1345 /// permitted.
1346 ///
1347 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1348 /// writeback conversion, which allows __autoreleasing id* parameters to
1349 /// be initialized with __strong id* or __weak id* arguments.
1350 static ImplicitConversionSequence
1351 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1352                       bool SuppressUserConversions,
1353                       bool AllowExplicit,
1354                       bool InOverloadResolution,
1355                       bool CStyle,
1356                       bool AllowObjCWritebackConversion,
1357                       bool AllowObjCConversionOnExplicit) {
1358   ImplicitConversionSequence ICS;
1359   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1360                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1361     ICS.setStandard();
1362     return ICS;
1363   }
1364 
1365   if (!S.getLangOpts().CPlusPlus) {
1366     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1367     return ICS;
1368   }
1369 
1370   // C++ [over.ics.user]p4:
1371   //   A conversion of an expression of class type to the same class
1372   //   type is given Exact Match rank, and a conversion of an
1373   //   expression of class type to a base class of that type is
1374   //   given Conversion rank, in spite of the fact that a copy/move
1375   //   constructor (i.e., a user-defined conversion function) is
1376   //   called for those cases.
1377   QualType FromType = From->getType();
1378   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1379       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1380        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1381     ICS.setStandard();
1382     ICS.Standard.setAsIdentityConversion();
1383     ICS.Standard.setFromType(FromType);
1384     ICS.Standard.setAllToTypes(ToType);
1385 
1386     // We don't actually check at this point whether there is a valid
1387     // copy/move constructor, since overloading just assumes that it
1388     // exists. When we actually perform initialization, we'll find the
1389     // appropriate constructor to copy the returned object, if needed.
1390     ICS.Standard.CopyConstructor = nullptr;
1391 
1392     // Determine whether this is considered a derived-to-base conversion.
1393     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1394       ICS.Standard.Second = ICK_Derived_To_Base;
1395 
1396     return ICS;
1397   }
1398 
1399   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1400                                   AllowExplicit, InOverloadResolution, CStyle,
1401                                   AllowObjCWritebackConversion,
1402                                   AllowObjCConversionOnExplicit);
1403 }
1404 
1405 ImplicitConversionSequence
1406 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1407                             bool SuppressUserConversions,
1408                             bool AllowExplicit,
1409                             bool InOverloadResolution,
1410                             bool CStyle,
1411                             bool AllowObjCWritebackConversion) {
1412   return ::TryImplicitConversion(*this, From, ToType,
1413                                  SuppressUserConversions, AllowExplicit,
1414                                  InOverloadResolution, CStyle,
1415                                  AllowObjCWritebackConversion,
1416                                  /*AllowObjCConversionOnExplicit=*/false);
1417 }
1418 
1419 /// PerformImplicitConversion - Perform an implicit conversion of the
1420 /// expression From to the type ToType. Returns the
1421 /// converted expression. Flavor is the kind of conversion we're
1422 /// performing, used in the error message. If @p AllowExplicit,
1423 /// explicit user-defined conversions are permitted.
1424 ExprResult
1425 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1426                                 AssignmentAction Action, bool AllowExplicit) {
1427   ImplicitConversionSequence ICS;
1428   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1429 }
1430 
1431 ExprResult
1432 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1433                                 AssignmentAction Action, bool AllowExplicit,
1434                                 ImplicitConversionSequence& ICS) {
1435   if (checkPlaceholderForOverload(*this, From))
1436     return ExprError();
1437 
1438   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1439   bool AllowObjCWritebackConversion
1440     = getLangOpts().ObjCAutoRefCount &&
1441       (Action == AA_Passing || Action == AA_Sending);
1442   if (getLangOpts().ObjC)
1443     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1444                                       From->getType(), From);
1445   ICS = ::TryImplicitConversion(*this, From, ToType,
1446                                 /*SuppressUserConversions=*/false,
1447                                 AllowExplicit,
1448                                 /*InOverloadResolution=*/false,
1449                                 /*CStyle=*/false,
1450                                 AllowObjCWritebackConversion,
1451                                 /*AllowObjCConversionOnExplicit=*/false);
1452   return PerformImplicitConversion(From, ToType, ICS, Action);
1453 }
1454 
1455 /// Determine whether the conversion from FromType to ToType is a valid
1456 /// conversion that strips "noexcept" or "noreturn" off the nested function
1457 /// type.
1458 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1459                                 QualType &ResultTy) {
1460   if (Context.hasSameUnqualifiedType(FromType, ToType))
1461     return false;
1462 
1463   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1464   //                    or F(t noexcept) -> F(t)
1465   // where F adds one of the following at most once:
1466   //   - a pointer
1467   //   - a member pointer
1468   //   - a block pointer
1469   // Changes here need matching changes in FindCompositePointerType.
1470   CanQualType CanTo = Context.getCanonicalType(ToType);
1471   CanQualType CanFrom = Context.getCanonicalType(FromType);
1472   Type::TypeClass TyClass = CanTo->getTypeClass();
1473   if (TyClass != CanFrom->getTypeClass()) return false;
1474   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1475     if (TyClass == Type::Pointer) {
1476       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1477       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1478     } else if (TyClass == Type::BlockPointer) {
1479       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1480       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1481     } else if (TyClass == Type::MemberPointer) {
1482       auto ToMPT = CanTo.castAs<MemberPointerType>();
1483       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1484       // A function pointer conversion cannot change the class of the function.
1485       if (ToMPT->getClass() != FromMPT->getClass())
1486         return false;
1487       CanTo = ToMPT->getPointeeType();
1488       CanFrom = FromMPT->getPointeeType();
1489     } else {
1490       return false;
1491     }
1492 
1493     TyClass = CanTo->getTypeClass();
1494     if (TyClass != CanFrom->getTypeClass()) return false;
1495     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1496       return false;
1497   }
1498 
1499   const auto *FromFn = cast<FunctionType>(CanFrom);
1500   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1501 
1502   const auto *ToFn = cast<FunctionType>(CanTo);
1503   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1504 
1505   bool Changed = false;
1506 
1507   // Drop 'noreturn' if not present in target type.
1508   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1509     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1510     Changed = true;
1511   }
1512 
1513   // Drop 'noexcept' if not present in target type.
1514   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1515     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1516     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1517       FromFn = cast<FunctionType>(
1518           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1519                                                    EST_None)
1520                  .getTypePtr());
1521       Changed = true;
1522     }
1523 
1524     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1525     // only if the ExtParameterInfo lists of the two function prototypes can be
1526     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1527     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1528     bool CanUseToFPT, CanUseFromFPT;
1529     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1530                                       CanUseFromFPT, NewParamInfos) &&
1531         CanUseToFPT && !CanUseFromFPT) {
1532       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1533       ExtInfo.ExtParameterInfos =
1534           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1535       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1536                                             FromFPT->getParamTypes(), ExtInfo);
1537       FromFn = QT->getAs<FunctionType>();
1538       Changed = true;
1539     }
1540   }
1541 
1542   if (!Changed)
1543     return false;
1544 
1545   assert(QualType(FromFn, 0).isCanonical());
1546   if (QualType(FromFn, 0) != CanTo) return false;
1547 
1548   ResultTy = ToType;
1549   return true;
1550 }
1551 
1552 /// Determine whether the conversion from FromType to ToType is a valid
1553 /// vector conversion.
1554 ///
1555 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1556 /// conversion.
1557 static bool IsVectorConversion(Sema &S, QualType FromType,
1558                                QualType ToType, ImplicitConversionKind &ICK) {
1559   // We need at least one of these types to be a vector type to have a vector
1560   // conversion.
1561   if (!ToType->isVectorType() && !FromType->isVectorType())
1562     return false;
1563 
1564   // Identical types require no conversions.
1565   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1566     return false;
1567 
1568   // There are no conversions between extended vector types, only identity.
1569   if (ToType->isExtVectorType()) {
1570     // There are no conversions between extended vector types other than the
1571     // identity conversion.
1572     if (FromType->isExtVectorType())
1573       return false;
1574 
1575     // Vector splat from any arithmetic type to a vector.
1576     if (FromType->isArithmeticType()) {
1577       ICK = ICK_Vector_Splat;
1578       return true;
1579     }
1580   }
1581 
1582   // We can perform the conversion between vector types in the following cases:
1583   // 1)vector types are equivalent AltiVec and GCC vector types
1584   // 2)lax vector conversions are permitted and the vector types are of the
1585   //   same size
1586   if (ToType->isVectorType() && FromType->isVectorType()) {
1587     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1588         S.isLaxVectorConversion(FromType, ToType)) {
1589       ICK = ICK_Vector_Conversion;
1590       return true;
1591     }
1592   }
1593 
1594   return false;
1595 }
1596 
1597 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1598                                 bool InOverloadResolution,
1599                                 StandardConversionSequence &SCS,
1600                                 bool CStyle);
1601 
1602 /// IsStandardConversion - Determines whether there is a standard
1603 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1604 /// expression From to the type ToType. Standard conversion sequences
1605 /// only consider non-class types; for conversions that involve class
1606 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1607 /// contain the standard conversion sequence required to perform this
1608 /// conversion and this routine will return true. Otherwise, this
1609 /// routine will return false and the value of SCS is unspecified.
1610 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1611                                  bool InOverloadResolution,
1612                                  StandardConversionSequence &SCS,
1613                                  bool CStyle,
1614                                  bool AllowObjCWritebackConversion) {
1615   QualType FromType = From->getType();
1616 
1617   // Standard conversions (C++ [conv])
1618   SCS.setAsIdentityConversion();
1619   SCS.IncompatibleObjC = false;
1620   SCS.setFromType(FromType);
1621   SCS.CopyConstructor = nullptr;
1622 
1623   // There are no standard conversions for class types in C++, so
1624   // abort early. When overloading in C, however, we do permit them.
1625   if (S.getLangOpts().CPlusPlus &&
1626       (FromType->isRecordType() || ToType->isRecordType()))
1627     return false;
1628 
1629   // The first conversion can be an lvalue-to-rvalue conversion,
1630   // array-to-pointer conversion, or function-to-pointer conversion
1631   // (C++ 4p1).
1632 
1633   if (FromType == S.Context.OverloadTy) {
1634     DeclAccessPair AccessPair;
1635     if (FunctionDecl *Fn
1636           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1637                                                  AccessPair)) {
1638       // We were able to resolve the address of the overloaded function,
1639       // so we can convert to the type of that function.
1640       FromType = Fn->getType();
1641       SCS.setFromType(FromType);
1642 
1643       // we can sometimes resolve &foo<int> regardless of ToType, so check
1644       // if the type matches (identity) or we are converting to bool
1645       if (!S.Context.hasSameUnqualifiedType(
1646                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1647         QualType resultTy;
1648         // if the function type matches except for [[noreturn]], it's ok
1649         if (!S.IsFunctionConversion(FromType,
1650               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1651           // otherwise, only a boolean conversion is standard
1652           if (!ToType->isBooleanType())
1653             return false;
1654       }
1655 
1656       // Check if the "from" expression is taking the address of an overloaded
1657       // function and recompute the FromType accordingly. Take advantage of the
1658       // fact that non-static member functions *must* have such an address-of
1659       // expression.
1660       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1661       if (Method && !Method->isStatic()) {
1662         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1663                "Non-unary operator on non-static member address");
1664         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1665                == UO_AddrOf &&
1666                "Non-address-of operator on non-static member address");
1667         const Type *ClassType
1668           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1669         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1670       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1671         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1672                UO_AddrOf &&
1673                "Non-address-of operator for overloaded function expression");
1674         FromType = S.Context.getPointerType(FromType);
1675       }
1676 
1677       // Check that we've computed the proper type after overload resolution.
1678       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1679       // be calling it from within an NDEBUG block.
1680       assert(S.Context.hasSameType(
1681         FromType,
1682         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1683     } else {
1684       return false;
1685     }
1686   }
1687   // Lvalue-to-rvalue conversion (C++11 4.1):
1688   //   A glvalue (3.10) of a non-function, non-array type T can
1689   //   be converted to a prvalue.
1690   bool argIsLValue = From->isGLValue();
1691   if (argIsLValue &&
1692       !FromType->isFunctionType() && !FromType->isArrayType() &&
1693       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1694     SCS.First = ICK_Lvalue_To_Rvalue;
1695 
1696     // C11 6.3.2.1p2:
1697     //   ... if the lvalue has atomic type, the value has the non-atomic version
1698     //   of the type of the lvalue ...
1699     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1700       FromType = Atomic->getValueType();
1701 
1702     // If T is a non-class type, the type of the rvalue is the
1703     // cv-unqualified version of T. Otherwise, the type of the rvalue
1704     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1705     // just strip the qualifiers because they don't matter.
1706     FromType = FromType.getUnqualifiedType();
1707   } else if (FromType->isArrayType()) {
1708     // Array-to-pointer conversion (C++ 4.2)
1709     SCS.First = ICK_Array_To_Pointer;
1710 
1711     // An lvalue or rvalue of type "array of N T" or "array of unknown
1712     // bound of T" can be converted to an rvalue of type "pointer to
1713     // T" (C++ 4.2p1).
1714     FromType = S.Context.getArrayDecayedType(FromType);
1715 
1716     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1717       // This conversion is deprecated in C++03 (D.4)
1718       SCS.DeprecatedStringLiteralToCharPtr = true;
1719 
1720       // For the purpose of ranking in overload resolution
1721       // (13.3.3.1.1), this conversion is considered an
1722       // array-to-pointer conversion followed by a qualification
1723       // conversion (4.4). (C++ 4.2p2)
1724       SCS.Second = ICK_Identity;
1725       SCS.Third = ICK_Qualification;
1726       SCS.QualificationIncludesObjCLifetime = false;
1727       SCS.setAllToTypes(FromType);
1728       return true;
1729     }
1730   } else if (FromType->isFunctionType() && argIsLValue) {
1731     // Function-to-pointer conversion (C++ 4.3).
1732     SCS.First = ICK_Function_To_Pointer;
1733 
1734     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1735       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1736         if (!S.checkAddressOfFunctionIsAvailable(FD))
1737           return false;
1738 
1739     // An lvalue of function type T can be converted to an rvalue of
1740     // type "pointer to T." The result is a pointer to the
1741     // function. (C++ 4.3p1).
1742     FromType = S.Context.getPointerType(FromType);
1743   } else {
1744     // We don't require any conversions for the first step.
1745     SCS.First = ICK_Identity;
1746   }
1747   SCS.setToType(0, FromType);
1748 
1749   // The second conversion can be an integral promotion, floating
1750   // point promotion, integral conversion, floating point conversion,
1751   // floating-integral conversion, pointer conversion,
1752   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1753   // For overloading in C, this can also be a "compatible-type"
1754   // conversion.
1755   bool IncompatibleObjC = false;
1756   ImplicitConversionKind SecondICK = ICK_Identity;
1757   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1758     // The unqualified versions of the types are the same: there's no
1759     // conversion to do.
1760     SCS.Second = ICK_Identity;
1761   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1762     // Integral promotion (C++ 4.5).
1763     SCS.Second = ICK_Integral_Promotion;
1764     FromType = ToType.getUnqualifiedType();
1765   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1766     // Floating point promotion (C++ 4.6).
1767     SCS.Second = ICK_Floating_Promotion;
1768     FromType = ToType.getUnqualifiedType();
1769   } else if (S.IsComplexPromotion(FromType, ToType)) {
1770     // Complex promotion (Clang extension)
1771     SCS.Second = ICK_Complex_Promotion;
1772     FromType = ToType.getUnqualifiedType();
1773   } else if (ToType->isBooleanType() &&
1774              (FromType->isArithmeticType() ||
1775               FromType->isAnyPointerType() ||
1776               FromType->isBlockPointerType() ||
1777               FromType->isMemberPointerType() ||
1778               FromType->isNullPtrType())) {
1779     // Boolean conversions (C++ 4.12).
1780     SCS.Second = ICK_Boolean_Conversion;
1781     FromType = S.Context.BoolTy;
1782   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1783              ToType->isIntegralType(S.Context)) {
1784     // Integral conversions (C++ 4.7).
1785     SCS.Second = ICK_Integral_Conversion;
1786     FromType = ToType.getUnqualifiedType();
1787   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1788     // Complex conversions (C99 6.3.1.6)
1789     SCS.Second = ICK_Complex_Conversion;
1790     FromType = ToType.getUnqualifiedType();
1791   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1792              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1793     // Complex-real conversions (C99 6.3.1.7)
1794     SCS.Second = ICK_Complex_Real;
1795     FromType = ToType.getUnqualifiedType();
1796   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1797     // FIXME: disable conversions between long double and __float128 if
1798     // their representation is different until there is back end support
1799     // We of course allow this conversion if long double is really double.
1800     if (&S.Context.getFloatTypeSemantics(FromType) !=
1801         &S.Context.getFloatTypeSemantics(ToType)) {
1802       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1803                                     ToType == S.Context.LongDoubleTy) ||
1804                                    (FromType == S.Context.LongDoubleTy &&
1805                                     ToType == S.Context.Float128Ty));
1806       if (Float128AndLongDouble &&
1807           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1808            &llvm::APFloat::PPCDoubleDouble()))
1809         return false;
1810     }
1811     // Floating point conversions (C++ 4.8).
1812     SCS.Second = ICK_Floating_Conversion;
1813     FromType = ToType.getUnqualifiedType();
1814   } else if ((FromType->isRealFloatingType() &&
1815               ToType->isIntegralType(S.Context)) ||
1816              (FromType->isIntegralOrUnscopedEnumerationType() &&
1817               ToType->isRealFloatingType())) {
1818     // Floating-integral conversions (C++ 4.9).
1819     SCS.Second = ICK_Floating_Integral;
1820     FromType = ToType.getUnqualifiedType();
1821   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1822     SCS.Second = ICK_Block_Pointer_Conversion;
1823   } else if (AllowObjCWritebackConversion &&
1824              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1825     SCS.Second = ICK_Writeback_Conversion;
1826   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1827                                    FromType, IncompatibleObjC)) {
1828     // Pointer conversions (C++ 4.10).
1829     SCS.Second = ICK_Pointer_Conversion;
1830     SCS.IncompatibleObjC = IncompatibleObjC;
1831     FromType = FromType.getUnqualifiedType();
1832   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1833                                          InOverloadResolution, FromType)) {
1834     // Pointer to member conversions (4.11).
1835     SCS.Second = ICK_Pointer_Member;
1836   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1837     SCS.Second = SecondICK;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (!S.getLangOpts().CPlusPlus &&
1840              S.Context.typesAreCompatible(ToType, FromType)) {
1841     // Compatible conversions (Clang extension for C function overloading)
1842     SCS.Second = ICK_Compatible_Conversion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1845                                              InOverloadResolution,
1846                                              SCS, CStyle)) {
1847     SCS.Second = ICK_TransparentUnionConversion;
1848     FromType = ToType;
1849   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1850                                  CStyle)) {
1851     // tryAtomicConversion has updated the standard conversion sequence
1852     // appropriately.
1853     return true;
1854   } else if (ToType->isEventT() &&
1855              From->isIntegerConstantExpr(S.getASTContext()) &&
1856              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1857     SCS.Second = ICK_Zero_Event_Conversion;
1858     FromType = ToType;
1859   } else if (ToType->isQueueT() &&
1860              From->isIntegerConstantExpr(S.getASTContext()) &&
1861              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1862     SCS.Second = ICK_Zero_Queue_Conversion;
1863     FromType = ToType;
1864   } else if (ToType->isSamplerT() &&
1865              From->isIntegerConstantExpr(S.getASTContext())) {
1866     SCS.Second = ICK_Compatible_Conversion;
1867     FromType = ToType;
1868   } else {
1869     // No second conversion required.
1870     SCS.Second = ICK_Identity;
1871   }
1872   SCS.setToType(1, FromType);
1873 
1874   // The third conversion can be a function pointer conversion or a
1875   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1876   bool ObjCLifetimeConversion;
1877   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1878     // Function pointer conversions (removing 'noexcept') including removal of
1879     // 'noreturn' (Clang extension).
1880     SCS.Third = ICK_Function_Conversion;
1881   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1882                                          ObjCLifetimeConversion)) {
1883     SCS.Third = ICK_Qualification;
1884     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1885     FromType = ToType;
1886   } else {
1887     // No conversion required
1888     SCS.Third = ICK_Identity;
1889   }
1890 
1891   // C++ [over.best.ics]p6:
1892   //   [...] Any difference in top-level cv-qualification is
1893   //   subsumed by the initialization itself and does not constitute
1894   //   a conversion. [...]
1895   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1896   QualType CanonTo = S.Context.getCanonicalType(ToType);
1897   if (CanonFrom.getLocalUnqualifiedType()
1898                                      == CanonTo.getLocalUnqualifiedType() &&
1899       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1900     FromType = ToType;
1901     CanonFrom = CanonTo;
1902   }
1903 
1904   SCS.setToType(2, FromType);
1905 
1906   if (CanonFrom == CanonTo)
1907     return true;
1908 
1909   // If we have not converted the argument type to the parameter type,
1910   // this is a bad conversion sequence, unless we're resolving an overload in C.
1911   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1912     return false;
1913 
1914   ExprResult ER = ExprResult{From};
1915   Sema::AssignConvertType Conv =
1916       S.CheckSingleAssignmentConstraints(ToType, ER,
1917                                          /*Diagnose=*/false,
1918                                          /*DiagnoseCFAudited=*/false,
1919                                          /*ConvertRHS=*/false);
1920   ImplicitConversionKind SecondConv;
1921   switch (Conv) {
1922   case Sema::Compatible:
1923     SecondConv = ICK_C_Only_Conversion;
1924     break;
1925   // For our purposes, discarding qualifiers is just as bad as using an
1926   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1927   // qualifiers, as well.
1928   case Sema::CompatiblePointerDiscardsQualifiers:
1929   case Sema::IncompatiblePointer:
1930   case Sema::IncompatiblePointerSign:
1931     SecondConv = ICK_Incompatible_Pointer_Conversion;
1932     break;
1933   default:
1934     return false;
1935   }
1936 
1937   // First can only be an lvalue conversion, so we pretend that this was the
1938   // second conversion. First should already be valid from earlier in the
1939   // function.
1940   SCS.Second = SecondConv;
1941   SCS.setToType(1, ToType);
1942 
1943   // Third is Identity, because Second should rank us worse than any other
1944   // conversion. This could also be ICK_Qualification, but it's simpler to just
1945   // lump everything in with the second conversion, and we don't gain anything
1946   // from making this ICK_Qualification.
1947   SCS.Third = ICK_Identity;
1948   SCS.setToType(2, ToType);
1949   return true;
1950 }
1951 
1952 static bool
1953 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1954                                      QualType &ToType,
1955                                      bool InOverloadResolution,
1956                                      StandardConversionSequence &SCS,
1957                                      bool CStyle) {
1958 
1959   const RecordType *UT = ToType->getAsUnionType();
1960   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1961     return false;
1962   // The field to initialize within the transparent union.
1963   RecordDecl *UD = UT->getDecl();
1964   // It's compatible if the expression matches any of the fields.
1965   for (const auto *it : UD->fields()) {
1966     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1967                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
1968       ToType = it->getType();
1969       return true;
1970     }
1971   }
1972   return false;
1973 }
1974 
1975 /// IsIntegralPromotion - Determines whether the conversion from the
1976 /// expression From (whose potentially-adjusted type is FromType) to
1977 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1978 /// sets PromotedType to the promoted type.
1979 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1980   const BuiltinType *To = ToType->getAs<BuiltinType>();
1981   // All integers are built-in.
1982   if (!To) {
1983     return false;
1984   }
1985 
1986   // An rvalue of type char, signed char, unsigned char, short int, or
1987   // unsigned short int can be converted to an rvalue of type int if
1988   // int can represent all the values of the source type; otherwise,
1989   // the source rvalue can be converted to an rvalue of type unsigned
1990   // int (C++ 4.5p1).
1991   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1992       !FromType->isEnumeralType()) {
1993     if (// We can promote any signed, promotable integer type to an int
1994         (FromType->isSignedIntegerType() ||
1995          // We can promote any unsigned integer type whose size is
1996          // less than int to an int.
1997          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1998       return To->getKind() == BuiltinType::Int;
1999     }
2000 
2001     return To->getKind() == BuiltinType::UInt;
2002   }
2003 
2004   // C++11 [conv.prom]p3:
2005   //   A prvalue of an unscoped enumeration type whose underlying type is not
2006   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2007   //   following types that can represent all the values of the enumeration
2008   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2009   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2010   //   long long int. If none of the types in that list can represent all the
2011   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2012   //   type can be converted to an rvalue a prvalue of the extended integer type
2013   //   with lowest integer conversion rank (4.13) greater than the rank of long
2014   //   long in which all the values of the enumeration can be represented. If
2015   //   there are two such extended types, the signed one is chosen.
2016   // C++11 [conv.prom]p4:
2017   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2018   //   can be converted to a prvalue of its underlying type. Moreover, if
2019   //   integral promotion can be applied to its underlying type, a prvalue of an
2020   //   unscoped enumeration type whose underlying type is fixed can also be
2021   //   converted to a prvalue of the promoted underlying type.
2022   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2023     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2024     // provided for a scoped enumeration.
2025     if (FromEnumType->getDecl()->isScoped())
2026       return false;
2027 
2028     // We can perform an integral promotion to the underlying type of the enum,
2029     // even if that's not the promoted type. Note that the check for promoting
2030     // the underlying type is based on the type alone, and does not consider
2031     // the bitfield-ness of the actual source expression.
2032     if (FromEnumType->getDecl()->isFixed()) {
2033       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2034       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2035              IsIntegralPromotion(nullptr, Underlying, ToType);
2036     }
2037 
2038     // We have already pre-calculated the promotion type, so this is trivial.
2039     if (ToType->isIntegerType() &&
2040         isCompleteType(From->getBeginLoc(), FromType))
2041       return Context.hasSameUnqualifiedType(
2042           ToType, FromEnumType->getDecl()->getPromotionType());
2043 
2044     // C++ [conv.prom]p5:
2045     //   If the bit-field has an enumerated type, it is treated as any other
2046     //   value of that type for promotion purposes.
2047     //
2048     // ... so do not fall through into the bit-field checks below in C++.
2049     if (getLangOpts().CPlusPlus)
2050       return false;
2051   }
2052 
2053   // C++0x [conv.prom]p2:
2054   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2055   //   to an rvalue a prvalue of the first of the following types that can
2056   //   represent all the values of its underlying type: int, unsigned int,
2057   //   long int, unsigned long int, long long int, or unsigned long long int.
2058   //   If none of the types in that list can represent all the values of its
2059   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2060   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2061   //   type.
2062   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2063       ToType->isIntegerType()) {
2064     // Determine whether the type we're converting from is signed or
2065     // unsigned.
2066     bool FromIsSigned = FromType->isSignedIntegerType();
2067     uint64_t FromSize = Context.getTypeSize(FromType);
2068 
2069     // The types we'll try to promote to, in the appropriate
2070     // order. Try each of these types.
2071     QualType PromoteTypes[6] = {
2072       Context.IntTy, Context.UnsignedIntTy,
2073       Context.LongTy, Context.UnsignedLongTy ,
2074       Context.LongLongTy, Context.UnsignedLongLongTy
2075     };
2076     for (int Idx = 0; Idx < 6; ++Idx) {
2077       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2078       if (FromSize < ToSize ||
2079           (FromSize == ToSize &&
2080            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2081         // We found the type that we can promote to. If this is the
2082         // type we wanted, we have a promotion. Otherwise, no
2083         // promotion.
2084         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2085       }
2086     }
2087   }
2088 
2089   // An rvalue for an integral bit-field (9.6) can be converted to an
2090   // rvalue of type int if int can represent all the values of the
2091   // bit-field; otherwise, it can be converted to unsigned int if
2092   // unsigned int can represent all the values of the bit-field. If
2093   // the bit-field is larger yet, no integral promotion applies to
2094   // it. If the bit-field has an enumerated type, it is treated as any
2095   // other value of that type for promotion purposes (C++ 4.5p3).
2096   // FIXME: We should delay checking of bit-fields until we actually perform the
2097   // conversion.
2098   //
2099   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2100   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2101   // bit-fields and those whose underlying type is larger than int) for GCC
2102   // compatibility.
2103   if (From) {
2104     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2105       llvm::APSInt BitWidth;
2106       if (FromType->isIntegralType(Context) &&
2107           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2108         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2109         ToSize = Context.getTypeSize(ToType);
2110 
2111         // Are we promoting to an int from a bitfield that fits in an int?
2112         if (BitWidth < ToSize ||
2113             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2114           return To->getKind() == BuiltinType::Int;
2115         }
2116 
2117         // Are we promoting to an unsigned int from an unsigned bitfield
2118         // that fits into an unsigned int?
2119         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2120           return To->getKind() == BuiltinType::UInt;
2121         }
2122 
2123         return false;
2124       }
2125     }
2126   }
2127 
2128   // An rvalue of type bool can be converted to an rvalue of type int,
2129   // with false becoming zero and true becoming one (C++ 4.5p4).
2130   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2131     return true;
2132   }
2133 
2134   return false;
2135 }
2136 
2137 /// IsFloatingPointPromotion - Determines whether the conversion from
2138 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2139 /// returns true and sets PromotedType to the promoted type.
2140 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2141   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2142     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2143       /// An rvalue of type float can be converted to an rvalue of type
2144       /// double. (C++ 4.6p1).
2145       if (FromBuiltin->getKind() == BuiltinType::Float &&
2146           ToBuiltin->getKind() == BuiltinType::Double)
2147         return true;
2148 
2149       // C99 6.3.1.5p1:
2150       //   When a float is promoted to double or long double, or a
2151       //   double is promoted to long double [...].
2152       if (!getLangOpts().CPlusPlus &&
2153           (FromBuiltin->getKind() == BuiltinType::Float ||
2154            FromBuiltin->getKind() == BuiltinType::Double) &&
2155           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2156            ToBuiltin->getKind() == BuiltinType::Float128))
2157         return true;
2158 
2159       // Half can be promoted to float.
2160       if (!getLangOpts().NativeHalfType &&
2161            FromBuiltin->getKind() == BuiltinType::Half &&
2162           ToBuiltin->getKind() == BuiltinType::Float)
2163         return true;
2164     }
2165 
2166   return false;
2167 }
2168 
2169 /// Determine if a conversion is a complex promotion.
2170 ///
2171 /// A complex promotion is defined as a complex -> complex conversion
2172 /// where the conversion between the underlying real types is a
2173 /// floating-point or integral promotion.
2174 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2175   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2176   if (!FromComplex)
2177     return false;
2178 
2179   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2180   if (!ToComplex)
2181     return false;
2182 
2183   return IsFloatingPointPromotion(FromComplex->getElementType(),
2184                                   ToComplex->getElementType()) ||
2185     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2186                         ToComplex->getElementType());
2187 }
2188 
2189 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2190 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2191 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2192 /// if non-empty, will be a pointer to ToType that may or may not have
2193 /// the right set of qualifiers on its pointee.
2194 ///
2195 static QualType
2196 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2197                                    QualType ToPointee, QualType ToType,
2198                                    ASTContext &Context,
2199                                    bool StripObjCLifetime = false) {
2200   assert((FromPtr->getTypeClass() == Type::Pointer ||
2201           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2202          "Invalid similarly-qualified pointer type");
2203 
2204   /// Conversions to 'id' subsume cv-qualifier conversions.
2205   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2206     return ToType.getUnqualifiedType();
2207 
2208   QualType CanonFromPointee
2209     = Context.getCanonicalType(FromPtr->getPointeeType());
2210   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2211   Qualifiers Quals = CanonFromPointee.getQualifiers();
2212 
2213   if (StripObjCLifetime)
2214     Quals.removeObjCLifetime();
2215 
2216   // Exact qualifier match -> return the pointer type we're converting to.
2217   if (CanonToPointee.getLocalQualifiers() == Quals) {
2218     // ToType is exactly what we need. Return it.
2219     if (!ToType.isNull())
2220       return ToType.getUnqualifiedType();
2221 
2222     // Build a pointer to ToPointee. It has the right qualifiers
2223     // already.
2224     if (isa<ObjCObjectPointerType>(ToType))
2225       return Context.getObjCObjectPointerType(ToPointee);
2226     return Context.getPointerType(ToPointee);
2227   }
2228 
2229   // Just build a canonical type that has the right qualifiers.
2230   QualType QualifiedCanonToPointee
2231     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2232 
2233   if (isa<ObjCObjectPointerType>(ToType))
2234     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2235   return Context.getPointerType(QualifiedCanonToPointee);
2236 }
2237 
2238 static bool isNullPointerConstantForConversion(Expr *Expr,
2239                                                bool InOverloadResolution,
2240                                                ASTContext &Context) {
2241   // Handle value-dependent integral null pointer constants correctly.
2242   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2243   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2244       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2245     return !InOverloadResolution;
2246 
2247   return Expr->isNullPointerConstant(Context,
2248                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2249                                         : Expr::NPC_ValueDependentIsNull);
2250 }
2251 
2252 /// IsPointerConversion - Determines whether the conversion of the
2253 /// expression From, which has the (possibly adjusted) type FromType,
2254 /// can be converted to the type ToType via a pointer conversion (C++
2255 /// 4.10). If so, returns true and places the converted type (that
2256 /// might differ from ToType in its cv-qualifiers at some level) into
2257 /// ConvertedType.
2258 ///
2259 /// This routine also supports conversions to and from block pointers
2260 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2261 /// pointers to interfaces. FIXME: Once we've determined the
2262 /// appropriate overloading rules for Objective-C, we may want to
2263 /// split the Objective-C checks into a different routine; however,
2264 /// GCC seems to consider all of these conversions to be pointer
2265 /// conversions, so for now they live here. IncompatibleObjC will be
2266 /// set if the conversion is an allowed Objective-C conversion that
2267 /// should result in a warning.
2268 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2269                                bool InOverloadResolution,
2270                                QualType& ConvertedType,
2271                                bool &IncompatibleObjC) {
2272   IncompatibleObjC = false;
2273   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2274                               IncompatibleObjC))
2275     return true;
2276 
2277   // Conversion from a null pointer constant to any Objective-C pointer type.
2278   if (ToType->isObjCObjectPointerType() &&
2279       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2280     ConvertedType = ToType;
2281     return true;
2282   }
2283 
2284   // Blocks: Block pointers can be converted to void*.
2285   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2286       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2287     ConvertedType = ToType;
2288     return true;
2289   }
2290   // Blocks: A null pointer constant can be converted to a block
2291   // pointer type.
2292   if (ToType->isBlockPointerType() &&
2293       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2294     ConvertedType = ToType;
2295     return true;
2296   }
2297 
2298   // If the left-hand-side is nullptr_t, the right side can be a null
2299   // pointer constant.
2300   if (ToType->isNullPtrType() &&
2301       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2302     ConvertedType = ToType;
2303     return true;
2304   }
2305 
2306   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2307   if (!ToTypePtr)
2308     return false;
2309 
2310   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2311   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2312     ConvertedType = ToType;
2313     return true;
2314   }
2315 
2316   // Beyond this point, both types need to be pointers
2317   // , including objective-c pointers.
2318   QualType ToPointeeType = ToTypePtr->getPointeeType();
2319   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2320       !getLangOpts().ObjCAutoRefCount) {
2321     ConvertedType = BuildSimilarlyQualifiedPointerType(
2322                                       FromType->getAs<ObjCObjectPointerType>(),
2323                                                        ToPointeeType,
2324                                                        ToType, Context);
2325     return true;
2326   }
2327   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2328   if (!FromTypePtr)
2329     return false;
2330 
2331   QualType FromPointeeType = FromTypePtr->getPointeeType();
2332 
2333   // If the unqualified pointee types are the same, this can't be a
2334   // pointer conversion, so don't do all of the work below.
2335   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2336     return false;
2337 
2338   // An rvalue of type "pointer to cv T," where T is an object type,
2339   // can be converted to an rvalue of type "pointer to cv void" (C++
2340   // 4.10p2).
2341   if (FromPointeeType->isIncompleteOrObjectType() &&
2342       ToPointeeType->isVoidType()) {
2343     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2344                                                        ToPointeeType,
2345                                                        ToType, Context,
2346                                                    /*StripObjCLifetime=*/true);
2347     return true;
2348   }
2349 
2350   // MSVC allows implicit function to void* type conversion.
2351   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2352       ToPointeeType->isVoidType()) {
2353     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354                                                        ToPointeeType,
2355                                                        ToType, Context);
2356     return true;
2357   }
2358 
2359   // When we're overloading in C, we allow a special kind of pointer
2360   // conversion for compatible-but-not-identical pointee types.
2361   if (!getLangOpts().CPlusPlus &&
2362       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2363     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2364                                                        ToPointeeType,
2365                                                        ToType, Context);
2366     return true;
2367   }
2368 
2369   // C++ [conv.ptr]p3:
2370   //
2371   //   An rvalue of type "pointer to cv D," where D is a class type,
2372   //   can be converted to an rvalue of type "pointer to cv B," where
2373   //   B is a base class (clause 10) of D. If B is an inaccessible
2374   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2375   //   necessitates this conversion is ill-formed. The result of the
2376   //   conversion is a pointer to the base class sub-object of the
2377   //   derived class object. The null pointer value is converted to
2378   //   the null pointer value of the destination type.
2379   //
2380   // Note that we do not check for ambiguity or inaccessibility
2381   // here. That is handled by CheckPointerConversion.
2382   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2383       ToPointeeType->isRecordType() &&
2384       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2385       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2386     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2387                                                        ToPointeeType,
2388                                                        ToType, Context);
2389     return true;
2390   }
2391 
2392   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2393       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2394     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2395                                                        ToPointeeType,
2396                                                        ToType, Context);
2397     return true;
2398   }
2399 
2400   return false;
2401 }
2402 
2403 /// Adopt the given qualifiers for the given type.
2404 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2405   Qualifiers TQs = T.getQualifiers();
2406 
2407   // Check whether qualifiers already match.
2408   if (TQs == Qs)
2409     return T;
2410 
2411   if (Qs.compatiblyIncludes(TQs))
2412     return Context.getQualifiedType(T, Qs);
2413 
2414   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2415 }
2416 
2417 /// isObjCPointerConversion - Determines whether this is an
2418 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2419 /// with the same arguments and return values.
2420 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2421                                    QualType& ConvertedType,
2422                                    bool &IncompatibleObjC) {
2423   if (!getLangOpts().ObjC)
2424     return false;
2425 
2426   // The set of qualifiers on the type we're converting from.
2427   Qualifiers FromQualifiers = FromType.getQualifiers();
2428 
2429   // First, we handle all conversions on ObjC object pointer types.
2430   const ObjCObjectPointerType* ToObjCPtr =
2431     ToType->getAs<ObjCObjectPointerType>();
2432   const ObjCObjectPointerType *FromObjCPtr =
2433     FromType->getAs<ObjCObjectPointerType>();
2434 
2435   if (ToObjCPtr && FromObjCPtr) {
2436     // If the pointee types are the same (ignoring qualifications),
2437     // then this is not a pointer conversion.
2438     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2439                                        FromObjCPtr->getPointeeType()))
2440       return false;
2441 
2442     // Conversion between Objective-C pointers.
2443     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2444       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2445       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2446       if (getLangOpts().CPlusPlus && LHS && RHS &&
2447           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2448                                                 FromObjCPtr->getPointeeType()))
2449         return false;
2450       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2451                                                    ToObjCPtr->getPointeeType(),
2452                                                          ToType, Context);
2453       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2454       return true;
2455     }
2456 
2457     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2458       // Okay: this is some kind of implicit downcast of Objective-C
2459       // interfaces, which is permitted. However, we're going to
2460       // complain about it.
2461       IncompatibleObjC = true;
2462       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2463                                                    ToObjCPtr->getPointeeType(),
2464                                                          ToType, Context);
2465       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2466       return true;
2467     }
2468   }
2469   // Beyond this point, both types need to be C pointers or block pointers.
2470   QualType ToPointeeType;
2471   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2472     ToPointeeType = ToCPtr->getPointeeType();
2473   else if (const BlockPointerType *ToBlockPtr =
2474             ToType->getAs<BlockPointerType>()) {
2475     // Objective C++: We're able to convert from a pointer to any object
2476     // to a block pointer type.
2477     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2478       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2479       return true;
2480     }
2481     ToPointeeType = ToBlockPtr->getPointeeType();
2482   }
2483   else if (FromType->getAs<BlockPointerType>() &&
2484            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2485     // Objective C++: We're able to convert from a block pointer type to a
2486     // pointer to any object.
2487     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2488     return true;
2489   }
2490   else
2491     return false;
2492 
2493   QualType FromPointeeType;
2494   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2495     FromPointeeType = FromCPtr->getPointeeType();
2496   else if (const BlockPointerType *FromBlockPtr =
2497            FromType->getAs<BlockPointerType>())
2498     FromPointeeType = FromBlockPtr->getPointeeType();
2499   else
2500     return false;
2501 
2502   // If we have pointers to pointers, recursively check whether this
2503   // is an Objective-C conversion.
2504   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2505       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2506                               IncompatibleObjC)) {
2507     // We always complain about this conversion.
2508     IncompatibleObjC = true;
2509     ConvertedType = Context.getPointerType(ConvertedType);
2510     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2511     return true;
2512   }
2513   // Allow conversion of pointee being objective-c pointer to another one;
2514   // as in I* to id.
2515   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2516       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2517       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2518                               IncompatibleObjC)) {
2519 
2520     ConvertedType = Context.getPointerType(ConvertedType);
2521     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2522     return true;
2523   }
2524 
2525   // If we have pointers to functions or blocks, check whether the only
2526   // differences in the argument and result types are in Objective-C
2527   // pointer conversions. If so, we permit the conversion (but
2528   // complain about it).
2529   const FunctionProtoType *FromFunctionType
2530     = FromPointeeType->getAs<FunctionProtoType>();
2531   const FunctionProtoType *ToFunctionType
2532     = ToPointeeType->getAs<FunctionProtoType>();
2533   if (FromFunctionType && ToFunctionType) {
2534     // If the function types are exactly the same, this isn't an
2535     // Objective-C pointer conversion.
2536     if (Context.getCanonicalType(FromPointeeType)
2537           == Context.getCanonicalType(ToPointeeType))
2538       return false;
2539 
2540     // Perform the quick checks that will tell us whether these
2541     // function types are obviously different.
2542     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2543         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2544         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2545       return false;
2546 
2547     bool HasObjCConversion = false;
2548     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2549         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2550       // Okay, the types match exactly. Nothing to do.
2551     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2552                                        ToFunctionType->getReturnType(),
2553                                        ConvertedType, IncompatibleObjC)) {
2554       // Okay, we have an Objective-C pointer conversion.
2555       HasObjCConversion = true;
2556     } else {
2557       // Function types are too different. Abort.
2558       return false;
2559     }
2560 
2561     // Check argument types.
2562     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2563          ArgIdx != NumArgs; ++ArgIdx) {
2564       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2565       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2566       if (Context.getCanonicalType(FromArgType)
2567             == Context.getCanonicalType(ToArgType)) {
2568         // Okay, the types match exactly. Nothing to do.
2569       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2570                                          ConvertedType, IncompatibleObjC)) {
2571         // Okay, we have an Objective-C pointer conversion.
2572         HasObjCConversion = true;
2573       } else {
2574         // Argument types are too different. Abort.
2575         return false;
2576       }
2577     }
2578 
2579     if (HasObjCConversion) {
2580       // We had an Objective-C conversion. Allow this pointer
2581       // conversion, but complain about it.
2582       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2583       IncompatibleObjC = true;
2584       return true;
2585     }
2586   }
2587 
2588   return false;
2589 }
2590 
2591 /// Determine whether this is an Objective-C writeback conversion,
2592 /// used for parameter passing when performing automatic reference counting.
2593 ///
2594 /// \param FromType The type we're converting form.
2595 ///
2596 /// \param ToType The type we're converting to.
2597 ///
2598 /// \param ConvertedType The type that will be produced after applying
2599 /// this conversion.
2600 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2601                                      QualType &ConvertedType) {
2602   if (!getLangOpts().ObjCAutoRefCount ||
2603       Context.hasSameUnqualifiedType(FromType, ToType))
2604     return false;
2605 
2606   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2607   QualType ToPointee;
2608   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2609     ToPointee = ToPointer->getPointeeType();
2610   else
2611     return false;
2612 
2613   Qualifiers ToQuals = ToPointee.getQualifiers();
2614   if (!ToPointee->isObjCLifetimeType() ||
2615       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2616       !ToQuals.withoutObjCLifetime().empty())
2617     return false;
2618 
2619   // Argument must be a pointer to __strong to __weak.
2620   QualType FromPointee;
2621   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2622     FromPointee = FromPointer->getPointeeType();
2623   else
2624     return false;
2625 
2626   Qualifiers FromQuals = FromPointee.getQualifiers();
2627   if (!FromPointee->isObjCLifetimeType() ||
2628       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2629        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2630     return false;
2631 
2632   // Make sure that we have compatible qualifiers.
2633   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2634   if (!ToQuals.compatiblyIncludes(FromQuals))
2635     return false;
2636 
2637   // Remove qualifiers from the pointee type we're converting from; they
2638   // aren't used in the compatibility check belong, and we'll be adding back
2639   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2640   FromPointee = FromPointee.getUnqualifiedType();
2641 
2642   // The unqualified form of the pointee types must be compatible.
2643   ToPointee = ToPointee.getUnqualifiedType();
2644   bool IncompatibleObjC;
2645   if (Context.typesAreCompatible(FromPointee, ToPointee))
2646     FromPointee = ToPointee;
2647   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2648                                     IncompatibleObjC))
2649     return false;
2650 
2651   /// Construct the type we're converting to, which is a pointer to
2652   /// __autoreleasing pointee.
2653   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2654   ConvertedType = Context.getPointerType(FromPointee);
2655   return true;
2656 }
2657 
2658 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2659                                     QualType& ConvertedType) {
2660   QualType ToPointeeType;
2661   if (const BlockPointerType *ToBlockPtr =
2662         ToType->getAs<BlockPointerType>())
2663     ToPointeeType = ToBlockPtr->getPointeeType();
2664   else
2665     return false;
2666 
2667   QualType FromPointeeType;
2668   if (const BlockPointerType *FromBlockPtr =
2669       FromType->getAs<BlockPointerType>())
2670     FromPointeeType = FromBlockPtr->getPointeeType();
2671   else
2672     return false;
2673   // We have pointer to blocks, check whether the only
2674   // differences in the argument and result types are in Objective-C
2675   // pointer conversions. If so, we permit the conversion.
2676 
2677   const FunctionProtoType *FromFunctionType
2678     = FromPointeeType->getAs<FunctionProtoType>();
2679   const FunctionProtoType *ToFunctionType
2680     = ToPointeeType->getAs<FunctionProtoType>();
2681 
2682   if (!FromFunctionType || !ToFunctionType)
2683     return false;
2684 
2685   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2686     return true;
2687 
2688   // Perform the quick checks that will tell us whether these
2689   // function types are obviously different.
2690   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2691       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2692     return false;
2693 
2694   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2695   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2696   if (FromEInfo != ToEInfo)
2697     return false;
2698 
2699   bool IncompatibleObjC = false;
2700   if (Context.hasSameType(FromFunctionType->getReturnType(),
2701                           ToFunctionType->getReturnType())) {
2702     // Okay, the types match exactly. Nothing to do.
2703   } else {
2704     QualType RHS = FromFunctionType->getReturnType();
2705     QualType LHS = ToFunctionType->getReturnType();
2706     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2707         !RHS.hasQualifiers() && LHS.hasQualifiers())
2708        LHS = LHS.getUnqualifiedType();
2709 
2710      if (Context.hasSameType(RHS,LHS)) {
2711        // OK exact match.
2712      } else if (isObjCPointerConversion(RHS, LHS,
2713                                         ConvertedType, IncompatibleObjC)) {
2714      if (IncompatibleObjC)
2715        return false;
2716      // Okay, we have an Objective-C pointer conversion.
2717      }
2718      else
2719        return false;
2720    }
2721 
2722    // Check argument types.
2723    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2724         ArgIdx != NumArgs; ++ArgIdx) {
2725      IncompatibleObjC = false;
2726      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2727      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2728      if (Context.hasSameType(FromArgType, ToArgType)) {
2729        // Okay, the types match exactly. Nothing to do.
2730      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2731                                         ConvertedType, IncompatibleObjC)) {
2732        if (IncompatibleObjC)
2733          return false;
2734        // Okay, we have an Objective-C pointer conversion.
2735      } else
2736        // Argument types are too different. Abort.
2737        return false;
2738    }
2739 
2740    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2741    bool CanUseToFPT, CanUseFromFPT;
2742    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2743                                       CanUseToFPT, CanUseFromFPT,
2744                                       NewParamInfos))
2745      return false;
2746 
2747    ConvertedType = ToType;
2748    return true;
2749 }
2750 
2751 enum {
2752   ft_default,
2753   ft_different_class,
2754   ft_parameter_arity,
2755   ft_parameter_mismatch,
2756   ft_return_type,
2757   ft_qualifer_mismatch,
2758   ft_noexcept
2759 };
2760 
2761 /// Attempts to get the FunctionProtoType from a Type. Handles
2762 /// MemberFunctionPointers properly.
2763 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2764   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2765     return FPT;
2766 
2767   if (auto *MPT = FromType->getAs<MemberPointerType>())
2768     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2769 
2770   return nullptr;
2771 }
2772 
2773 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2774 /// function types.  Catches different number of parameter, mismatch in
2775 /// parameter types, and different return types.
2776 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2777                                       QualType FromType, QualType ToType) {
2778   // If either type is not valid, include no extra info.
2779   if (FromType.isNull() || ToType.isNull()) {
2780     PDiag << ft_default;
2781     return;
2782   }
2783 
2784   // Get the function type from the pointers.
2785   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2786     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2787                             *ToMember = ToType->getAs<MemberPointerType>();
2788     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2789       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2790             << QualType(FromMember->getClass(), 0);
2791       return;
2792     }
2793     FromType = FromMember->getPointeeType();
2794     ToType = ToMember->getPointeeType();
2795   }
2796 
2797   if (FromType->isPointerType())
2798     FromType = FromType->getPointeeType();
2799   if (ToType->isPointerType())
2800     ToType = ToType->getPointeeType();
2801 
2802   // Remove references.
2803   FromType = FromType.getNonReferenceType();
2804   ToType = ToType.getNonReferenceType();
2805 
2806   // Don't print extra info for non-specialized template functions.
2807   if (FromType->isInstantiationDependentType() &&
2808       !FromType->getAs<TemplateSpecializationType>()) {
2809     PDiag << ft_default;
2810     return;
2811   }
2812 
2813   // No extra info for same types.
2814   if (Context.hasSameType(FromType, ToType)) {
2815     PDiag << ft_default;
2816     return;
2817   }
2818 
2819   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2820                           *ToFunction = tryGetFunctionProtoType(ToType);
2821 
2822   // Both types need to be function types.
2823   if (!FromFunction || !ToFunction) {
2824     PDiag << ft_default;
2825     return;
2826   }
2827 
2828   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2829     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2830           << FromFunction->getNumParams();
2831     return;
2832   }
2833 
2834   // Handle different parameter types.
2835   unsigned ArgPos;
2836   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2837     PDiag << ft_parameter_mismatch << ArgPos + 1
2838           << ToFunction->getParamType(ArgPos)
2839           << FromFunction->getParamType(ArgPos);
2840     return;
2841   }
2842 
2843   // Handle different return type.
2844   if (!Context.hasSameType(FromFunction->getReturnType(),
2845                            ToFunction->getReturnType())) {
2846     PDiag << ft_return_type << ToFunction->getReturnType()
2847           << FromFunction->getReturnType();
2848     return;
2849   }
2850 
2851   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2852     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2853           << FromFunction->getMethodQuals();
2854     return;
2855   }
2856 
2857   // Handle exception specification differences on canonical type (in C++17
2858   // onwards).
2859   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2860           ->isNothrow() !=
2861       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2862           ->isNothrow()) {
2863     PDiag << ft_noexcept;
2864     return;
2865   }
2866 
2867   // Unable to find a difference, so add no extra info.
2868   PDiag << ft_default;
2869 }
2870 
2871 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2872 /// for equality of their argument types. Caller has already checked that
2873 /// they have same number of arguments.  If the parameters are different,
2874 /// ArgPos will have the parameter index of the first different parameter.
2875 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2876                                       const FunctionProtoType *NewType,
2877                                       unsigned *ArgPos) {
2878   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2879                                               N = NewType->param_type_begin(),
2880                                               E = OldType->param_type_end();
2881        O && (O != E); ++O, ++N) {
2882     if (!Context.hasSameType(O->getUnqualifiedType(),
2883                              N->getUnqualifiedType())) {
2884       if (ArgPos)
2885         *ArgPos = O - OldType->param_type_begin();
2886       return false;
2887     }
2888   }
2889   return true;
2890 }
2891 
2892 /// CheckPointerConversion - Check the pointer conversion from the
2893 /// expression From to the type ToType. This routine checks for
2894 /// ambiguous or inaccessible derived-to-base pointer
2895 /// conversions for which IsPointerConversion has already returned
2896 /// true. It returns true and produces a diagnostic if there was an
2897 /// error, or returns false otherwise.
2898 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2899                                   CastKind &Kind,
2900                                   CXXCastPath& BasePath,
2901                                   bool IgnoreBaseAccess,
2902                                   bool Diagnose) {
2903   QualType FromType = From->getType();
2904   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2905 
2906   Kind = CK_BitCast;
2907 
2908   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2909       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2910           Expr::NPCK_ZeroExpression) {
2911     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2912       DiagRuntimeBehavior(From->getExprLoc(), From,
2913                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2914                             << ToType << From->getSourceRange());
2915     else if (!isUnevaluatedContext())
2916       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2917         << ToType << From->getSourceRange();
2918   }
2919   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2920     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2921       QualType FromPointeeType = FromPtrType->getPointeeType(),
2922                ToPointeeType   = ToPtrType->getPointeeType();
2923 
2924       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2925           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2926         // We must have a derived-to-base conversion. Check an
2927         // ambiguous or inaccessible conversion.
2928         unsigned InaccessibleID = 0;
2929         unsigned AmbigiousID = 0;
2930         if (Diagnose) {
2931           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2932           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2933         }
2934         if (CheckDerivedToBaseConversion(
2935                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2936                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2937                 &BasePath, IgnoreBaseAccess))
2938           return true;
2939 
2940         // The conversion was successful.
2941         Kind = CK_DerivedToBase;
2942       }
2943 
2944       if (Diagnose && !IsCStyleOrFunctionalCast &&
2945           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2946         assert(getLangOpts().MSVCCompat &&
2947                "this should only be possible with MSVCCompat!");
2948         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2949             << From->getSourceRange();
2950       }
2951     }
2952   } else if (const ObjCObjectPointerType *ToPtrType =
2953                ToType->getAs<ObjCObjectPointerType>()) {
2954     if (const ObjCObjectPointerType *FromPtrType =
2955           FromType->getAs<ObjCObjectPointerType>()) {
2956       // Objective-C++ conversions are always okay.
2957       // FIXME: We should have a different class of conversions for the
2958       // Objective-C++ implicit conversions.
2959       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2960         return false;
2961     } else if (FromType->isBlockPointerType()) {
2962       Kind = CK_BlockPointerToObjCPointerCast;
2963     } else {
2964       Kind = CK_CPointerToObjCPointerCast;
2965     }
2966   } else if (ToType->isBlockPointerType()) {
2967     if (!FromType->isBlockPointerType())
2968       Kind = CK_AnyPointerToBlockPointerCast;
2969   }
2970 
2971   // We shouldn't fall into this case unless it's valid for other
2972   // reasons.
2973   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2974     Kind = CK_NullToPointer;
2975 
2976   return false;
2977 }
2978 
2979 /// IsMemberPointerConversion - Determines whether the conversion of the
2980 /// expression From, which has the (possibly adjusted) type FromType, can be
2981 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2982 /// If so, returns true and places the converted type (that might differ from
2983 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2984 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2985                                      QualType ToType,
2986                                      bool InOverloadResolution,
2987                                      QualType &ConvertedType) {
2988   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2989   if (!ToTypePtr)
2990     return false;
2991 
2992   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2993   if (From->isNullPointerConstant(Context,
2994                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2995                                         : Expr::NPC_ValueDependentIsNull)) {
2996     ConvertedType = ToType;
2997     return true;
2998   }
2999 
3000   // Otherwise, both types have to be member pointers.
3001   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3002   if (!FromTypePtr)
3003     return false;
3004 
3005   // A pointer to member of B can be converted to a pointer to member of D,
3006   // where D is derived from B (C++ 4.11p2).
3007   QualType FromClass(FromTypePtr->getClass(), 0);
3008   QualType ToClass(ToTypePtr->getClass(), 0);
3009 
3010   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3011       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3012     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3013                                                  ToClass.getTypePtr());
3014     return true;
3015   }
3016 
3017   return false;
3018 }
3019 
3020 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3021 /// expression From to the type ToType. This routine checks for ambiguous or
3022 /// virtual or inaccessible base-to-derived member pointer conversions
3023 /// for which IsMemberPointerConversion has already returned true. It returns
3024 /// true and produces a diagnostic if there was an error, or returns false
3025 /// otherwise.
3026 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3027                                         CastKind &Kind,
3028                                         CXXCastPath &BasePath,
3029                                         bool IgnoreBaseAccess) {
3030   QualType FromType = From->getType();
3031   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3032   if (!FromPtrType) {
3033     // This must be a null pointer to member pointer conversion
3034     assert(From->isNullPointerConstant(Context,
3035                                        Expr::NPC_ValueDependentIsNull) &&
3036            "Expr must be null pointer constant!");
3037     Kind = CK_NullToMemberPointer;
3038     return false;
3039   }
3040 
3041   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3042   assert(ToPtrType && "No member pointer cast has a target type "
3043                       "that is not a member pointer.");
3044 
3045   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3046   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3047 
3048   // FIXME: What about dependent types?
3049   assert(FromClass->isRecordType() && "Pointer into non-class.");
3050   assert(ToClass->isRecordType() && "Pointer into non-class.");
3051 
3052   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3053                      /*DetectVirtual=*/true);
3054   bool DerivationOkay =
3055       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3056   assert(DerivationOkay &&
3057          "Should not have been called if derivation isn't OK.");
3058   (void)DerivationOkay;
3059 
3060   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3061                                   getUnqualifiedType())) {
3062     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3063     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3064       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3065     return true;
3066   }
3067 
3068   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3069     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3070       << FromClass << ToClass << QualType(VBase, 0)
3071       << From->getSourceRange();
3072     return true;
3073   }
3074 
3075   if (!IgnoreBaseAccess)
3076     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3077                          Paths.front(),
3078                          diag::err_downcast_from_inaccessible_base);
3079 
3080   // Must be a base to derived member conversion.
3081   BuildBasePathArray(Paths, BasePath);
3082   Kind = CK_BaseToDerivedMemberPointer;
3083   return false;
3084 }
3085 
3086 /// Determine whether the lifetime conversion between the two given
3087 /// qualifiers sets is nontrivial.
3088 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3089                                                Qualifiers ToQuals) {
3090   // Converting anything to const __unsafe_unretained is trivial.
3091   if (ToQuals.hasConst() &&
3092       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3093     return false;
3094 
3095   return true;
3096 }
3097 
3098 /// IsQualificationConversion - Determines whether the conversion from
3099 /// an rvalue of type FromType to ToType is a qualification conversion
3100 /// (C++ 4.4).
3101 ///
3102 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3103 /// when the qualification conversion involves a change in the Objective-C
3104 /// object lifetime.
3105 bool
3106 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3107                                 bool CStyle, bool &ObjCLifetimeConversion) {
3108   FromType = Context.getCanonicalType(FromType);
3109   ToType = Context.getCanonicalType(ToType);
3110   ObjCLifetimeConversion = false;
3111 
3112   // If FromType and ToType are the same type, this is not a
3113   // qualification conversion.
3114   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3115     return false;
3116 
3117   // (C++ 4.4p4):
3118   //   A conversion can add cv-qualifiers at levels other than the first
3119   //   in multi-level pointers, subject to the following rules: [...]
3120   bool PreviousToQualsIncludeConst = true;
3121   bool UnwrappedAnyPointer = false;
3122   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3123     // Within each iteration of the loop, we check the qualifiers to
3124     // determine if this still looks like a qualification
3125     // conversion. Then, if all is well, we unwrap one more level of
3126     // pointers or pointers-to-members and do it all again
3127     // until there are no more pointers or pointers-to-members left to
3128     // unwrap.
3129     UnwrappedAnyPointer = true;
3130 
3131     Qualifiers FromQuals = FromType.getQualifiers();
3132     Qualifiers ToQuals = ToType.getQualifiers();
3133 
3134     // Ignore __unaligned qualifier if this type is void.
3135     if (ToType.getUnqualifiedType()->isVoidType())
3136       FromQuals.removeUnaligned();
3137 
3138     // Objective-C ARC:
3139     //   Check Objective-C lifetime conversions.
3140     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3141         UnwrappedAnyPointer) {
3142       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3143         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3144           ObjCLifetimeConversion = true;
3145         FromQuals.removeObjCLifetime();
3146         ToQuals.removeObjCLifetime();
3147       } else {
3148         // Qualification conversions cannot cast between different
3149         // Objective-C lifetime qualifiers.
3150         return false;
3151       }
3152     }
3153 
3154     // Allow addition/removal of GC attributes but not changing GC attributes.
3155     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3156         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3157       FromQuals.removeObjCGCAttr();
3158       ToQuals.removeObjCGCAttr();
3159     }
3160 
3161     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3162     //      2,j, and similarly for volatile.
3163     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3164       return false;
3165 
3166     //   -- if the cv 1,j and cv 2,j are different, then const is in
3167     //      every cv for 0 < k < j.
3168     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3169         && !PreviousToQualsIncludeConst)
3170       return false;
3171 
3172     // Keep track of whether all prior cv-qualifiers in the "to" type
3173     // include const.
3174     PreviousToQualsIncludeConst
3175       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3176   }
3177 
3178   // Allows address space promotion by language rules implemented in
3179   // Type::Qualifiers::isAddressSpaceSupersetOf.
3180   Qualifiers FromQuals = FromType.getQualifiers();
3181   Qualifiers ToQuals = ToType.getQualifiers();
3182   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3183       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3184     return false;
3185   }
3186 
3187   // We are left with FromType and ToType being the pointee types
3188   // after unwrapping the original FromType and ToType the same number
3189   // of types. If we unwrapped any pointers, and if FromType and
3190   // ToType have the same unqualified type (since we checked
3191   // qualifiers above), then this is a qualification conversion.
3192   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3193 }
3194 
3195 /// - Determine whether this is a conversion from a scalar type to an
3196 /// atomic type.
3197 ///
3198 /// If successful, updates \c SCS's second and third steps in the conversion
3199 /// sequence to finish the conversion.
3200 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3201                                 bool InOverloadResolution,
3202                                 StandardConversionSequence &SCS,
3203                                 bool CStyle) {
3204   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3205   if (!ToAtomic)
3206     return false;
3207 
3208   StandardConversionSequence InnerSCS;
3209   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3210                             InOverloadResolution, InnerSCS,
3211                             CStyle, /*AllowObjCWritebackConversion=*/false))
3212     return false;
3213 
3214   SCS.Second = InnerSCS.Second;
3215   SCS.setToType(1, InnerSCS.getToType(1));
3216   SCS.Third = InnerSCS.Third;
3217   SCS.QualificationIncludesObjCLifetime
3218     = InnerSCS.QualificationIncludesObjCLifetime;
3219   SCS.setToType(2, InnerSCS.getToType(2));
3220   return true;
3221 }
3222 
3223 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3224                                               CXXConstructorDecl *Constructor,
3225                                               QualType Type) {
3226   const FunctionProtoType *CtorType =
3227       Constructor->getType()->getAs<FunctionProtoType>();
3228   if (CtorType->getNumParams() > 0) {
3229     QualType FirstArg = CtorType->getParamType(0);
3230     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3231       return true;
3232   }
3233   return false;
3234 }
3235 
3236 static OverloadingResult
3237 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3238                                        CXXRecordDecl *To,
3239                                        UserDefinedConversionSequence &User,
3240                                        OverloadCandidateSet &CandidateSet,
3241                                        bool AllowExplicit) {
3242   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3243   for (auto *D : S.LookupConstructors(To)) {
3244     auto Info = getConstructorInfo(D);
3245     if (!Info)
3246       continue;
3247 
3248     bool Usable = !Info.Constructor->isInvalidDecl() &&
3249                   S.isInitListConstructor(Info.Constructor) &&
3250                   (AllowExplicit || !Info.Constructor->isExplicit());
3251     if (Usable) {
3252       // If the first argument is (a reference to) the target type,
3253       // suppress conversions.
3254       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3255           S.Context, Info.Constructor, ToType);
3256       if (Info.ConstructorTmpl)
3257         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3258                                        /*ExplicitArgs*/ nullptr, From,
3259                                        CandidateSet, SuppressUserConversions,
3260                                        /*PartialOverloading*/ false,
3261                                        AllowExplicit);
3262       else
3263         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3264                                CandidateSet, SuppressUserConversions,
3265                                /*PartialOverloading*/ false, AllowExplicit);
3266     }
3267   }
3268 
3269   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3270 
3271   OverloadCandidateSet::iterator Best;
3272   switch (auto Result =
3273               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3274   case OR_Deleted:
3275   case OR_Success: {
3276     // Record the standard conversion we used and the conversion function.
3277     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3278     QualType ThisType = Constructor->getThisType();
3279     // Initializer lists don't have conversions as such.
3280     User.Before.setAsIdentityConversion();
3281     User.HadMultipleCandidates = HadMultipleCandidates;
3282     User.ConversionFunction = Constructor;
3283     User.FoundConversionFunction = Best->FoundDecl;
3284     User.After.setAsIdentityConversion();
3285     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3286     User.After.setAllToTypes(ToType);
3287     return Result;
3288   }
3289 
3290   case OR_No_Viable_Function:
3291     return OR_No_Viable_Function;
3292   case OR_Ambiguous:
3293     return OR_Ambiguous;
3294   }
3295 
3296   llvm_unreachable("Invalid OverloadResult!");
3297 }
3298 
3299 /// Determines whether there is a user-defined conversion sequence
3300 /// (C++ [over.ics.user]) that converts expression From to the type
3301 /// ToType. If such a conversion exists, User will contain the
3302 /// user-defined conversion sequence that performs such a conversion
3303 /// and this routine will return true. Otherwise, this routine returns
3304 /// false and User is unspecified.
3305 ///
3306 /// \param AllowExplicit  true if the conversion should consider C++0x
3307 /// "explicit" conversion functions as well as non-explicit conversion
3308 /// functions (C++0x [class.conv.fct]p2).
3309 ///
3310 /// \param AllowObjCConversionOnExplicit true if the conversion should
3311 /// allow an extra Objective-C pointer conversion on uses of explicit
3312 /// constructors. Requires \c AllowExplicit to also be set.
3313 static OverloadingResult
3314 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3315                         UserDefinedConversionSequence &User,
3316                         OverloadCandidateSet &CandidateSet,
3317                         bool AllowExplicit,
3318                         bool AllowObjCConversionOnExplicit) {
3319   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3320   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3321 
3322   // Whether we will only visit constructors.
3323   bool ConstructorsOnly = false;
3324 
3325   // If the type we are conversion to is a class type, enumerate its
3326   // constructors.
3327   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3328     // C++ [over.match.ctor]p1:
3329     //   When objects of class type are direct-initialized (8.5), or
3330     //   copy-initialized from an expression of the same or a
3331     //   derived class type (8.5), overload resolution selects the
3332     //   constructor. [...] For copy-initialization, the candidate
3333     //   functions are all the converting constructors (12.3.1) of
3334     //   that class. The argument list is the expression-list within
3335     //   the parentheses of the initializer.
3336     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3337         (From->getType()->getAs<RecordType>() &&
3338          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3339       ConstructorsOnly = true;
3340 
3341     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3342       // We're not going to find any constructors.
3343     } else if (CXXRecordDecl *ToRecordDecl
3344                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3345 
3346       Expr **Args = &From;
3347       unsigned NumArgs = 1;
3348       bool ListInitializing = false;
3349       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3350         // But first, see if there is an init-list-constructor that will work.
3351         OverloadingResult Result = IsInitializerListConstructorConversion(
3352             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3353         if (Result != OR_No_Viable_Function)
3354           return Result;
3355         // Never mind.
3356         CandidateSet.clear(
3357             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3358 
3359         // If we're list-initializing, we pass the individual elements as
3360         // arguments, not the entire list.
3361         Args = InitList->getInits();
3362         NumArgs = InitList->getNumInits();
3363         ListInitializing = true;
3364       }
3365 
3366       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3367         auto Info = getConstructorInfo(D);
3368         if (!Info)
3369           continue;
3370 
3371         bool Usable = !Info.Constructor->isInvalidDecl();
3372         if (ListInitializing)
3373           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3374         else
3375           Usable = Usable &&
3376                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3377         if (Usable) {
3378           bool SuppressUserConversions = !ConstructorsOnly;
3379           if (SuppressUserConversions && ListInitializing) {
3380             SuppressUserConversions = false;
3381             if (NumArgs == 1) {
3382               // If the first argument is (a reference to) the target type,
3383               // suppress conversions.
3384               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3385                   S.Context, Info.Constructor, ToType);
3386             }
3387           }
3388           if (Info.ConstructorTmpl)
3389             S.AddTemplateOverloadCandidate(
3390                 Info.ConstructorTmpl, Info.FoundDecl,
3391                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3392                 CandidateSet, SuppressUserConversions,
3393                 /*PartialOverloading*/ false, AllowExplicit);
3394           else
3395             // Allow one user-defined conversion when user specifies a
3396             // From->ToType conversion via an static cast (c-style, etc).
3397             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3398                                    llvm::makeArrayRef(Args, NumArgs),
3399                                    CandidateSet, SuppressUserConversions,
3400                                    /*PartialOverloading*/ false, AllowExplicit);
3401         }
3402       }
3403     }
3404   }
3405 
3406   // Enumerate conversion functions, if we're allowed to.
3407   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3408   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3409     // No conversion functions from incomplete types.
3410   } else if (const RecordType *FromRecordType =
3411                  From->getType()->getAs<RecordType>()) {
3412     if (CXXRecordDecl *FromRecordDecl
3413          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3414       // Add all of the conversion functions as candidates.
3415       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3416       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3417         DeclAccessPair FoundDecl = I.getPair();
3418         NamedDecl *D = FoundDecl.getDecl();
3419         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3420         if (isa<UsingShadowDecl>(D))
3421           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3422 
3423         CXXConversionDecl *Conv;
3424         FunctionTemplateDecl *ConvTemplate;
3425         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3426           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3427         else
3428           Conv = cast<CXXConversionDecl>(D);
3429 
3430         if (AllowExplicit || !Conv->isExplicit()) {
3431           if (ConvTemplate)
3432             S.AddTemplateConversionCandidate(
3433                 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3434                 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3435           else
3436             S.AddConversionCandidate(
3437                 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3438                 AllowObjCConversionOnExplicit, AllowExplicit);
3439         }
3440       }
3441     }
3442   }
3443 
3444   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3445 
3446   OverloadCandidateSet::iterator Best;
3447   switch (auto Result =
3448               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3449   case OR_Success:
3450   case OR_Deleted:
3451     // Record the standard conversion we used and the conversion function.
3452     if (CXXConstructorDecl *Constructor
3453           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3454       // C++ [over.ics.user]p1:
3455       //   If the user-defined conversion is specified by a
3456       //   constructor (12.3.1), the initial standard conversion
3457       //   sequence converts the source type to the type required by
3458       //   the argument of the constructor.
3459       //
3460       QualType ThisType = Constructor->getThisType();
3461       if (isa<InitListExpr>(From)) {
3462         // Initializer lists don't have conversions as such.
3463         User.Before.setAsIdentityConversion();
3464       } else {
3465         if (Best->Conversions[0].isEllipsis())
3466           User.EllipsisConversion = true;
3467         else {
3468           User.Before = Best->Conversions[0].Standard;
3469           User.EllipsisConversion = false;
3470         }
3471       }
3472       User.HadMultipleCandidates = HadMultipleCandidates;
3473       User.ConversionFunction = Constructor;
3474       User.FoundConversionFunction = Best->FoundDecl;
3475       User.After.setAsIdentityConversion();
3476       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3477       User.After.setAllToTypes(ToType);
3478       return Result;
3479     }
3480     if (CXXConversionDecl *Conversion
3481                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3482       // C++ [over.ics.user]p1:
3483       //
3484       //   [...] If the user-defined conversion is specified by a
3485       //   conversion function (12.3.2), the initial standard
3486       //   conversion sequence converts the source type to the
3487       //   implicit object parameter of the conversion function.
3488       User.Before = Best->Conversions[0].Standard;
3489       User.HadMultipleCandidates = HadMultipleCandidates;
3490       User.ConversionFunction = Conversion;
3491       User.FoundConversionFunction = Best->FoundDecl;
3492       User.EllipsisConversion = false;
3493 
3494       // C++ [over.ics.user]p2:
3495       //   The second standard conversion sequence converts the
3496       //   result of the user-defined conversion to the target type
3497       //   for the sequence. Since an implicit conversion sequence
3498       //   is an initialization, the special rules for
3499       //   initialization by user-defined conversion apply when
3500       //   selecting the best user-defined conversion for a
3501       //   user-defined conversion sequence (see 13.3.3 and
3502       //   13.3.3.1).
3503       User.After = Best->FinalConversion;
3504       return Result;
3505     }
3506     llvm_unreachable("Not a constructor or conversion function?");
3507 
3508   case OR_No_Viable_Function:
3509     return OR_No_Viable_Function;
3510 
3511   case OR_Ambiguous:
3512     return OR_Ambiguous;
3513   }
3514 
3515   llvm_unreachable("Invalid OverloadResult!");
3516 }
3517 
3518 bool
3519 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3520   ImplicitConversionSequence ICS;
3521   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3522                                     OverloadCandidateSet::CSK_Normal);
3523   OverloadingResult OvResult =
3524     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3525                             CandidateSet, false, false);
3526 
3527   if (!(OvResult == OR_Ambiguous ||
3528         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3529     return false;
3530 
3531   auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
3532   if (OvResult == OR_Ambiguous)
3533     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3534         << From->getType() << ToType << From->getSourceRange();
3535   else { // OR_No_Viable_Function && !CandidateSet.empty()
3536     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3537                              diag::err_typecheck_nonviable_condition_incomplete,
3538                              From->getType(), From->getSourceRange()))
3539       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3540           << false << From->getType() << From->getSourceRange() << ToType;
3541   }
3542 
3543   CandidateSet.NoteCandidates(
3544                               *this, From, Cands);
3545   return true;
3546 }
3547 
3548 /// Compare the user-defined conversion functions or constructors
3549 /// of two user-defined conversion sequences to determine whether any ordering
3550 /// is possible.
3551 static ImplicitConversionSequence::CompareKind
3552 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3553                            FunctionDecl *Function2) {
3554   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3555     return ImplicitConversionSequence::Indistinguishable;
3556 
3557   // Objective-C++:
3558   //   If both conversion functions are implicitly-declared conversions from
3559   //   a lambda closure type to a function pointer and a block pointer,
3560   //   respectively, always prefer the conversion to a function pointer,
3561   //   because the function pointer is more lightweight and is more likely
3562   //   to keep code working.
3563   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3564   if (!Conv1)
3565     return ImplicitConversionSequence::Indistinguishable;
3566 
3567   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3568   if (!Conv2)
3569     return ImplicitConversionSequence::Indistinguishable;
3570 
3571   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3572     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3573     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3574     if (Block1 != Block2)
3575       return Block1 ? ImplicitConversionSequence::Worse
3576                     : ImplicitConversionSequence::Better;
3577   }
3578 
3579   return ImplicitConversionSequence::Indistinguishable;
3580 }
3581 
3582 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3583     const ImplicitConversionSequence &ICS) {
3584   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3585          (ICS.isUserDefined() &&
3586           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3587 }
3588 
3589 /// CompareImplicitConversionSequences - Compare two implicit
3590 /// conversion sequences to determine whether one is better than the
3591 /// other or if they are indistinguishable (C++ 13.3.3.2).
3592 static ImplicitConversionSequence::CompareKind
3593 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3594                                    const ImplicitConversionSequence& ICS1,
3595                                    const ImplicitConversionSequence& ICS2)
3596 {
3597   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3598   // conversion sequences (as defined in 13.3.3.1)
3599   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3600   //      conversion sequence than a user-defined conversion sequence or
3601   //      an ellipsis conversion sequence, and
3602   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3603   //      conversion sequence than an ellipsis conversion sequence
3604   //      (13.3.3.1.3).
3605   //
3606   // C++0x [over.best.ics]p10:
3607   //   For the purpose of ranking implicit conversion sequences as
3608   //   described in 13.3.3.2, the ambiguous conversion sequence is
3609   //   treated as a user-defined sequence that is indistinguishable
3610   //   from any other user-defined conversion sequence.
3611 
3612   // String literal to 'char *' conversion has been deprecated in C++03. It has
3613   // been removed from C++11. We still accept this conversion, if it happens at
3614   // the best viable function. Otherwise, this conversion is considered worse
3615   // than ellipsis conversion. Consider this as an extension; this is not in the
3616   // standard. For example:
3617   //
3618   // int &f(...);    // #1
3619   // void f(char*);  // #2
3620   // void g() { int &r = f("foo"); }
3621   //
3622   // In C++03, we pick #2 as the best viable function.
3623   // In C++11, we pick #1 as the best viable function, because ellipsis
3624   // conversion is better than string-literal to char* conversion (since there
3625   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3626   // convert arguments, #2 would be the best viable function in C++11.
3627   // If the best viable function has this conversion, a warning will be issued
3628   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3629 
3630   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3631       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3632       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3633     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3634                ? ImplicitConversionSequence::Worse
3635                : ImplicitConversionSequence::Better;
3636 
3637   if (ICS1.getKindRank() < ICS2.getKindRank())
3638     return ImplicitConversionSequence::Better;
3639   if (ICS2.getKindRank() < ICS1.getKindRank())
3640     return ImplicitConversionSequence::Worse;
3641 
3642   // The following checks require both conversion sequences to be of
3643   // the same kind.
3644   if (ICS1.getKind() != ICS2.getKind())
3645     return ImplicitConversionSequence::Indistinguishable;
3646 
3647   ImplicitConversionSequence::CompareKind Result =
3648       ImplicitConversionSequence::Indistinguishable;
3649 
3650   // Two implicit conversion sequences of the same form are
3651   // indistinguishable conversion sequences unless one of the
3652   // following rules apply: (C++ 13.3.3.2p3):
3653 
3654   // List-initialization sequence L1 is a better conversion sequence than
3655   // list-initialization sequence L2 if:
3656   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3657   //   if not that,
3658   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3659   //   and N1 is smaller than N2.,
3660   // even if one of the other rules in this paragraph would otherwise apply.
3661   if (!ICS1.isBad()) {
3662     if (ICS1.isStdInitializerListElement() &&
3663         !ICS2.isStdInitializerListElement())
3664       return ImplicitConversionSequence::Better;
3665     if (!ICS1.isStdInitializerListElement() &&
3666         ICS2.isStdInitializerListElement())
3667       return ImplicitConversionSequence::Worse;
3668   }
3669 
3670   if (ICS1.isStandard())
3671     // Standard conversion sequence S1 is a better conversion sequence than
3672     // standard conversion sequence S2 if [...]
3673     Result = CompareStandardConversionSequences(S, Loc,
3674                                                 ICS1.Standard, ICS2.Standard);
3675   else if (ICS1.isUserDefined()) {
3676     // User-defined conversion sequence U1 is a better conversion
3677     // sequence than another user-defined conversion sequence U2 if
3678     // they contain the same user-defined conversion function or
3679     // constructor and if the second standard conversion sequence of
3680     // U1 is better than the second standard conversion sequence of
3681     // U2 (C++ 13.3.3.2p3).
3682     if (ICS1.UserDefined.ConversionFunction ==
3683           ICS2.UserDefined.ConversionFunction)
3684       Result = CompareStandardConversionSequences(S, Loc,
3685                                                   ICS1.UserDefined.After,
3686                                                   ICS2.UserDefined.After);
3687     else
3688       Result = compareConversionFunctions(S,
3689                                           ICS1.UserDefined.ConversionFunction,
3690                                           ICS2.UserDefined.ConversionFunction);
3691   }
3692 
3693   return Result;
3694 }
3695 
3696 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3697 // determine if one is a proper subset of the other.
3698 static ImplicitConversionSequence::CompareKind
3699 compareStandardConversionSubsets(ASTContext &Context,
3700                                  const StandardConversionSequence& SCS1,
3701                                  const StandardConversionSequence& SCS2) {
3702   ImplicitConversionSequence::CompareKind Result
3703     = ImplicitConversionSequence::Indistinguishable;
3704 
3705   // the identity conversion sequence is considered to be a subsequence of
3706   // any non-identity conversion sequence
3707   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3708     return ImplicitConversionSequence::Better;
3709   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3710     return ImplicitConversionSequence::Worse;
3711 
3712   if (SCS1.Second != SCS2.Second) {
3713     if (SCS1.Second == ICK_Identity)
3714       Result = ImplicitConversionSequence::Better;
3715     else if (SCS2.Second == ICK_Identity)
3716       Result = ImplicitConversionSequence::Worse;
3717     else
3718       return ImplicitConversionSequence::Indistinguishable;
3719   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3720     return ImplicitConversionSequence::Indistinguishable;
3721 
3722   if (SCS1.Third == SCS2.Third) {
3723     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3724                              : ImplicitConversionSequence::Indistinguishable;
3725   }
3726 
3727   if (SCS1.Third == ICK_Identity)
3728     return Result == ImplicitConversionSequence::Worse
3729              ? ImplicitConversionSequence::Indistinguishable
3730              : ImplicitConversionSequence::Better;
3731 
3732   if (SCS2.Third == ICK_Identity)
3733     return Result == ImplicitConversionSequence::Better
3734              ? ImplicitConversionSequence::Indistinguishable
3735              : ImplicitConversionSequence::Worse;
3736 
3737   return ImplicitConversionSequence::Indistinguishable;
3738 }
3739 
3740 /// Determine whether one of the given reference bindings is better
3741 /// than the other based on what kind of bindings they are.
3742 static bool
3743 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3744                              const StandardConversionSequence &SCS2) {
3745   // C++0x [over.ics.rank]p3b4:
3746   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3747   //      implicit object parameter of a non-static member function declared
3748   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3749   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3750   //      lvalue reference to a function lvalue and S2 binds an rvalue
3751   //      reference*.
3752   //
3753   // FIXME: Rvalue references. We're going rogue with the above edits,
3754   // because the semantics in the current C++0x working paper (N3225 at the
3755   // time of this writing) break the standard definition of std::forward
3756   // and std::reference_wrapper when dealing with references to functions.
3757   // Proposed wording changes submitted to CWG for consideration.
3758   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3759       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3760     return false;
3761 
3762   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3763           SCS2.IsLvalueReference) ||
3764          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3765           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3766 }
3767 
3768 enum class FixedEnumPromotion {
3769   None,
3770   ToUnderlyingType,
3771   ToPromotedUnderlyingType
3772 };
3773 
3774 /// Returns kind of fixed enum promotion the \a SCS uses.
3775 static FixedEnumPromotion
3776 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3777 
3778   if (SCS.Second != ICK_Integral_Promotion)
3779     return FixedEnumPromotion::None;
3780 
3781   QualType FromType = SCS.getFromType();
3782   if (!FromType->isEnumeralType())
3783     return FixedEnumPromotion::None;
3784 
3785   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3786   if (!Enum->isFixed())
3787     return FixedEnumPromotion::None;
3788 
3789   QualType UnderlyingType = Enum->getIntegerType();
3790   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3791     return FixedEnumPromotion::ToUnderlyingType;
3792 
3793   return FixedEnumPromotion::ToPromotedUnderlyingType;
3794 }
3795 
3796 /// CompareStandardConversionSequences - Compare two standard
3797 /// conversion sequences to determine whether one is better than the
3798 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3799 static ImplicitConversionSequence::CompareKind
3800 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3801                                    const StandardConversionSequence& SCS1,
3802                                    const StandardConversionSequence& SCS2)
3803 {
3804   // Standard conversion sequence S1 is a better conversion sequence
3805   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3806 
3807   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3808   //     sequences in the canonical form defined by 13.3.3.1.1,
3809   //     excluding any Lvalue Transformation; the identity conversion
3810   //     sequence is considered to be a subsequence of any
3811   //     non-identity conversion sequence) or, if not that,
3812   if (ImplicitConversionSequence::CompareKind CK
3813         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3814     return CK;
3815 
3816   //  -- the rank of S1 is better than the rank of S2 (by the rules
3817   //     defined below), or, if not that,
3818   ImplicitConversionRank Rank1 = SCS1.getRank();
3819   ImplicitConversionRank Rank2 = SCS2.getRank();
3820   if (Rank1 < Rank2)
3821     return ImplicitConversionSequence::Better;
3822   else if (Rank2 < Rank1)
3823     return ImplicitConversionSequence::Worse;
3824 
3825   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3826   // are indistinguishable unless one of the following rules
3827   // applies:
3828 
3829   //   A conversion that is not a conversion of a pointer, or
3830   //   pointer to member, to bool is better than another conversion
3831   //   that is such a conversion.
3832   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3833     return SCS2.isPointerConversionToBool()
3834              ? ImplicitConversionSequence::Better
3835              : ImplicitConversionSequence::Worse;
3836 
3837   // C++14 [over.ics.rank]p4b2:
3838   // This is retroactively applied to C++11 by CWG 1601.
3839   //
3840   //   A conversion that promotes an enumeration whose underlying type is fixed
3841   //   to its underlying type is better than one that promotes to the promoted
3842   //   underlying type, if the two are different.
3843   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3844   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3845   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3846       FEP1 != FEP2)
3847     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3848                ? ImplicitConversionSequence::Better
3849                : ImplicitConversionSequence::Worse;
3850 
3851   // C++ [over.ics.rank]p4b2:
3852   //
3853   //   If class B is derived directly or indirectly from class A,
3854   //   conversion of B* to A* is better than conversion of B* to
3855   //   void*, and conversion of A* to void* is better than conversion
3856   //   of B* to void*.
3857   bool SCS1ConvertsToVoid
3858     = SCS1.isPointerConversionToVoidPointer(S.Context);
3859   bool SCS2ConvertsToVoid
3860     = SCS2.isPointerConversionToVoidPointer(S.Context);
3861   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3862     // Exactly one of the conversion sequences is a conversion to
3863     // a void pointer; it's the worse conversion.
3864     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3865                               : ImplicitConversionSequence::Worse;
3866   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3867     // Neither conversion sequence converts to a void pointer; compare
3868     // their derived-to-base conversions.
3869     if (ImplicitConversionSequence::CompareKind DerivedCK
3870           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3871       return DerivedCK;
3872   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3873              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3874     // Both conversion sequences are conversions to void
3875     // pointers. Compare the source types to determine if there's an
3876     // inheritance relationship in their sources.
3877     QualType FromType1 = SCS1.getFromType();
3878     QualType FromType2 = SCS2.getFromType();
3879 
3880     // Adjust the types we're converting from via the array-to-pointer
3881     // conversion, if we need to.
3882     if (SCS1.First == ICK_Array_To_Pointer)
3883       FromType1 = S.Context.getArrayDecayedType(FromType1);
3884     if (SCS2.First == ICK_Array_To_Pointer)
3885       FromType2 = S.Context.getArrayDecayedType(FromType2);
3886 
3887     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3888     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3889 
3890     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3891       return ImplicitConversionSequence::Better;
3892     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3893       return ImplicitConversionSequence::Worse;
3894 
3895     // Objective-C++: If one interface is more specific than the
3896     // other, it is the better one.
3897     const ObjCObjectPointerType* FromObjCPtr1
3898       = FromType1->getAs<ObjCObjectPointerType>();
3899     const ObjCObjectPointerType* FromObjCPtr2
3900       = FromType2->getAs<ObjCObjectPointerType>();
3901     if (FromObjCPtr1 && FromObjCPtr2) {
3902       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3903                                                           FromObjCPtr2);
3904       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3905                                                            FromObjCPtr1);
3906       if (AssignLeft != AssignRight) {
3907         return AssignLeft? ImplicitConversionSequence::Better
3908                          : ImplicitConversionSequence::Worse;
3909       }
3910     }
3911   }
3912 
3913   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3914   // bullet 3).
3915   if (ImplicitConversionSequence::CompareKind QualCK
3916         = CompareQualificationConversions(S, SCS1, SCS2))
3917     return QualCK;
3918 
3919   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3920     // Check for a better reference binding based on the kind of bindings.
3921     if (isBetterReferenceBindingKind(SCS1, SCS2))
3922       return ImplicitConversionSequence::Better;
3923     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3924       return ImplicitConversionSequence::Worse;
3925 
3926     // C++ [over.ics.rank]p3b4:
3927     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3928     //      which the references refer are the same type except for
3929     //      top-level cv-qualifiers, and the type to which the reference
3930     //      initialized by S2 refers is more cv-qualified than the type
3931     //      to which the reference initialized by S1 refers.
3932     QualType T1 = SCS1.getToType(2);
3933     QualType T2 = SCS2.getToType(2);
3934     T1 = S.Context.getCanonicalType(T1);
3935     T2 = S.Context.getCanonicalType(T2);
3936     Qualifiers T1Quals, T2Quals;
3937     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3938     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3939     if (UnqualT1 == UnqualT2) {
3940       // Objective-C++ ARC: If the references refer to objects with different
3941       // lifetimes, prefer bindings that don't change lifetime.
3942       if (SCS1.ObjCLifetimeConversionBinding !=
3943                                           SCS2.ObjCLifetimeConversionBinding) {
3944         return SCS1.ObjCLifetimeConversionBinding
3945                                            ? ImplicitConversionSequence::Worse
3946                                            : ImplicitConversionSequence::Better;
3947       }
3948 
3949       // If the type is an array type, promote the element qualifiers to the
3950       // type for comparison.
3951       if (isa<ArrayType>(T1) && T1Quals)
3952         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3953       if (isa<ArrayType>(T2) && T2Quals)
3954         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3955       if (T2.isMoreQualifiedThan(T1))
3956         return ImplicitConversionSequence::Better;
3957       else if (T1.isMoreQualifiedThan(T2))
3958         return ImplicitConversionSequence::Worse;
3959     }
3960   }
3961 
3962   // In Microsoft mode, prefer an integral conversion to a
3963   // floating-to-integral conversion if the integral conversion
3964   // is between types of the same size.
3965   // For example:
3966   // void f(float);
3967   // void f(int);
3968   // int main {
3969   //    long a;
3970   //    f(a);
3971   // }
3972   // Here, MSVC will call f(int) instead of generating a compile error
3973   // as clang will do in standard mode.
3974   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3975       SCS2.Second == ICK_Floating_Integral &&
3976       S.Context.getTypeSize(SCS1.getFromType()) ==
3977           S.Context.getTypeSize(SCS1.getToType(2)))
3978     return ImplicitConversionSequence::Better;
3979 
3980   // Prefer a compatible vector conversion over a lax vector conversion
3981   // For example:
3982   //
3983   // typedef float __v4sf __attribute__((__vector_size__(16)));
3984   // void f(vector float);
3985   // void f(vector signed int);
3986   // int main() {
3987   //   __v4sf a;
3988   //   f(a);
3989   // }
3990   // Here, we'd like to choose f(vector float) and not
3991   // report an ambiguous call error
3992   if (SCS1.Second == ICK_Vector_Conversion &&
3993       SCS2.Second == ICK_Vector_Conversion) {
3994     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3995         SCS1.getFromType(), SCS1.getToType(2));
3996     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3997         SCS2.getFromType(), SCS2.getToType(2));
3998 
3999     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4000       return SCS1IsCompatibleVectorConversion
4001                  ? ImplicitConversionSequence::Better
4002                  : ImplicitConversionSequence::Worse;
4003   }
4004 
4005   return ImplicitConversionSequence::Indistinguishable;
4006 }
4007 
4008 /// CompareQualificationConversions - Compares two standard conversion
4009 /// sequences to determine whether they can be ranked based on their
4010 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4011 static ImplicitConversionSequence::CompareKind
4012 CompareQualificationConversions(Sema &S,
4013                                 const StandardConversionSequence& SCS1,
4014                                 const StandardConversionSequence& SCS2) {
4015   // C++ 13.3.3.2p3:
4016   //  -- S1 and S2 differ only in their qualification conversion and
4017   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4018   //     cv-qualification signature of type T1 is a proper subset of
4019   //     the cv-qualification signature of type T2, and S1 is not the
4020   //     deprecated string literal array-to-pointer conversion (4.2).
4021   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4022       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4023     return ImplicitConversionSequence::Indistinguishable;
4024 
4025   // FIXME: the example in the standard doesn't use a qualification
4026   // conversion (!)
4027   QualType T1 = SCS1.getToType(2);
4028   QualType T2 = SCS2.getToType(2);
4029   T1 = S.Context.getCanonicalType(T1);
4030   T2 = S.Context.getCanonicalType(T2);
4031   Qualifiers T1Quals, T2Quals;
4032   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4033   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4034 
4035   // If the types are the same, we won't learn anything by unwrapped
4036   // them.
4037   if (UnqualT1 == UnqualT2)
4038     return ImplicitConversionSequence::Indistinguishable;
4039 
4040   // If the type is an array type, promote the element qualifiers to the type
4041   // for comparison.
4042   if (isa<ArrayType>(T1) && T1Quals)
4043     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4044   if (isa<ArrayType>(T2) && T2Quals)
4045     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4046 
4047   ImplicitConversionSequence::CompareKind Result
4048     = ImplicitConversionSequence::Indistinguishable;
4049 
4050   // Objective-C++ ARC:
4051   //   Prefer qualification conversions not involving a change in lifetime
4052   //   to qualification conversions that do not change lifetime.
4053   if (SCS1.QualificationIncludesObjCLifetime !=
4054                                       SCS2.QualificationIncludesObjCLifetime) {
4055     Result = SCS1.QualificationIncludesObjCLifetime
4056                ? ImplicitConversionSequence::Worse
4057                : ImplicitConversionSequence::Better;
4058   }
4059 
4060   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4061     // Within each iteration of the loop, we check the qualifiers to
4062     // determine if this still looks like a qualification
4063     // conversion. Then, if all is well, we unwrap one more level of
4064     // pointers or pointers-to-members and do it all again
4065     // until there are no more pointers or pointers-to-members left
4066     // to unwrap. This essentially mimics what
4067     // IsQualificationConversion does, but here we're checking for a
4068     // strict subset of qualifiers.
4069     if (T1.getQualifiers().withoutObjCLifetime() ==
4070         T2.getQualifiers().withoutObjCLifetime())
4071       // The qualifiers are the same, so this doesn't tell us anything
4072       // about how the sequences rank.
4073       // ObjC ownership quals are omitted above as they interfere with
4074       // the ARC overload rule.
4075       ;
4076     else if (T2.isMoreQualifiedThan(T1)) {
4077       // T1 has fewer qualifiers, so it could be the better sequence.
4078       if (Result == ImplicitConversionSequence::Worse)
4079         // Neither has qualifiers that are a subset of the other's
4080         // qualifiers.
4081         return ImplicitConversionSequence::Indistinguishable;
4082 
4083       Result = ImplicitConversionSequence::Better;
4084     } else if (T1.isMoreQualifiedThan(T2)) {
4085       // T2 has fewer qualifiers, so it could be the better sequence.
4086       if (Result == ImplicitConversionSequence::Better)
4087         // Neither has qualifiers that are a subset of the other's
4088         // qualifiers.
4089         return ImplicitConversionSequence::Indistinguishable;
4090 
4091       Result = ImplicitConversionSequence::Worse;
4092     } else {
4093       // Qualifiers are disjoint.
4094       return ImplicitConversionSequence::Indistinguishable;
4095     }
4096 
4097     // If the types after this point are equivalent, we're done.
4098     if (S.Context.hasSameUnqualifiedType(T1, T2))
4099       break;
4100   }
4101 
4102   // Check that the winning standard conversion sequence isn't using
4103   // the deprecated string literal array to pointer conversion.
4104   switch (Result) {
4105   case ImplicitConversionSequence::Better:
4106     if (SCS1.DeprecatedStringLiteralToCharPtr)
4107       Result = ImplicitConversionSequence::Indistinguishable;
4108     break;
4109 
4110   case ImplicitConversionSequence::Indistinguishable:
4111     break;
4112 
4113   case ImplicitConversionSequence::Worse:
4114     if (SCS2.DeprecatedStringLiteralToCharPtr)
4115       Result = ImplicitConversionSequence::Indistinguishable;
4116     break;
4117   }
4118 
4119   return Result;
4120 }
4121 
4122 /// CompareDerivedToBaseConversions - Compares two standard conversion
4123 /// sequences to determine whether they can be ranked based on their
4124 /// various kinds of derived-to-base conversions (C++
4125 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4126 /// conversions between Objective-C interface types.
4127 static ImplicitConversionSequence::CompareKind
4128 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4129                                 const StandardConversionSequence& SCS1,
4130                                 const StandardConversionSequence& SCS2) {
4131   QualType FromType1 = SCS1.getFromType();
4132   QualType ToType1 = SCS1.getToType(1);
4133   QualType FromType2 = SCS2.getFromType();
4134   QualType ToType2 = SCS2.getToType(1);
4135 
4136   // Adjust the types we're converting from via the array-to-pointer
4137   // conversion, if we need to.
4138   if (SCS1.First == ICK_Array_To_Pointer)
4139     FromType1 = S.Context.getArrayDecayedType(FromType1);
4140   if (SCS2.First == ICK_Array_To_Pointer)
4141     FromType2 = S.Context.getArrayDecayedType(FromType2);
4142 
4143   // Canonicalize all of the types.
4144   FromType1 = S.Context.getCanonicalType(FromType1);
4145   ToType1 = S.Context.getCanonicalType(ToType1);
4146   FromType2 = S.Context.getCanonicalType(FromType2);
4147   ToType2 = S.Context.getCanonicalType(ToType2);
4148 
4149   // C++ [over.ics.rank]p4b3:
4150   //
4151   //   If class B is derived directly or indirectly from class A and
4152   //   class C is derived directly or indirectly from B,
4153   //
4154   // Compare based on pointer conversions.
4155   if (SCS1.Second == ICK_Pointer_Conversion &&
4156       SCS2.Second == ICK_Pointer_Conversion &&
4157       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4158       FromType1->isPointerType() && FromType2->isPointerType() &&
4159       ToType1->isPointerType() && ToType2->isPointerType()) {
4160     QualType FromPointee1 =
4161         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4162     QualType ToPointee1 =
4163         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4164     QualType FromPointee2 =
4165         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4166     QualType ToPointee2 =
4167         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4168 
4169     //   -- conversion of C* to B* is better than conversion of C* to A*,
4170     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4171       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4172         return ImplicitConversionSequence::Better;
4173       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4174         return ImplicitConversionSequence::Worse;
4175     }
4176 
4177     //   -- conversion of B* to A* is better than conversion of C* to A*,
4178     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4179       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4180         return ImplicitConversionSequence::Better;
4181       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4182         return ImplicitConversionSequence::Worse;
4183     }
4184   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4185              SCS2.Second == ICK_Pointer_Conversion) {
4186     const ObjCObjectPointerType *FromPtr1
4187       = FromType1->getAs<ObjCObjectPointerType>();
4188     const ObjCObjectPointerType *FromPtr2
4189       = FromType2->getAs<ObjCObjectPointerType>();
4190     const ObjCObjectPointerType *ToPtr1
4191       = ToType1->getAs<ObjCObjectPointerType>();
4192     const ObjCObjectPointerType *ToPtr2
4193       = ToType2->getAs<ObjCObjectPointerType>();
4194 
4195     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4196       // Apply the same conversion ranking rules for Objective-C pointer types
4197       // that we do for C++ pointers to class types. However, we employ the
4198       // Objective-C pseudo-subtyping relationship used for assignment of
4199       // Objective-C pointer types.
4200       bool FromAssignLeft
4201         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4202       bool FromAssignRight
4203         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4204       bool ToAssignLeft
4205         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4206       bool ToAssignRight
4207         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4208 
4209       // A conversion to an a non-id object pointer type or qualified 'id'
4210       // type is better than a conversion to 'id'.
4211       if (ToPtr1->isObjCIdType() &&
4212           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4213         return ImplicitConversionSequence::Worse;
4214       if (ToPtr2->isObjCIdType() &&
4215           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4216         return ImplicitConversionSequence::Better;
4217 
4218       // A conversion to a non-id object pointer type is better than a
4219       // conversion to a qualified 'id' type
4220       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4221         return ImplicitConversionSequence::Worse;
4222       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4223         return ImplicitConversionSequence::Better;
4224 
4225       // A conversion to an a non-Class object pointer type or qualified 'Class'
4226       // type is better than a conversion to 'Class'.
4227       if (ToPtr1->isObjCClassType() &&
4228           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4229         return ImplicitConversionSequence::Worse;
4230       if (ToPtr2->isObjCClassType() &&
4231           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4232         return ImplicitConversionSequence::Better;
4233 
4234       // A conversion to a non-Class object pointer type is better than a
4235       // conversion to a qualified 'Class' type.
4236       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4237         return ImplicitConversionSequence::Worse;
4238       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4239         return ImplicitConversionSequence::Better;
4240 
4241       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4242       if (S.Context.hasSameType(FromType1, FromType2) &&
4243           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4244           (ToAssignLeft != ToAssignRight)) {
4245         if (FromPtr1->isSpecialized()) {
4246           // "conversion of B<A> * to B * is better than conversion of B * to
4247           // C *.
4248           bool IsFirstSame =
4249               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4250           bool IsSecondSame =
4251               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4252           if (IsFirstSame) {
4253             if (!IsSecondSame)
4254               return ImplicitConversionSequence::Better;
4255           } else if (IsSecondSame)
4256             return ImplicitConversionSequence::Worse;
4257         }
4258         return ToAssignLeft? ImplicitConversionSequence::Worse
4259                            : ImplicitConversionSequence::Better;
4260       }
4261 
4262       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4263       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4264           (FromAssignLeft != FromAssignRight))
4265         return FromAssignLeft? ImplicitConversionSequence::Better
4266         : ImplicitConversionSequence::Worse;
4267     }
4268   }
4269 
4270   // Ranking of member-pointer types.
4271   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4272       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4273       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4274     const MemberPointerType * FromMemPointer1 =
4275                                         FromType1->getAs<MemberPointerType>();
4276     const MemberPointerType * ToMemPointer1 =
4277                                           ToType1->getAs<MemberPointerType>();
4278     const MemberPointerType * FromMemPointer2 =
4279                                           FromType2->getAs<MemberPointerType>();
4280     const MemberPointerType * ToMemPointer2 =
4281                                           ToType2->getAs<MemberPointerType>();
4282     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4283     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4284     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4285     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4286     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4287     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4288     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4289     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4290     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4291     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4292       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4293         return ImplicitConversionSequence::Worse;
4294       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4295         return ImplicitConversionSequence::Better;
4296     }
4297     // conversion of B::* to C::* is better than conversion of A::* to C::*
4298     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4299       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4300         return ImplicitConversionSequence::Better;
4301       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4302         return ImplicitConversionSequence::Worse;
4303     }
4304   }
4305 
4306   if (SCS1.Second == ICK_Derived_To_Base) {
4307     //   -- conversion of C to B is better than conversion of C to A,
4308     //   -- binding of an expression of type C to a reference of type
4309     //      B& is better than binding an expression of type C to a
4310     //      reference of type A&,
4311     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4312         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4313       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4314         return ImplicitConversionSequence::Better;
4315       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4316         return ImplicitConversionSequence::Worse;
4317     }
4318 
4319     //   -- conversion of B to A is better than conversion of C to A.
4320     //   -- binding of an expression of type B to a reference of type
4321     //      A& is better than binding an expression of type C to a
4322     //      reference of type A&,
4323     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4324         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4325       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4326         return ImplicitConversionSequence::Better;
4327       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4328         return ImplicitConversionSequence::Worse;
4329     }
4330   }
4331 
4332   return ImplicitConversionSequence::Indistinguishable;
4333 }
4334 
4335 /// Determine whether the given type is valid, e.g., it is not an invalid
4336 /// C++ class.
4337 static bool isTypeValid(QualType T) {
4338   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4339     return !Record->isInvalidDecl();
4340 
4341   return true;
4342 }
4343 
4344 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4345 /// determine whether they are reference-related,
4346 /// reference-compatible, reference-compatible with added
4347 /// qualification, or incompatible, for use in C++ initialization by
4348 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4349 /// type, and the first type (T1) is the pointee type of the reference
4350 /// type being initialized.
4351 Sema::ReferenceCompareResult
4352 Sema::CompareReferenceRelationship(SourceLocation Loc,
4353                                    QualType OrigT1, QualType OrigT2,
4354                                    bool &DerivedToBase,
4355                                    bool &ObjCConversion,
4356                                    bool &ObjCLifetimeConversion) {
4357   assert(!OrigT1->isReferenceType() &&
4358     "T1 must be the pointee type of the reference type");
4359   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4360 
4361   QualType T1 = Context.getCanonicalType(OrigT1);
4362   QualType T2 = Context.getCanonicalType(OrigT2);
4363   Qualifiers T1Quals, T2Quals;
4364   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4365   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4366 
4367   // C++ [dcl.init.ref]p4:
4368   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4369   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4370   //   T1 is a base class of T2.
4371   DerivedToBase = false;
4372   ObjCConversion = false;
4373   ObjCLifetimeConversion = false;
4374   QualType ConvertedT2;
4375   if (UnqualT1 == UnqualT2) {
4376     // Nothing to do.
4377   } else if (isCompleteType(Loc, OrigT2) &&
4378              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4379              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4380     DerivedToBase = true;
4381   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4382            UnqualT2->isObjCObjectOrInterfaceType() &&
4383            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4384     ObjCConversion = true;
4385   else if (UnqualT2->isFunctionType() &&
4386            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4387     // C++1z [dcl.init.ref]p4:
4388     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4389     //   function" and T1 is "function"
4390     //
4391     // We extend this to also apply to 'noreturn', so allow any function
4392     // conversion between function types.
4393     return Ref_Compatible;
4394   else
4395     return Ref_Incompatible;
4396 
4397   // At this point, we know that T1 and T2 are reference-related (at
4398   // least).
4399 
4400   // If the type is an array type, promote the element qualifiers to the type
4401   // for comparison.
4402   if (isa<ArrayType>(T1) && T1Quals)
4403     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4404   if (isa<ArrayType>(T2) && T2Quals)
4405     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4406 
4407   // C++ [dcl.init.ref]p4:
4408   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4409   //   reference-related to T2 and cv1 is the same cv-qualification
4410   //   as, or greater cv-qualification than, cv2. For purposes of
4411   //   overload resolution, cases for which cv1 is greater
4412   //   cv-qualification than cv2 are identified as
4413   //   reference-compatible with added qualification (see 13.3.3.2).
4414   //
4415   // Note that we also require equivalence of Objective-C GC and address-space
4416   // qualifiers when performing these computations, so that e.g., an int in
4417   // address space 1 is not reference-compatible with an int in address
4418   // space 2.
4419   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4420       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4421     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4422       ObjCLifetimeConversion = true;
4423 
4424     T1Quals.removeObjCLifetime();
4425     T2Quals.removeObjCLifetime();
4426   }
4427 
4428   // MS compiler ignores __unaligned qualifier for references; do the same.
4429   T1Quals.removeUnaligned();
4430   T2Quals.removeUnaligned();
4431 
4432   if (T1Quals.compatiblyIncludes(T2Quals))
4433     return Ref_Compatible;
4434   else
4435     return Ref_Related;
4436 }
4437 
4438 /// Look for a user-defined conversion to a value reference-compatible
4439 ///        with DeclType. Return true if something definite is found.
4440 static bool
4441 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4442                          QualType DeclType, SourceLocation DeclLoc,
4443                          Expr *Init, QualType T2, bool AllowRvalues,
4444                          bool AllowExplicit) {
4445   assert(T2->isRecordType() && "Can only find conversions of record types.");
4446   CXXRecordDecl *T2RecordDecl
4447     = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4448 
4449   OverloadCandidateSet CandidateSet(
4450       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4451   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4452   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4453     NamedDecl *D = *I;
4454     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4455     if (isa<UsingShadowDecl>(D))
4456       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4457 
4458     FunctionTemplateDecl *ConvTemplate
4459       = dyn_cast<FunctionTemplateDecl>(D);
4460     CXXConversionDecl *Conv;
4461     if (ConvTemplate)
4462       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4463     else
4464       Conv = cast<CXXConversionDecl>(D);
4465 
4466     // If this is an explicit conversion, and we're not allowed to consider
4467     // explicit conversions, skip it.
4468     if (!AllowExplicit && Conv->isExplicit())
4469       continue;
4470 
4471     if (AllowRvalues) {
4472       bool DerivedToBase = false;
4473       bool ObjCConversion = false;
4474       bool ObjCLifetimeConversion = false;
4475 
4476       // If we are initializing an rvalue reference, don't permit conversion
4477       // functions that return lvalues.
4478       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4479         const ReferenceType *RefType
4480           = Conv->getConversionType()->getAs<LValueReferenceType>();
4481         if (RefType && !RefType->getPointeeType()->isFunctionType())
4482           continue;
4483       }
4484 
4485       if (!ConvTemplate &&
4486           S.CompareReferenceRelationship(
4487             DeclLoc,
4488             Conv->getConversionType().getNonReferenceType()
4489               .getUnqualifiedType(),
4490             DeclType.getNonReferenceType().getUnqualifiedType(),
4491             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4492           Sema::Ref_Incompatible)
4493         continue;
4494     } else {
4495       // If the conversion function doesn't return a reference type,
4496       // it can't be considered for this conversion. An rvalue reference
4497       // is only acceptable if its referencee is a function type.
4498 
4499       const ReferenceType *RefType =
4500         Conv->getConversionType()->getAs<ReferenceType>();
4501       if (!RefType ||
4502           (!RefType->isLValueReferenceType() &&
4503            !RefType->getPointeeType()->isFunctionType()))
4504         continue;
4505     }
4506 
4507     if (ConvTemplate)
4508       S.AddTemplateConversionCandidate(
4509           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4510           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4511     else
4512       S.AddConversionCandidate(
4513           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4514           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4515   }
4516 
4517   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4518 
4519   OverloadCandidateSet::iterator Best;
4520   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4521   case OR_Success:
4522     // C++ [over.ics.ref]p1:
4523     //
4524     //   [...] If the parameter binds directly to the result of
4525     //   applying a conversion function to the argument
4526     //   expression, the implicit conversion sequence is a
4527     //   user-defined conversion sequence (13.3.3.1.2), with the
4528     //   second standard conversion sequence either an identity
4529     //   conversion or, if the conversion function returns an
4530     //   entity of a type that is a derived class of the parameter
4531     //   type, a derived-to-base Conversion.
4532     if (!Best->FinalConversion.DirectBinding)
4533       return false;
4534 
4535     ICS.setUserDefined();
4536     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4537     ICS.UserDefined.After = Best->FinalConversion;
4538     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4539     ICS.UserDefined.ConversionFunction = Best->Function;
4540     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4541     ICS.UserDefined.EllipsisConversion = false;
4542     assert(ICS.UserDefined.After.ReferenceBinding &&
4543            ICS.UserDefined.After.DirectBinding &&
4544            "Expected a direct reference binding!");
4545     return true;
4546 
4547   case OR_Ambiguous:
4548     ICS.setAmbiguous();
4549     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4550          Cand != CandidateSet.end(); ++Cand)
4551       if (Cand->Viable)
4552         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4553     return true;
4554 
4555   case OR_No_Viable_Function:
4556   case OR_Deleted:
4557     // There was no suitable conversion, or we found a deleted
4558     // conversion; continue with other checks.
4559     return false;
4560   }
4561 
4562   llvm_unreachable("Invalid OverloadResult!");
4563 }
4564 
4565 /// Compute an implicit conversion sequence for reference
4566 /// initialization.
4567 static ImplicitConversionSequence
4568 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4569                  SourceLocation DeclLoc,
4570                  bool SuppressUserConversions,
4571                  bool AllowExplicit) {
4572   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4573 
4574   // Most paths end in a failed conversion.
4575   ImplicitConversionSequence ICS;
4576   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4577 
4578   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4579   QualType T2 = Init->getType();
4580 
4581   // If the initializer is the address of an overloaded function, try
4582   // to resolve the overloaded function. If all goes well, T2 is the
4583   // type of the resulting function.
4584   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4585     DeclAccessPair Found;
4586     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4587                                                                 false, Found))
4588       T2 = Fn->getType();
4589   }
4590 
4591   // Compute some basic properties of the types and the initializer.
4592   bool isRValRef = DeclType->isRValueReferenceType();
4593   bool DerivedToBase = false;
4594   bool ObjCConversion = false;
4595   bool ObjCLifetimeConversion = false;
4596   Expr::Classification InitCategory = Init->Classify(S.Context);
4597   Sema::ReferenceCompareResult RefRelationship
4598     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4599                                      ObjCConversion, ObjCLifetimeConversion);
4600 
4601 
4602   // C++0x [dcl.init.ref]p5:
4603   //   A reference to type "cv1 T1" is initialized by an expression
4604   //   of type "cv2 T2" as follows:
4605 
4606   //     -- If reference is an lvalue reference and the initializer expression
4607   if (!isRValRef) {
4608     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4609     //        reference-compatible with "cv2 T2," or
4610     //
4611     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4612     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4613       // C++ [over.ics.ref]p1:
4614       //   When a parameter of reference type binds directly (8.5.3)
4615       //   to an argument expression, the implicit conversion sequence
4616       //   is the identity conversion, unless the argument expression
4617       //   has a type that is a derived class of the parameter type,
4618       //   in which case the implicit conversion sequence is a
4619       //   derived-to-base Conversion (13.3.3.1).
4620       ICS.setStandard();
4621       ICS.Standard.First = ICK_Identity;
4622       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4623                          : ObjCConversion? ICK_Compatible_Conversion
4624                          : ICK_Identity;
4625       ICS.Standard.Third = ICK_Identity;
4626       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4627       ICS.Standard.setToType(0, T2);
4628       ICS.Standard.setToType(1, T1);
4629       ICS.Standard.setToType(2, T1);
4630       ICS.Standard.ReferenceBinding = true;
4631       ICS.Standard.DirectBinding = true;
4632       ICS.Standard.IsLvalueReference = !isRValRef;
4633       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4634       ICS.Standard.BindsToRvalue = false;
4635       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4637       ICS.Standard.CopyConstructor = nullptr;
4638       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4639 
4640       // Nothing more to do: the inaccessibility/ambiguity check for
4641       // derived-to-base conversions is suppressed when we're
4642       // computing the implicit conversion sequence (C++
4643       // [over.best.ics]p2).
4644       return ICS;
4645     }
4646 
4647     //       -- has a class type (i.e., T2 is a class type), where T1 is
4648     //          not reference-related to T2, and can be implicitly
4649     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4650     //          is reference-compatible with "cv3 T3" 92) (this
4651     //          conversion is selected by enumerating the applicable
4652     //          conversion functions (13.3.1.6) and choosing the best
4653     //          one through overload resolution (13.3)),
4654     if (!SuppressUserConversions && T2->isRecordType() &&
4655         S.isCompleteType(DeclLoc, T2) &&
4656         RefRelationship == Sema::Ref_Incompatible) {
4657       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4658                                    Init, T2, /*AllowRvalues=*/false,
4659                                    AllowExplicit))
4660         return ICS;
4661     }
4662   }
4663 
4664   //     -- Otherwise, the reference shall be an lvalue reference to a
4665   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4666   //        shall be an rvalue reference.
4667   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4668     return ICS;
4669 
4670   //       -- If the initializer expression
4671   //
4672   //            -- is an xvalue, class prvalue, array prvalue or function
4673   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4674   if (RefRelationship == Sema::Ref_Compatible &&
4675       (InitCategory.isXValue() ||
4676        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4677        (InitCategory.isLValue() && T2->isFunctionType()))) {
4678     ICS.setStandard();
4679     ICS.Standard.First = ICK_Identity;
4680     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4681                       : ObjCConversion? ICK_Compatible_Conversion
4682                       : ICK_Identity;
4683     ICS.Standard.Third = ICK_Identity;
4684     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4685     ICS.Standard.setToType(0, T2);
4686     ICS.Standard.setToType(1, T1);
4687     ICS.Standard.setToType(2, T1);
4688     ICS.Standard.ReferenceBinding = true;
4689     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4690     // binding unless we're binding to a class prvalue.
4691     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4692     // allow the use of rvalue references in C++98/03 for the benefit of
4693     // standard library implementors; therefore, we need the xvalue check here.
4694     ICS.Standard.DirectBinding =
4695       S.getLangOpts().CPlusPlus11 ||
4696       !(InitCategory.isPRValue() || T2->isRecordType());
4697     ICS.Standard.IsLvalueReference = !isRValRef;
4698     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4699     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4700     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4701     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4702     ICS.Standard.CopyConstructor = nullptr;
4703     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4704     return ICS;
4705   }
4706 
4707   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4708   //               reference-related to T2, and can be implicitly converted to
4709   //               an xvalue, class prvalue, or function lvalue of type
4710   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4711   //               "cv3 T3",
4712   //
4713   //          then the reference is bound to the value of the initializer
4714   //          expression in the first case and to the result of the conversion
4715   //          in the second case (or, in either case, to an appropriate base
4716   //          class subobject).
4717   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4718       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4719       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4720                                Init, T2, /*AllowRvalues=*/true,
4721                                AllowExplicit)) {
4722     // In the second case, if the reference is an rvalue reference
4723     // and the second standard conversion sequence of the
4724     // user-defined conversion sequence includes an lvalue-to-rvalue
4725     // conversion, the program is ill-formed.
4726     if (ICS.isUserDefined() && isRValRef &&
4727         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4728       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4729 
4730     return ICS;
4731   }
4732 
4733   // A temporary of function type cannot be created; don't even try.
4734   if (T1->isFunctionType())
4735     return ICS;
4736 
4737   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4738   //          initialized from the initializer expression using the
4739   //          rules for a non-reference copy initialization (8.5). The
4740   //          reference is then bound to the temporary. If T1 is
4741   //          reference-related to T2, cv1 must be the same
4742   //          cv-qualification as, or greater cv-qualification than,
4743   //          cv2; otherwise, the program is ill-formed.
4744   if (RefRelationship == Sema::Ref_Related) {
4745     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4746     // we would be reference-compatible or reference-compatible with
4747     // added qualification. But that wasn't the case, so the reference
4748     // initialization fails.
4749     //
4750     // Note that we only want to check address spaces and cvr-qualifiers here.
4751     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4752     Qualifiers T1Quals = T1.getQualifiers();
4753     Qualifiers T2Quals = T2.getQualifiers();
4754     T1Quals.removeObjCGCAttr();
4755     T1Quals.removeObjCLifetime();
4756     T2Quals.removeObjCGCAttr();
4757     T2Quals.removeObjCLifetime();
4758     // MS compiler ignores __unaligned qualifier for references; do the same.
4759     T1Quals.removeUnaligned();
4760     T2Quals.removeUnaligned();
4761     if (!T1Quals.compatiblyIncludes(T2Quals))
4762       return ICS;
4763   }
4764 
4765   // If at least one of the types is a class type, the types are not
4766   // related, and we aren't allowed any user conversions, the
4767   // reference binding fails. This case is important for breaking
4768   // recursion, since TryImplicitConversion below will attempt to
4769   // create a temporary through the use of a copy constructor.
4770   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4771       (T1->isRecordType() || T2->isRecordType()))
4772     return ICS;
4773 
4774   // If T1 is reference-related to T2 and the reference is an rvalue
4775   // reference, the initializer expression shall not be an lvalue.
4776   if (RefRelationship >= Sema::Ref_Related &&
4777       isRValRef && Init->Classify(S.Context).isLValue())
4778     return ICS;
4779 
4780   // C++ [over.ics.ref]p2:
4781   //   When a parameter of reference type is not bound directly to
4782   //   an argument expression, the conversion sequence is the one
4783   //   required to convert the argument expression to the
4784   //   underlying type of the reference according to
4785   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4786   //   to copy-initializing a temporary of the underlying type with
4787   //   the argument expression. Any difference in top-level
4788   //   cv-qualification is subsumed by the initialization itself
4789   //   and does not constitute a conversion.
4790   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4791                               /*AllowExplicit=*/false,
4792                               /*InOverloadResolution=*/false,
4793                               /*CStyle=*/false,
4794                               /*AllowObjCWritebackConversion=*/false,
4795                               /*AllowObjCConversionOnExplicit=*/false);
4796 
4797   // Of course, that's still a reference binding.
4798   if (ICS.isStandard()) {
4799     ICS.Standard.ReferenceBinding = true;
4800     ICS.Standard.IsLvalueReference = !isRValRef;
4801     ICS.Standard.BindsToFunctionLvalue = false;
4802     ICS.Standard.BindsToRvalue = true;
4803     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4804     ICS.Standard.ObjCLifetimeConversionBinding = false;
4805   } else if (ICS.isUserDefined()) {
4806     const ReferenceType *LValRefType =
4807         ICS.UserDefined.ConversionFunction->getReturnType()
4808             ->getAs<LValueReferenceType>();
4809 
4810     // C++ [over.ics.ref]p3:
4811     //   Except for an implicit object parameter, for which see 13.3.1, a
4812     //   standard conversion sequence cannot be formed if it requires [...]
4813     //   binding an rvalue reference to an lvalue other than a function
4814     //   lvalue.
4815     // Note that the function case is not possible here.
4816     if (DeclType->isRValueReferenceType() && LValRefType) {
4817       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4818       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4819       // reference to an rvalue!
4820       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4821       return ICS;
4822     }
4823 
4824     ICS.UserDefined.After.ReferenceBinding = true;
4825     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4826     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4827     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4828     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4829     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4830   }
4831 
4832   return ICS;
4833 }
4834 
4835 static ImplicitConversionSequence
4836 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4837                       bool SuppressUserConversions,
4838                       bool InOverloadResolution,
4839                       bool AllowObjCWritebackConversion,
4840                       bool AllowExplicit = false);
4841 
4842 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4843 /// initializer list From.
4844 static ImplicitConversionSequence
4845 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4846                   bool SuppressUserConversions,
4847                   bool InOverloadResolution,
4848                   bool AllowObjCWritebackConversion) {
4849   // C++11 [over.ics.list]p1:
4850   //   When an argument is an initializer list, it is not an expression and
4851   //   special rules apply for converting it to a parameter type.
4852 
4853   ImplicitConversionSequence Result;
4854   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4855 
4856   // We need a complete type for what follows. Incomplete types can never be
4857   // initialized from init lists.
4858   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4859     return Result;
4860 
4861   // Per DR1467:
4862   //   If the parameter type is a class X and the initializer list has a single
4863   //   element of type cv U, where U is X or a class derived from X, the
4864   //   implicit conversion sequence is the one required to convert the element
4865   //   to the parameter type.
4866   //
4867   //   Otherwise, if the parameter type is a character array [... ]
4868   //   and the initializer list has a single element that is an
4869   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4870   //   implicit conversion sequence is the identity conversion.
4871   if (From->getNumInits() == 1) {
4872     if (ToType->isRecordType()) {
4873       QualType InitType = From->getInit(0)->getType();
4874       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4875           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4876         return TryCopyInitialization(S, From->getInit(0), ToType,
4877                                      SuppressUserConversions,
4878                                      InOverloadResolution,
4879                                      AllowObjCWritebackConversion);
4880     }
4881     // FIXME: Check the other conditions here: array of character type,
4882     // initializer is a string literal.
4883     if (ToType->isArrayType()) {
4884       InitializedEntity Entity =
4885         InitializedEntity::InitializeParameter(S.Context, ToType,
4886                                                /*Consumed=*/false);
4887       if (S.CanPerformCopyInitialization(Entity, From)) {
4888         Result.setStandard();
4889         Result.Standard.setAsIdentityConversion();
4890         Result.Standard.setFromType(ToType);
4891         Result.Standard.setAllToTypes(ToType);
4892         return Result;
4893       }
4894     }
4895   }
4896 
4897   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4898   // C++11 [over.ics.list]p2:
4899   //   If the parameter type is std::initializer_list<X> or "array of X" and
4900   //   all the elements can be implicitly converted to X, the implicit
4901   //   conversion sequence is the worst conversion necessary to convert an
4902   //   element of the list to X.
4903   //
4904   // C++14 [over.ics.list]p3:
4905   //   Otherwise, if the parameter type is "array of N X", if the initializer
4906   //   list has exactly N elements or if it has fewer than N elements and X is
4907   //   default-constructible, and if all the elements of the initializer list
4908   //   can be implicitly converted to X, the implicit conversion sequence is
4909   //   the worst conversion necessary to convert an element of the list to X.
4910   //
4911   // FIXME: We're missing a lot of these checks.
4912   bool toStdInitializerList = false;
4913   QualType X;
4914   if (ToType->isArrayType())
4915     X = S.Context.getAsArrayType(ToType)->getElementType();
4916   else
4917     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4918   if (!X.isNull()) {
4919     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4920       Expr *Init = From->getInit(i);
4921       ImplicitConversionSequence ICS =
4922           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4923                                 InOverloadResolution,
4924                                 AllowObjCWritebackConversion);
4925       // If a single element isn't convertible, fail.
4926       if (ICS.isBad()) {
4927         Result = ICS;
4928         break;
4929       }
4930       // Otherwise, look for the worst conversion.
4931       if (Result.isBad() || CompareImplicitConversionSequences(
4932                                 S, From->getBeginLoc(), ICS, Result) ==
4933                                 ImplicitConversionSequence::Worse)
4934         Result = ICS;
4935     }
4936 
4937     // For an empty list, we won't have computed any conversion sequence.
4938     // Introduce the identity conversion sequence.
4939     if (From->getNumInits() == 0) {
4940       Result.setStandard();
4941       Result.Standard.setAsIdentityConversion();
4942       Result.Standard.setFromType(ToType);
4943       Result.Standard.setAllToTypes(ToType);
4944     }
4945 
4946     Result.setStdInitializerListElement(toStdInitializerList);
4947     return Result;
4948   }
4949 
4950   // C++14 [over.ics.list]p4:
4951   // C++11 [over.ics.list]p3:
4952   //   Otherwise, if the parameter is a non-aggregate class X and overload
4953   //   resolution chooses a single best constructor [...] the implicit
4954   //   conversion sequence is a user-defined conversion sequence. If multiple
4955   //   constructors are viable but none is better than the others, the
4956   //   implicit conversion sequence is a user-defined conversion sequence.
4957   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4958     // This function can deal with initializer lists.
4959     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4960                                     /*AllowExplicit=*/false,
4961                                     InOverloadResolution, /*CStyle=*/false,
4962                                     AllowObjCWritebackConversion,
4963                                     /*AllowObjCConversionOnExplicit=*/false);
4964   }
4965 
4966   // C++14 [over.ics.list]p5:
4967   // C++11 [over.ics.list]p4:
4968   //   Otherwise, if the parameter has an aggregate type which can be
4969   //   initialized from the initializer list [...] the implicit conversion
4970   //   sequence is a user-defined conversion sequence.
4971   if (ToType->isAggregateType()) {
4972     // Type is an aggregate, argument is an init list. At this point it comes
4973     // down to checking whether the initialization works.
4974     // FIXME: Find out whether this parameter is consumed or not.
4975     InitializedEntity Entity =
4976         InitializedEntity::InitializeParameter(S.Context, ToType,
4977                                                /*Consumed=*/false);
4978     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
4979                                                                  From)) {
4980       Result.setUserDefined();
4981       Result.UserDefined.Before.setAsIdentityConversion();
4982       // Initializer lists don't have a type.
4983       Result.UserDefined.Before.setFromType(QualType());
4984       Result.UserDefined.Before.setAllToTypes(QualType());
4985 
4986       Result.UserDefined.After.setAsIdentityConversion();
4987       Result.UserDefined.After.setFromType(ToType);
4988       Result.UserDefined.After.setAllToTypes(ToType);
4989       Result.UserDefined.ConversionFunction = nullptr;
4990     }
4991     return Result;
4992   }
4993 
4994   // C++14 [over.ics.list]p6:
4995   // C++11 [over.ics.list]p5:
4996   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4997   if (ToType->isReferenceType()) {
4998     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4999     // mention initializer lists in any way. So we go by what list-
5000     // initialization would do and try to extrapolate from that.
5001 
5002     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5003 
5004     // If the initializer list has a single element that is reference-related
5005     // to the parameter type, we initialize the reference from that.
5006     if (From->getNumInits() == 1) {
5007       Expr *Init = From->getInit(0);
5008 
5009       QualType T2 = Init->getType();
5010 
5011       // If the initializer is the address of an overloaded function, try
5012       // to resolve the overloaded function. If all goes well, T2 is the
5013       // type of the resulting function.
5014       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5015         DeclAccessPair Found;
5016         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5017                                    Init, ToType, false, Found))
5018           T2 = Fn->getType();
5019       }
5020 
5021       // Compute some basic properties of the types and the initializer.
5022       bool dummy1 = false;
5023       bool dummy2 = false;
5024       bool dummy3 = false;
5025       Sema::ReferenceCompareResult RefRelationship =
5026           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
5027                                          dummy2, dummy3);
5028 
5029       if (RefRelationship >= Sema::Ref_Related) {
5030         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5031                                 SuppressUserConversions,
5032                                 /*AllowExplicit=*/false);
5033       }
5034     }
5035 
5036     // Otherwise, we bind the reference to a temporary created from the
5037     // initializer list.
5038     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5039                                InOverloadResolution,
5040                                AllowObjCWritebackConversion);
5041     if (Result.isFailure())
5042       return Result;
5043     assert(!Result.isEllipsis() &&
5044            "Sub-initialization cannot result in ellipsis conversion.");
5045 
5046     // Can we even bind to a temporary?
5047     if (ToType->isRValueReferenceType() ||
5048         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5049       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5050                                             Result.UserDefined.After;
5051       SCS.ReferenceBinding = true;
5052       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5053       SCS.BindsToRvalue = true;
5054       SCS.BindsToFunctionLvalue = false;
5055       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5056       SCS.ObjCLifetimeConversionBinding = false;
5057     } else
5058       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5059                     From, ToType);
5060     return Result;
5061   }
5062 
5063   // C++14 [over.ics.list]p7:
5064   // C++11 [over.ics.list]p6:
5065   //   Otherwise, if the parameter type is not a class:
5066   if (!ToType->isRecordType()) {
5067     //    - if the initializer list has one element that is not itself an
5068     //      initializer list, the implicit conversion sequence is the one
5069     //      required to convert the element to the parameter type.
5070     unsigned NumInits = From->getNumInits();
5071     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5072       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5073                                      SuppressUserConversions,
5074                                      InOverloadResolution,
5075                                      AllowObjCWritebackConversion);
5076     //    - if the initializer list has no elements, the implicit conversion
5077     //      sequence is the identity conversion.
5078     else if (NumInits == 0) {
5079       Result.setStandard();
5080       Result.Standard.setAsIdentityConversion();
5081       Result.Standard.setFromType(ToType);
5082       Result.Standard.setAllToTypes(ToType);
5083     }
5084     return Result;
5085   }
5086 
5087   // C++14 [over.ics.list]p8:
5088   // C++11 [over.ics.list]p7:
5089   //   In all cases other than those enumerated above, no conversion is possible
5090   return Result;
5091 }
5092 
5093 /// TryCopyInitialization - Try to copy-initialize a value of type
5094 /// ToType from the expression From. Return the implicit conversion
5095 /// sequence required to pass this argument, which may be a bad
5096 /// conversion sequence (meaning that the argument cannot be passed to
5097 /// a parameter of this type). If @p SuppressUserConversions, then we
5098 /// do not permit any user-defined conversion sequences.
5099 static ImplicitConversionSequence
5100 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5101                       bool SuppressUserConversions,
5102                       bool InOverloadResolution,
5103                       bool AllowObjCWritebackConversion,
5104                       bool AllowExplicit) {
5105   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5106     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5107                              InOverloadResolution,AllowObjCWritebackConversion);
5108 
5109   if (ToType->isReferenceType())
5110     return TryReferenceInit(S, From, ToType,
5111                             /*FIXME:*/ From->getBeginLoc(),
5112                             SuppressUserConversions, AllowExplicit);
5113 
5114   return TryImplicitConversion(S, From, ToType,
5115                                SuppressUserConversions,
5116                                /*AllowExplicit=*/false,
5117                                InOverloadResolution,
5118                                /*CStyle=*/false,
5119                                AllowObjCWritebackConversion,
5120                                /*AllowObjCConversionOnExplicit=*/false);
5121 }
5122 
5123 static bool TryCopyInitialization(const CanQualType FromQTy,
5124                                   const CanQualType ToQTy,
5125                                   Sema &S,
5126                                   SourceLocation Loc,
5127                                   ExprValueKind FromVK) {
5128   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5129   ImplicitConversionSequence ICS =
5130     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5131 
5132   return !ICS.isBad();
5133 }
5134 
5135 /// TryObjectArgumentInitialization - Try to initialize the object
5136 /// parameter of the given member function (@c Method) from the
5137 /// expression @p From.
5138 static ImplicitConversionSequence
5139 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5140                                 Expr::Classification FromClassification,
5141                                 CXXMethodDecl *Method,
5142                                 CXXRecordDecl *ActingContext) {
5143   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5144   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5145   //                 const volatile object.
5146   Qualifiers Quals = Method->getMethodQualifiers();
5147   if (isa<CXXDestructorDecl>(Method)) {
5148     Quals.addConst();
5149     Quals.addVolatile();
5150   }
5151 
5152   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5153 
5154   // Set up the conversion sequence as a "bad" conversion, to allow us
5155   // to exit early.
5156   ImplicitConversionSequence ICS;
5157 
5158   // We need to have an object of class type.
5159   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5160     FromType = PT->getPointeeType();
5161 
5162     // When we had a pointer, it's implicitly dereferenced, so we
5163     // better have an lvalue.
5164     assert(FromClassification.isLValue());
5165   }
5166 
5167   assert(FromType->isRecordType());
5168 
5169   // C++0x [over.match.funcs]p4:
5170   //   For non-static member functions, the type of the implicit object
5171   //   parameter is
5172   //
5173   //     - "lvalue reference to cv X" for functions declared without a
5174   //        ref-qualifier or with the & ref-qualifier
5175   //     - "rvalue reference to cv X" for functions declared with the &&
5176   //        ref-qualifier
5177   //
5178   // where X is the class of which the function is a member and cv is the
5179   // cv-qualification on the member function declaration.
5180   //
5181   // However, when finding an implicit conversion sequence for the argument, we
5182   // are not allowed to perform user-defined conversions
5183   // (C++ [over.match.funcs]p5). We perform a simplified version of
5184   // reference binding here, that allows class rvalues to bind to
5185   // non-constant references.
5186 
5187   // First check the qualifiers.
5188   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5189   if (ImplicitParamType.getCVRQualifiers()
5190                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5191       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5192     ICS.setBad(BadConversionSequence::bad_qualifiers,
5193                FromType, ImplicitParamType);
5194     return ICS;
5195   }
5196 
5197   if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5198     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5199     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5200     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5201       ICS.setBad(BadConversionSequence::bad_qualifiers,
5202                  FromType, ImplicitParamType);
5203       return ICS;
5204     }
5205   }
5206 
5207   // Check that we have either the same type or a derived type. It
5208   // affects the conversion rank.
5209   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5210   ImplicitConversionKind SecondKind;
5211   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5212     SecondKind = ICK_Identity;
5213   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5214     SecondKind = ICK_Derived_To_Base;
5215   else {
5216     ICS.setBad(BadConversionSequence::unrelated_class,
5217                FromType, ImplicitParamType);
5218     return ICS;
5219   }
5220 
5221   // Check the ref-qualifier.
5222   switch (Method->getRefQualifier()) {
5223   case RQ_None:
5224     // Do nothing; we don't care about lvalueness or rvalueness.
5225     break;
5226 
5227   case RQ_LValue:
5228     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5229       // non-const lvalue reference cannot bind to an rvalue
5230       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5231                  ImplicitParamType);
5232       return ICS;
5233     }
5234     break;
5235 
5236   case RQ_RValue:
5237     if (!FromClassification.isRValue()) {
5238       // rvalue reference cannot bind to an lvalue
5239       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5240                  ImplicitParamType);
5241       return ICS;
5242     }
5243     break;
5244   }
5245 
5246   // Success. Mark this as a reference binding.
5247   ICS.setStandard();
5248   ICS.Standard.setAsIdentityConversion();
5249   ICS.Standard.Second = SecondKind;
5250   ICS.Standard.setFromType(FromType);
5251   ICS.Standard.setAllToTypes(ImplicitParamType);
5252   ICS.Standard.ReferenceBinding = true;
5253   ICS.Standard.DirectBinding = true;
5254   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5255   ICS.Standard.BindsToFunctionLvalue = false;
5256   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5257   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5258     = (Method->getRefQualifier() == RQ_None);
5259   return ICS;
5260 }
5261 
5262 /// PerformObjectArgumentInitialization - Perform initialization of
5263 /// the implicit object parameter for the given Method with the given
5264 /// expression.
5265 ExprResult
5266 Sema::PerformObjectArgumentInitialization(Expr *From,
5267                                           NestedNameSpecifier *Qualifier,
5268                                           NamedDecl *FoundDecl,
5269                                           CXXMethodDecl *Method) {
5270   QualType FromRecordType, DestType;
5271   QualType ImplicitParamRecordType  =
5272     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5273 
5274   Expr::Classification FromClassification;
5275   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5276     FromRecordType = PT->getPointeeType();
5277     DestType = Method->getThisType();
5278     FromClassification = Expr::Classification::makeSimpleLValue();
5279   } else {
5280     FromRecordType = From->getType();
5281     DestType = ImplicitParamRecordType;
5282     FromClassification = From->Classify(Context);
5283 
5284     // When performing member access on an rvalue, materialize a temporary.
5285     if (From->isRValue()) {
5286       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5287                                             Method->getRefQualifier() !=
5288                                                 RefQualifierKind::RQ_RValue);
5289     }
5290   }
5291 
5292   // Note that we always use the true parent context when performing
5293   // the actual argument initialization.
5294   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5295       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5296       Method->getParent());
5297   if (ICS.isBad()) {
5298     switch (ICS.Bad.Kind) {
5299     case BadConversionSequence::bad_qualifiers: {
5300       Qualifiers FromQs = FromRecordType.getQualifiers();
5301       Qualifiers ToQs = DestType.getQualifiers();
5302       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5303       if (CVR) {
5304         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5305             << Method->getDeclName() << FromRecordType << (CVR - 1)
5306             << From->getSourceRange();
5307         Diag(Method->getLocation(), diag::note_previous_decl)
5308           << Method->getDeclName();
5309         return ExprError();
5310       }
5311       break;
5312     }
5313 
5314     case BadConversionSequence::lvalue_ref_to_rvalue:
5315     case BadConversionSequence::rvalue_ref_to_lvalue: {
5316       bool IsRValueQualified =
5317         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5318       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5319           << Method->getDeclName() << FromClassification.isRValue()
5320           << IsRValueQualified;
5321       Diag(Method->getLocation(), diag::note_previous_decl)
5322         << Method->getDeclName();
5323       return ExprError();
5324     }
5325 
5326     case BadConversionSequence::no_conversion:
5327     case BadConversionSequence::unrelated_class:
5328       break;
5329     }
5330 
5331     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5332            << ImplicitParamRecordType << FromRecordType
5333            << From->getSourceRange();
5334   }
5335 
5336   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5337     ExprResult FromRes =
5338       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5339     if (FromRes.isInvalid())
5340       return ExprError();
5341     From = FromRes.get();
5342   }
5343 
5344   if (!Context.hasSameType(From->getType(), DestType)) {
5345     CastKind CK;
5346     if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
5347       CK = CK_AddressSpaceConversion;
5348     else
5349       CK = CK_NoOp;
5350     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5351   }
5352   return From;
5353 }
5354 
5355 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5356 /// expression From to bool (C++0x [conv]p3).
5357 static ImplicitConversionSequence
5358 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5359   return TryImplicitConversion(S, From, S.Context.BoolTy,
5360                                /*SuppressUserConversions=*/false,
5361                                /*AllowExplicit=*/true,
5362                                /*InOverloadResolution=*/false,
5363                                /*CStyle=*/false,
5364                                /*AllowObjCWritebackConversion=*/false,
5365                                /*AllowObjCConversionOnExplicit=*/false);
5366 }
5367 
5368 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5369 /// of the expression From to bool (C++0x [conv]p3).
5370 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5371   if (checkPlaceholderForOverload(*this, From))
5372     return ExprError();
5373 
5374   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5375   if (!ICS.isBad())
5376     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5377 
5378   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5379     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5380            << From->getType() << From->getSourceRange();
5381   return ExprError();
5382 }
5383 
5384 /// Check that the specified conversion is permitted in a converted constant
5385 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5386 /// is acceptable.
5387 static bool CheckConvertedConstantConversions(Sema &S,
5388                                               StandardConversionSequence &SCS) {
5389   // Since we know that the target type is an integral or unscoped enumeration
5390   // type, most conversion kinds are impossible. All possible First and Third
5391   // conversions are fine.
5392   switch (SCS.Second) {
5393   case ICK_Identity:
5394   case ICK_Function_Conversion:
5395   case ICK_Integral_Promotion:
5396   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5397   case ICK_Zero_Queue_Conversion:
5398     return true;
5399 
5400   case ICK_Boolean_Conversion:
5401     // Conversion from an integral or unscoped enumeration type to bool is
5402     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5403     // conversion, so we allow it in a converted constant expression.
5404     //
5405     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5406     // a lot of popular code. We should at least add a warning for this
5407     // (non-conforming) extension.
5408     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5409            SCS.getToType(2)->isBooleanType();
5410 
5411   case ICK_Pointer_Conversion:
5412   case ICK_Pointer_Member:
5413     // C++1z: null pointer conversions and null member pointer conversions are
5414     // only permitted if the source type is std::nullptr_t.
5415     return SCS.getFromType()->isNullPtrType();
5416 
5417   case ICK_Floating_Promotion:
5418   case ICK_Complex_Promotion:
5419   case ICK_Floating_Conversion:
5420   case ICK_Complex_Conversion:
5421   case ICK_Floating_Integral:
5422   case ICK_Compatible_Conversion:
5423   case ICK_Derived_To_Base:
5424   case ICK_Vector_Conversion:
5425   case ICK_Vector_Splat:
5426   case ICK_Complex_Real:
5427   case ICK_Block_Pointer_Conversion:
5428   case ICK_TransparentUnionConversion:
5429   case ICK_Writeback_Conversion:
5430   case ICK_Zero_Event_Conversion:
5431   case ICK_C_Only_Conversion:
5432   case ICK_Incompatible_Pointer_Conversion:
5433     return false;
5434 
5435   case ICK_Lvalue_To_Rvalue:
5436   case ICK_Array_To_Pointer:
5437   case ICK_Function_To_Pointer:
5438     llvm_unreachable("found a first conversion kind in Second");
5439 
5440   case ICK_Qualification:
5441     llvm_unreachable("found a third conversion kind in Second");
5442 
5443   case ICK_Num_Conversion_Kinds:
5444     break;
5445   }
5446 
5447   llvm_unreachable("unknown conversion kind");
5448 }
5449 
5450 /// CheckConvertedConstantExpression - Check that the expression From is a
5451 /// converted constant expression of type T, perform the conversion and produce
5452 /// the converted expression, per C++11 [expr.const]p3.
5453 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5454                                                    QualType T, APValue &Value,
5455                                                    Sema::CCEKind CCE,
5456                                                    bool RequireInt) {
5457   assert(S.getLangOpts().CPlusPlus11 &&
5458          "converted constant expression outside C++11");
5459 
5460   if (checkPlaceholderForOverload(S, From))
5461     return ExprError();
5462 
5463   // C++1z [expr.const]p3:
5464   //  A converted constant expression of type T is an expression,
5465   //  implicitly converted to type T, where the converted
5466   //  expression is a constant expression and the implicit conversion
5467   //  sequence contains only [... list of conversions ...].
5468   // C++1z [stmt.if]p2:
5469   //  If the if statement is of the form if constexpr, the value of the
5470   //  condition shall be a contextually converted constant expression of type
5471   //  bool.
5472   ImplicitConversionSequence ICS =
5473       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5474           ? TryContextuallyConvertToBool(S, From)
5475           : TryCopyInitialization(S, From, T,
5476                                   /*SuppressUserConversions=*/false,
5477                                   /*InOverloadResolution=*/false,
5478                                   /*AllowObjCWritebackConversion=*/false,
5479                                   /*AllowExplicit=*/false);
5480   StandardConversionSequence *SCS = nullptr;
5481   switch (ICS.getKind()) {
5482   case ImplicitConversionSequence::StandardConversion:
5483     SCS = &ICS.Standard;
5484     break;
5485   case ImplicitConversionSequence::UserDefinedConversion:
5486     // We are converting to a non-class type, so the Before sequence
5487     // must be trivial.
5488     SCS = &ICS.UserDefined.After;
5489     break;
5490   case ImplicitConversionSequence::AmbiguousConversion:
5491   case ImplicitConversionSequence::BadConversion:
5492     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5493       return S.Diag(From->getBeginLoc(),
5494                     diag::err_typecheck_converted_constant_expression)
5495              << From->getType() << From->getSourceRange() << T;
5496     return ExprError();
5497 
5498   case ImplicitConversionSequence::EllipsisConversion:
5499     llvm_unreachable("ellipsis conversion in converted constant expression");
5500   }
5501 
5502   // Check that we would only use permitted conversions.
5503   if (!CheckConvertedConstantConversions(S, *SCS)) {
5504     return S.Diag(From->getBeginLoc(),
5505                   diag::err_typecheck_converted_constant_expression_disallowed)
5506            << From->getType() << From->getSourceRange() << T;
5507   }
5508   // [...] and where the reference binding (if any) binds directly.
5509   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5510     return S.Diag(From->getBeginLoc(),
5511                   diag::err_typecheck_converted_constant_expression_indirect)
5512            << From->getType() << From->getSourceRange() << T;
5513   }
5514 
5515   ExprResult Result =
5516       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5517   if (Result.isInvalid())
5518     return Result;
5519 
5520   // C++2a [intro.execution]p5:
5521   //   A full-expression is [...] a constant-expression [...]
5522   Result =
5523       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5524                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5525   if (Result.isInvalid())
5526     return Result;
5527 
5528   // Check for a narrowing implicit conversion.
5529   APValue PreNarrowingValue;
5530   QualType PreNarrowingType;
5531   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5532                                 PreNarrowingType)) {
5533   case NK_Dependent_Narrowing:
5534     // Implicit conversion to a narrower type, but the expression is
5535     // value-dependent so we can't tell whether it's actually narrowing.
5536   case NK_Variable_Narrowing:
5537     // Implicit conversion to a narrower type, and the value is not a constant
5538     // expression. We'll diagnose this in a moment.
5539   case NK_Not_Narrowing:
5540     break;
5541 
5542   case NK_Constant_Narrowing:
5543     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5544         << CCE << /*Constant*/ 1
5545         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5546     break;
5547 
5548   case NK_Type_Narrowing:
5549     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5550         << CCE << /*Constant*/ 0 << From->getType() << T;
5551     break;
5552   }
5553 
5554   if (Result.get()->isValueDependent()) {
5555     Value = APValue();
5556     return Result;
5557   }
5558 
5559   // Check the expression is a constant expression.
5560   SmallVector<PartialDiagnosticAt, 8> Notes;
5561   Expr::EvalResult Eval;
5562   Eval.Diag = &Notes;
5563   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5564                                    ? Expr::EvaluateForMangling
5565                                    : Expr::EvaluateForCodeGen;
5566 
5567   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5568       (RequireInt && !Eval.Val.isInt())) {
5569     // The expression can't be folded, so we can't keep it at this position in
5570     // the AST.
5571     Result = ExprError();
5572   } else {
5573     Value = Eval.Val;
5574 
5575     if (Notes.empty()) {
5576       // It's a constant expression.
5577       return ConstantExpr::Create(S.Context, Result.get(), Value);
5578     }
5579   }
5580 
5581   // It's not a constant expression. Produce an appropriate diagnostic.
5582   if (Notes.size() == 1 &&
5583       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5584     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5585   else {
5586     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5587         << CCE << From->getSourceRange();
5588     for (unsigned I = 0; I < Notes.size(); ++I)
5589       S.Diag(Notes[I].first, Notes[I].second);
5590   }
5591   return ExprError();
5592 }
5593 
5594 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5595                                                   APValue &Value, CCEKind CCE) {
5596   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5597 }
5598 
5599 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5600                                                   llvm::APSInt &Value,
5601                                                   CCEKind CCE) {
5602   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5603 
5604   APValue V;
5605   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5606   if (!R.isInvalid() && !R.get()->isValueDependent())
5607     Value = V.getInt();
5608   return R;
5609 }
5610 
5611 
5612 /// dropPointerConversions - If the given standard conversion sequence
5613 /// involves any pointer conversions, remove them.  This may change
5614 /// the result type of the conversion sequence.
5615 static void dropPointerConversion(StandardConversionSequence &SCS) {
5616   if (SCS.Second == ICK_Pointer_Conversion) {
5617     SCS.Second = ICK_Identity;
5618     SCS.Third = ICK_Identity;
5619     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5620   }
5621 }
5622 
5623 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5624 /// convert the expression From to an Objective-C pointer type.
5625 static ImplicitConversionSequence
5626 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5627   // Do an implicit conversion to 'id'.
5628   QualType Ty = S.Context.getObjCIdType();
5629   ImplicitConversionSequence ICS
5630     = TryImplicitConversion(S, From, Ty,
5631                             // FIXME: Are these flags correct?
5632                             /*SuppressUserConversions=*/false,
5633                             /*AllowExplicit=*/true,
5634                             /*InOverloadResolution=*/false,
5635                             /*CStyle=*/false,
5636                             /*AllowObjCWritebackConversion=*/false,
5637                             /*AllowObjCConversionOnExplicit=*/true);
5638 
5639   // Strip off any final conversions to 'id'.
5640   switch (ICS.getKind()) {
5641   case ImplicitConversionSequence::BadConversion:
5642   case ImplicitConversionSequence::AmbiguousConversion:
5643   case ImplicitConversionSequence::EllipsisConversion:
5644     break;
5645 
5646   case ImplicitConversionSequence::UserDefinedConversion:
5647     dropPointerConversion(ICS.UserDefined.After);
5648     break;
5649 
5650   case ImplicitConversionSequence::StandardConversion:
5651     dropPointerConversion(ICS.Standard);
5652     break;
5653   }
5654 
5655   return ICS;
5656 }
5657 
5658 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5659 /// conversion of the expression From to an Objective-C pointer type.
5660 /// Returns a valid but null ExprResult if no conversion sequence exists.
5661 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5662   if (checkPlaceholderForOverload(*this, From))
5663     return ExprError();
5664 
5665   QualType Ty = Context.getObjCIdType();
5666   ImplicitConversionSequence ICS =
5667     TryContextuallyConvertToObjCPointer(*this, From);
5668   if (!ICS.isBad())
5669     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5670   return ExprResult();
5671 }
5672 
5673 /// Determine whether the provided type is an integral type, or an enumeration
5674 /// type of a permitted flavor.
5675 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5676   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5677                                  : T->isIntegralOrUnscopedEnumerationType();
5678 }
5679 
5680 static ExprResult
5681 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5682                             Sema::ContextualImplicitConverter &Converter,
5683                             QualType T, UnresolvedSetImpl &ViableConversions) {
5684 
5685   if (Converter.Suppress)
5686     return ExprError();
5687 
5688   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5689   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5690     CXXConversionDecl *Conv =
5691         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5692     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5693     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5694   }
5695   return From;
5696 }
5697 
5698 static bool
5699 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5700                            Sema::ContextualImplicitConverter &Converter,
5701                            QualType T, bool HadMultipleCandidates,
5702                            UnresolvedSetImpl &ExplicitConversions) {
5703   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5704     DeclAccessPair Found = ExplicitConversions[0];
5705     CXXConversionDecl *Conversion =
5706         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5707 
5708     // The user probably meant to invoke the given explicit
5709     // conversion; use it.
5710     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5711     std::string TypeStr;
5712     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5713 
5714     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5715         << FixItHint::CreateInsertion(From->getBeginLoc(),
5716                                       "static_cast<" + TypeStr + ">(")
5717         << FixItHint::CreateInsertion(
5718                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5719     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5720 
5721     // If we aren't in a SFINAE context, build a call to the
5722     // explicit conversion function.
5723     if (SemaRef.isSFINAEContext())
5724       return true;
5725 
5726     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5727     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5728                                                        HadMultipleCandidates);
5729     if (Result.isInvalid())
5730       return true;
5731     // Record usage of conversion in an implicit cast.
5732     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5733                                     CK_UserDefinedConversion, Result.get(),
5734                                     nullptr, Result.get()->getValueKind());
5735   }
5736   return false;
5737 }
5738 
5739 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5740                              Sema::ContextualImplicitConverter &Converter,
5741                              QualType T, bool HadMultipleCandidates,
5742                              DeclAccessPair &Found) {
5743   CXXConversionDecl *Conversion =
5744       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5745   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5746 
5747   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5748   if (!Converter.SuppressConversion) {
5749     if (SemaRef.isSFINAEContext())
5750       return true;
5751 
5752     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5753         << From->getSourceRange();
5754   }
5755 
5756   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5757                                                      HadMultipleCandidates);
5758   if (Result.isInvalid())
5759     return true;
5760   // Record usage of conversion in an implicit cast.
5761   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5762                                   CK_UserDefinedConversion, Result.get(),
5763                                   nullptr, Result.get()->getValueKind());
5764   return false;
5765 }
5766 
5767 static ExprResult finishContextualImplicitConversion(
5768     Sema &SemaRef, SourceLocation Loc, Expr *From,
5769     Sema::ContextualImplicitConverter &Converter) {
5770   if (!Converter.match(From->getType()) && !Converter.Suppress)
5771     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5772         << From->getSourceRange();
5773 
5774   return SemaRef.DefaultLvalueConversion(From);
5775 }
5776 
5777 static void
5778 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5779                                   UnresolvedSetImpl &ViableConversions,
5780                                   OverloadCandidateSet &CandidateSet) {
5781   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5782     DeclAccessPair FoundDecl = ViableConversions[I];
5783     NamedDecl *D = FoundDecl.getDecl();
5784     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5785     if (isa<UsingShadowDecl>(D))
5786       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5787 
5788     CXXConversionDecl *Conv;
5789     FunctionTemplateDecl *ConvTemplate;
5790     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5791       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5792     else
5793       Conv = cast<CXXConversionDecl>(D);
5794 
5795     if (ConvTemplate)
5796       SemaRef.AddTemplateConversionCandidate(
5797           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5798           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5799     else
5800       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5801                                      ToType, CandidateSet,
5802                                      /*AllowObjCConversionOnExplicit=*/false,
5803                                      /*AllowExplicit*/ true);
5804   }
5805 }
5806 
5807 /// Attempt to convert the given expression to a type which is accepted
5808 /// by the given converter.
5809 ///
5810 /// This routine will attempt to convert an expression of class type to a
5811 /// type accepted by the specified converter. In C++11 and before, the class
5812 /// must have a single non-explicit conversion function converting to a matching
5813 /// type. In C++1y, there can be multiple such conversion functions, but only
5814 /// one target type.
5815 ///
5816 /// \param Loc The source location of the construct that requires the
5817 /// conversion.
5818 ///
5819 /// \param From The expression we're converting from.
5820 ///
5821 /// \param Converter Used to control and diagnose the conversion process.
5822 ///
5823 /// \returns The expression, converted to an integral or enumeration type if
5824 /// successful.
5825 ExprResult Sema::PerformContextualImplicitConversion(
5826     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5827   // We can't perform any more checking for type-dependent expressions.
5828   if (From->isTypeDependent())
5829     return From;
5830 
5831   // Process placeholders immediately.
5832   if (From->hasPlaceholderType()) {
5833     ExprResult result = CheckPlaceholderExpr(From);
5834     if (result.isInvalid())
5835       return result;
5836     From = result.get();
5837   }
5838 
5839   // If the expression already has a matching type, we're golden.
5840   QualType T = From->getType();
5841   if (Converter.match(T))
5842     return DefaultLvalueConversion(From);
5843 
5844   // FIXME: Check for missing '()' if T is a function type?
5845 
5846   // We can only perform contextual implicit conversions on objects of class
5847   // type.
5848   const RecordType *RecordTy = T->getAs<RecordType>();
5849   if (!RecordTy || !getLangOpts().CPlusPlus) {
5850     if (!Converter.Suppress)
5851       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5852     return From;
5853   }
5854 
5855   // We must have a complete class type.
5856   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5857     ContextualImplicitConverter &Converter;
5858     Expr *From;
5859 
5860     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5861         : Converter(Converter), From(From) {}
5862 
5863     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5864       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5865     }
5866   } IncompleteDiagnoser(Converter, From);
5867 
5868   if (Converter.Suppress ? !isCompleteType(Loc, T)
5869                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5870     return From;
5871 
5872   // Look for a conversion to an integral or enumeration type.
5873   UnresolvedSet<4>
5874       ViableConversions; // These are *potentially* viable in C++1y.
5875   UnresolvedSet<4> ExplicitConversions;
5876   const auto &Conversions =
5877       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5878 
5879   bool HadMultipleCandidates =
5880       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5881 
5882   // To check that there is only one target type, in C++1y:
5883   QualType ToType;
5884   bool HasUniqueTargetType = true;
5885 
5886   // Collect explicit or viable (potentially in C++1y) conversions.
5887   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5888     NamedDecl *D = (*I)->getUnderlyingDecl();
5889     CXXConversionDecl *Conversion;
5890     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5891     if (ConvTemplate) {
5892       if (getLangOpts().CPlusPlus14)
5893         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5894       else
5895         continue; // C++11 does not consider conversion operator templates(?).
5896     } else
5897       Conversion = cast<CXXConversionDecl>(D);
5898 
5899     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5900            "Conversion operator templates are considered potentially "
5901            "viable in C++1y");
5902 
5903     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5904     if (Converter.match(CurToType) || ConvTemplate) {
5905 
5906       if (Conversion->isExplicit()) {
5907         // FIXME: For C++1y, do we need this restriction?
5908         // cf. diagnoseNoViableConversion()
5909         if (!ConvTemplate)
5910           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5911       } else {
5912         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5913           if (ToType.isNull())
5914             ToType = CurToType.getUnqualifiedType();
5915           else if (HasUniqueTargetType &&
5916                    (CurToType.getUnqualifiedType() != ToType))
5917             HasUniqueTargetType = false;
5918         }
5919         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5920       }
5921     }
5922   }
5923 
5924   if (getLangOpts().CPlusPlus14) {
5925     // C++1y [conv]p6:
5926     // ... An expression e of class type E appearing in such a context
5927     // is said to be contextually implicitly converted to a specified
5928     // type T and is well-formed if and only if e can be implicitly
5929     // converted to a type T that is determined as follows: E is searched
5930     // for conversion functions whose return type is cv T or reference to
5931     // cv T such that T is allowed by the context. There shall be
5932     // exactly one such T.
5933 
5934     // If no unique T is found:
5935     if (ToType.isNull()) {
5936       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5937                                      HadMultipleCandidates,
5938                                      ExplicitConversions))
5939         return ExprError();
5940       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5941     }
5942 
5943     // If more than one unique Ts are found:
5944     if (!HasUniqueTargetType)
5945       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5946                                          ViableConversions);
5947 
5948     // If one unique T is found:
5949     // First, build a candidate set from the previously recorded
5950     // potentially viable conversions.
5951     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5952     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5953                                       CandidateSet);
5954 
5955     // Then, perform overload resolution over the candidate set.
5956     OverloadCandidateSet::iterator Best;
5957     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5958     case OR_Success: {
5959       // Apply this conversion.
5960       DeclAccessPair Found =
5961           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5962       if (recordConversion(*this, Loc, From, Converter, T,
5963                            HadMultipleCandidates, Found))
5964         return ExprError();
5965       break;
5966     }
5967     case OR_Ambiguous:
5968       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5969                                          ViableConversions);
5970     case OR_No_Viable_Function:
5971       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5972                                      HadMultipleCandidates,
5973                                      ExplicitConversions))
5974         return ExprError();
5975       LLVM_FALLTHROUGH;
5976     case OR_Deleted:
5977       // We'll complain below about a non-integral condition type.
5978       break;
5979     }
5980   } else {
5981     switch (ViableConversions.size()) {
5982     case 0: {
5983       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5984                                      HadMultipleCandidates,
5985                                      ExplicitConversions))
5986         return ExprError();
5987 
5988       // We'll complain below about a non-integral condition type.
5989       break;
5990     }
5991     case 1: {
5992       // Apply this conversion.
5993       DeclAccessPair Found = ViableConversions[0];
5994       if (recordConversion(*this, Loc, From, Converter, T,
5995                            HadMultipleCandidates, Found))
5996         return ExprError();
5997       break;
5998     }
5999     default:
6000       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6001                                          ViableConversions);
6002     }
6003   }
6004 
6005   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6006 }
6007 
6008 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6009 /// an acceptable non-member overloaded operator for a call whose
6010 /// arguments have types T1 (and, if non-empty, T2). This routine
6011 /// implements the check in C++ [over.match.oper]p3b2 concerning
6012 /// enumeration types.
6013 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6014                                                    FunctionDecl *Fn,
6015                                                    ArrayRef<Expr *> Args) {
6016   QualType T1 = Args[0]->getType();
6017   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6018 
6019   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6020     return true;
6021 
6022   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6023     return true;
6024 
6025   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
6026   if (Proto->getNumParams() < 1)
6027     return false;
6028 
6029   if (T1->isEnumeralType()) {
6030     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6031     if (Context.hasSameUnqualifiedType(T1, ArgType))
6032       return true;
6033   }
6034 
6035   if (Proto->getNumParams() < 2)
6036     return false;
6037 
6038   if (!T2.isNull() && T2->isEnumeralType()) {
6039     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6040     if (Context.hasSameUnqualifiedType(T2, ArgType))
6041       return true;
6042   }
6043 
6044   return false;
6045 }
6046 
6047 /// AddOverloadCandidate - Adds the given function to the set of
6048 /// candidate functions, using the given function call arguments.  If
6049 /// @p SuppressUserConversions, then don't allow user-defined
6050 /// conversions via constructors or conversion operators.
6051 ///
6052 /// \param PartialOverloading true if we are performing "partial" overloading
6053 /// based on an incomplete set of function arguments. This feature is used by
6054 /// code completion.
6055 void Sema::AddOverloadCandidate(
6056     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6057     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6058     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6059     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) {
6060   const FunctionProtoType *Proto
6061     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6062   assert(Proto && "Functions without a prototype cannot be overloaded");
6063   assert(!Function->getDescribedFunctionTemplate() &&
6064          "Use AddTemplateOverloadCandidate for function templates");
6065 
6066   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6067     if (!isa<CXXConstructorDecl>(Method)) {
6068       // If we get here, it's because we're calling a member function
6069       // that is named without a member access expression (e.g.,
6070       // "this->f") that was either written explicitly or created
6071       // implicitly. This can happen with a qualified call to a member
6072       // function, e.g., X::f(). We use an empty type for the implied
6073       // object argument (C++ [over.call.func]p3), and the acting context
6074       // is irrelevant.
6075       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6076                          Expr::Classification::makeSimpleLValue(), Args,
6077                          CandidateSet, SuppressUserConversions,
6078                          PartialOverloading, EarlyConversions);
6079       return;
6080     }
6081     // We treat a constructor like a non-member function, since its object
6082     // argument doesn't participate in overload resolution.
6083   }
6084 
6085   if (!CandidateSet.isNewCandidate(Function))
6086     return;
6087 
6088   // C++ [over.match.oper]p3:
6089   //   if no operand has a class type, only those non-member functions in the
6090   //   lookup set that have a first parameter of type T1 or "reference to
6091   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6092   //   is a right operand) a second parameter of type T2 or "reference to
6093   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6094   //   candidate functions.
6095   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6096       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6097     return;
6098 
6099   // C++11 [class.copy]p11: [DR1402]
6100   //   A defaulted move constructor that is defined as deleted is ignored by
6101   //   overload resolution.
6102   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6103   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6104       Constructor->isMoveConstructor())
6105     return;
6106 
6107   // Overload resolution is always an unevaluated context.
6108   EnterExpressionEvaluationContext Unevaluated(
6109       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6110 
6111   // Add this candidate
6112   OverloadCandidate &Candidate =
6113       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6114   Candidate.FoundDecl = FoundDecl;
6115   Candidate.Function = Function;
6116   Candidate.Viable = true;
6117   Candidate.IsSurrogate = false;
6118   Candidate.IsADLCandidate = IsADLCandidate;
6119   Candidate.IgnoreObjectArgument = false;
6120   Candidate.ExplicitCallArguments = Args.size();
6121 
6122   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6123       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6124     Candidate.Viable = false;
6125     Candidate.FailureKind = ovl_non_default_multiversion_function;
6126     return;
6127   }
6128 
6129   if (Constructor) {
6130     // C++ [class.copy]p3:
6131     //   A member function template is never instantiated to perform the copy
6132     //   of a class object to an object of its class type.
6133     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6134     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6135         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6136          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6137                        ClassType))) {
6138       Candidate.Viable = false;
6139       Candidate.FailureKind = ovl_fail_illegal_constructor;
6140       return;
6141     }
6142 
6143     // C++ [over.match.funcs]p8: (proposed DR resolution)
6144     //   A constructor inherited from class type C that has a first parameter
6145     //   of type "reference to P" (including such a constructor instantiated
6146     //   from a template) is excluded from the set of candidate functions when
6147     //   constructing an object of type cv D if the argument list has exactly
6148     //   one argument and D is reference-related to P and P is reference-related
6149     //   to C.
6150     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6151     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6152         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6153       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6154       QualType C = Context.getRecordType(Constructor->getParent());
6155       QualType D = Context.getRecordType(Shadow->getParent());
6156       SourceLocation Loc = Args.front()->getExprLoc();
6157       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6158           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6159         Candidate.Viable = false;
6160         Candidate.FailureKind = ovl_fail_inhctor_slice;
6161         return;
6162       }
6163     }
6164 
6165     // Check that the constructor is capable of constructing an object in the
6166     // destination address space.
6167     if (!Qualifiers::isAddressSpaceSupersetOf(
6168             Constructor->getMethodQualifiers().getAddressSpace(),
6169             CandidateSet.getDestAS())) {
6170       Candidate.Viable = false;
6171       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6172     }
6173   }
6174 
6175   unsigned NumParams = Proto->getNumParams();
6176 
6177   // (C++ 13.3.2p2): A candidate function having fewer than m
6178   // parameters is viable only if it has an ellipsis in its parameter
6179   // list (8.3.5).
6180   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6181       !Proto->isVariadic()) {
6182     Candidate.Viable = false;
6183     Candidate.FailureKind = ovl_fail_too_many_arguments;
6184     return;
6185   }
6186 
6187   // (C++ 13.3.2p2): A candidate function having more than m parameters
6188   // is viable only if the (m+1)st parameter has a default argument
6189   // (8.3.6). For the purposes of overload resolution, the
6190   // parameter list is truncated on the right, so that there are
6191   // exactly m parameters.
6192   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6193   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6194     // Not enough arguments.
6195     Candidate.Viable = false;
6196     Candidate.FailureKind = ovl_fail_too_few_arguments;
6197     return;
6198   }
6199 
6200   // (CUDA B.1): Check for invalid calls between targets.
6201   if (getLangOpts().CUDA)
6202     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6203       // Skip the check for callers that are implicit members, because in this
6204       // case we may not yet know what the member's target is; the target is
6205       // inferred for the member automatically, based on the bases and fields of
6206       // the class.
6207       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6208         Candidate.Viable = false;
6209         Candidate.FailureKind = ovl_fail_bad_target;
6210         return;
6211       }
6212 
6213   // Determine the implicit conversion sequences for each of the
6214   // arguments.
6215   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6216     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6217       // We already formed a conversion sequence for this parameter during
6218       // template argument deduction.
6219     } else if (ArgIdx < NumParams) {
6220       // (C++ 13.3.2p3): for F to be a viable function, there shall
6221       // exist for each argument an implicit conversion sequence
6222       // (13.3.3.1) that converts that argument to the corresponding
6223       // parameter of F.
6224       QualType ParamType = Proto->getParamType(ArgIdx);
6225       Candidate.Conversions[ArgIdx] = TryCopyInitialization(
6226           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6227           /*InOverloadResolution=*/true,
6228           /*AllowObjCWritebackConversion=*/
6229           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6230       if (Candidate.Conversions[ArgIdx].isBad()) {
6231         Candidate.Viable = false;
6232         Candidate.FailureKind = ovl_fail_bad_conversion;
6233         return;
6234       }
6235     } else {
6236       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6237       // argument for which there is no corresponding parameter is
6238       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6239       Candidate.Conversions[ArgIdx].setEllipsis();
6240     }
6241   }
6242 
6243   if (!AllowExplicit) {
6244     ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6245     if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6246       Candidate.Viable = false;
6247       Candidate.FailureKind = ovl_fail_explicit_resolved;
6248       return;
6249     }
6250   }
6251 
6252   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6253     Candidate.Viable = false;
6254     Candidate.FailureKind = ovl_fail_enable_if;
6255     Candidate.DeductionFailure.Data = FailedAttr;
6256     return;
6257   }
6258 
6259   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6260     Candidate.Viable = false;
6261     Candidate.FailureKind = ovl_fail_ext_disabled;
6262     return;
6263   }
6264 }
6265 
6266 ObjCMethodDecl *
6267 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6268                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6269   if (Methods.size() <= 1)
6270     return nullptr;
6271 
6272   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6273     bool Match = true;
6274     ObjCMethodDecl *Method = Methods[b];
6275     unsigned NumNamedArgs = Sel.getNumArgs();
6276     // Method might have more arguments than selector indicates. This is due
6277     // to addition of c-style arguments in method.
6278     if (Method->param_size() > NumNamedArgs)
6279       NumNamedArgs = Method->param_size();
6280     if (Args.size() < NumNamedArgs)
6281       continue;
6282 
6283     for (unsigned i = 0; i < NumNamedArgs; i++) {
6284       // We can't do any type-checking on a type-dependent argument.
6285       if (Args[i]->isTypeDependent()) {
6286         Match = false;
6287         break;
6288       }
6289 
6290       ParmVarDecl *param = Method->parameters()[i];
6291       Expr *argExpr = Args[i];
6292       assert(argExpr && "SelectBestMethod(): missing expression");
6293 
6294       // Strip the unbridged-cast placeholder expression off unless it's
6295       // a consumed argument.
6296       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6297           !param->hasAttr<CFConsumedAttr>())
6298         argExpr = stripARCUnbridgedCast(argExpr);
6299 
6300       // If the parameter is __unknown_anytype, move on to the next method.
6301       if (param->getType() == Context.UnknownAnyTy) {
6302         Match = false;
6303         break;
6304       }
6305 
6306       ImplicitConversionSequence ConversionState
6307         = TryCopyInitialization(*this, argExpr, param->getType(),
6308                                 /*SuppressUserConversions*/false,
6309                                 /*InOverloadResolution=*/true,
6310                                 /*AllowObjCWritebackConversion=*/
6311                                 getLangOpts().ObjCAutoRefCount,
6312                                 /*AllowExplicit*/false);
6313       // This function looks for a reasonably-exact match, so we consider
6314       // incompatible pointer conversions to be a failure here.
6315       if (ConversionState.isBad() ||
6316           (ConversionState.isStandard() &&
6317            ConversionState.Standard.Second ==
6318                ICK_Incompatible_Pointer_Conversion)) {
6319         Match = false;
6320         break;
6321       }
6322     }
6323     // Promote additional arguments to variadic methods.
6324     if (Match && Method->isVariadic()) {
6325       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6326         if (Args[i]->isTypeDependent()) {
6327           Match = false;
6328           break;
6329         }
6330         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6331                                                           nullptr);
6332         if (Arg.isInvalid()) {
6333           Match = false;
6334           break;
6335         }
6336       }
6337     } else {
6338       // Check for extra arguments to non-variadic methods.
6339       if (Args.size() != NumNamedArgs)
6340         Match = false;
6341       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6342         // Special case when selectors have no argument. In this case, select
6343         // one with the most general result type of 'id'.
6344         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6345           QualType ReturnT = Methods[b]->getReturnType();
6346           if (ReturnT->isObjCIdType())
6347             return Methods[b];
6348         }
6349       }
6350     }
6351 
6352     if (Match)
6353       return Method;
6354   }
6355   return nullptr;
6356 }
6357 
6358 static bool
6359 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6360                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6361                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6362                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6363   if (ThisArg) {
6364     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6365     assert(!isa<CXXConstructorDecl>(Method) &&
6366            "Shouldn't have `this` for ctors!");
6367     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6368     ExprResult R = S.PerformObjectArgumentInitialization(
6369         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6370     if (R.isInvalid())
6371       return false;
6372     ConvertedThis = R.get();
6373   } else {
6374     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6375       (void)MD;
6376       assert((MissingImplicitThis || MD->isStatic() ||
6377               isa<CXXConstructorDecl>(MD)) &&
6378              "Expected `this` for non-ctor instance methods");
6379     }
6380     ConvertedThis = nullptr;
6381   }
6382 
6383   // Ignore any variadic arguments. Converting them is pointless, since the
6384   // user can't refer to them in the function condition.
6385   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6386 
6387   // Convert the arguments.
6388   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6389     ExprResult R;
6390     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6391                                         S.Context, Function->getParamDecl(I)),
6392                                     SourceLocation(), Args[I]);
6393 
6394     if (R.isInvalid())
6395       return false;
6396 
6397     ConvertedArgs.push_back(R.get());
6398   }
6399 
6400   if (Trap.hasErrorOccurred())
6401     return false;
6402 
6403   // Push default arguments if needed.
6404   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6405     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6406       ParmVarDecl *P = Function->getParamDecl(i);
6407       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6408                          ? P->getUninstantiatedDefaultArg()
6409                          : P->getDefaultArg();
6410       // This can only happen in code completion, i.e. when PartialOverloading
6411       // is true.
6412       if (!DefArg)
6413         return false;
6414       ExprResult R =
6415           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6416                                           S.Context, Function->getParamDecl(i)),
6417                                       SourceLocation(), DefArg);
6418       if (R.isInvalid())
6419         return false;
6420       ConvertedArgs.push_back(R.get());
6421     }
6422 
6423     if (Trap.hasErrorOccurred())
6424       return false;
6425   }
6426   return true;
6427 }
6428 
6429 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6430                                   bool MissingImplicitThis) {
6431   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6432   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6433     return nullptr;
6434 
6435   SFINAETrap Trap(*this);
6436   SmallVector<Expr *, 16> ConvertedArgs;
6437   // FIXME: We should look into making enable_if late-parsed.
6438   Expr *DiscardedThis;
6439   if (!convertArgsForAvailabilityChecks(
6440           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6441           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6442     return *EnableIfAttrs.begin();
6443 
6444   for (auto *EIA : EnableIfAttrs) {
6445     APValue Result;
6446     // FIXME: This doesn't consider value-dependent cases, because doing so is
6447     // very difficult. Ideally, we should handle them more gracefully.
6448     if (EIA->getCond()->isValueDependent() ||
6449         !EIA->getCond()->EvaluateWithSubstitution(
6450             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6451       return EIA;
6452 
6453     if (!Result.isInt() || !Result.getInt().getBoolValue())
6454       return EIA;
6455   }
6456   return nullptr;
6457 }
6458 
6459 template <typename CheckFn>
6460 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6461                                         bool ArgDependent, SourceLocation Loc,
6462                                         CheckFn &&IsSuccessful) {
6463   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6464   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6465     if (ArgDependent == DIA->getArgDependent())
6466       Attrs.push_back(DIA);
6467   }
6468 
6469   // Common case: No diagnose_if attributes, so we can quit early.
6470   if (Attrs.empty())
6471     return false;
6472 
6473   auto WarningBegin = std::stable_partition(
6474       Attrs.begin(), Attrs.end(),
6475       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6476 
6477   // Note that diagnose_if attributes are late-parsed, so they appear in the
6478   // correct order (unlike enable_if attributes).
6479   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6480                                IsSuccessful);
6481   if (ErrAttr != WarningBegin) {
6482     const DiagnoseIfAttr *DIA = *ErrAttr;
6483     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6484     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6485         << DIA->getParent() << DIA->getCond()->getSourceRange();
6486     return true;
6487   }
6488 
6489   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6490     if (IsSuccessful(DIA)) {
6491       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6492       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6493           << DIA->getParent() << DIA->getCond()->getSourceRange();
6494     }
6495 
6496   return false;
6497 }
6498 
6499 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6500                                                const Expr *ThisArg,
6501                                                ArrayRef<const Expr *> Args,
6502                                                SourceLocation Loc) {
6503   return diagnoseDiagnoseIfAttrsWith(
6504       *this, Function, /*ArgDependent=*/true, Loc,
6505       [&](const DiagnoseIfAttr *DIA) {
6506         APValue Result;
6507         // It's sane to use the same Args for any redecl of this function, since
6508         // EvaluateWithSubstitution only cares about the position of each
6509         // argument in the arg list, not the ParmVarDecl* it maps to.
6510         if (!DIA->getCond()->EvaluateWithSubstitution(
6511                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6512           return false;
6513         return Result.isInt() && Result.getInt().getBoolValue();
6514       });
6515 }
6516 
6517 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6518                                                  SourceLocation Loc) {
6519   return diagnoseDiagnoseIfAttrsWith(
6520       *this, ND, /*ArgDependent=*/false, Loc,
6521       [&](const DiagnoseIfAttr *DIA) {
6522         bool Result;
6523         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6524                Result;
6525       });
6526 }
6527 
6528 /// Add all of the function declarations in the given function set to
6529 /// the overload candidate set.
6530 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6531                                  ArrayRef<Expr *> Args,
6532                                  OverloadCandidateSet &CandidateSet,
6533                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6534                                  bool SuppressUserConversions,
6535                                  bool PartialOverloading,
6536                                  bool FirstArgumentIsBase) {
6537   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6538     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6539     ArrayRef<Expr *> FunctionArgs = Args;
6540 
6541     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6542     FunctionDecl *FD =
6543         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6544 
6545     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6546       QualType ObjectType;
6547       Expr::Classification ObjectClassification;
6548       if (Args.size() > 0) {
6549         if (Expr *E = Args[0]) {
6550           // Use the explicit base to restrict the lookup:
6551           ObjectType = E->getType();
6552           // Pointers in the object arguments are implicitly dereferenced, so we
6553           // always classify them as l-values.
6554           if (!ObjectType.isNull() && ObjectType->isPointerType())
6555             ObjectClassification = Expr::Classification::makeSimpleLValue();
6556           else
6557             ObjectClassification = E->Classify(Context);
6558         } // .. else there is an implicit base.
6559         FunctionArgs = Args.slice(1);
6560       }
6561       if (FunTmpl) {
6562         AddMethodTemplateCandidate(
6563             FunTmpl, F.getPair(),
6564             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6565             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6566             FunctionArgs, CandidateSet, SuppressUserConversions,
6567             PartialOverloading);
6568       } else {
6569         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6570                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6571                            ObjectClassification, FunctionArgs, CandidateSet,
6572                            SuppressUserConversions, PartialOverloading);
6573       }
6574     } else {
6575       // This branch handles both standalone functions and static methods.
6576 
6577       // Slice the first argument (which is the base) when we access
6578       // static method as non-static.
6579       if (Args.size() > 0 &&
6580           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6581                         !isa<CXXConstructorDecl>(FD)))) {
6582         assert(cast<CXXMethodDecl>(FD)->isStatic());
6583         FunctionArgs = Args.slice(1);
6584       }
6585       if (FunTmpl) {
6586         AddTemplateOverloadCandidate(
6587             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6588             CandidateSet, SuppressUserConversions, PartialOverloading);
6589       } else {
6590         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6591                              SuppressUserConversions, PartialOverloading);
6592       }
6593     }
6594   }
6595 }
6596 
6597 /// AddMethodCandidate - Adds a named decl (which is some kind of
6598 /// method) as a method candidate to the given overload set.
6599 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6600                               QualType ObjectType,
6601                               Expr::Classification ObjectClassification,
6602                               ArrayRef<Expr *> Args,
6603                               OverloadCandidateSet& CandidateSet,
6604                               bool SuppressUserConversions) {
6605   NamedDecl *Decl = FoundDecl.getDecl();
6606   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6607 
6608   if (isa<UsingShadowDecl>(Decl))
6609     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6610 
6611   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6612     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6613            "Expected a member function template");
6614     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6615                                /*ExplicitArgs*/ nullptr, ObjectType,
6616                                ObjectClassification, Args, CandidateSet,
6617                                SuppressUserConversions);
6618   } else {
6619     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6620                        ObjectType, ObjectClassification, Args, CandidateSet,
6621                        SuppressUserConversions);
6622   }
6623 }
6624 
6625 /// AddMethodCandidate - Adds the given C++ member function to the set
6626 /// of candidate functions, using the given function call arguments
6627 /// and the object argument (@c Object). For example, in a call
6628 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6629 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6630 /// allow user-defined conversions via constructors or conversion
6631 /// operators.
6632 void
6633 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6634                          CXXRecordDecl *ActingContext, QualType ObjectType,
6635                          Expr::Classification ObjectClassification,
6636                          ArrayRef<Expr *> Args,
6637                          OverloadCandidateSet &CandidateSet,
6638                          bool SuppressUserConversions,
6639                          bool PartialOverloading,
6640                          ConversionSequenceList EarlyConversions) {
6641   const FunctionProtoType *Proto
6642     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6643   assert(Proto && "Methods without a prototype cannot be overloaded");
6644   assert(!isa<CXXConstructorDecl>(Method) &&
6645          "Use AddOverloadCandidate for constructors");
6646 
6647   if (!CandidateSet.isNewCandidate(Method))
6648     return;
6649 
6650   // C++11 [class.copy]p23: [DR1402]
6651   //   A defaulted move assignment operator that is defined as deleted is
6652   //   ignored by overload resolution.
6653   if (Method->isDefaulted() && Method->isDeleted() &&
6654       Method->isMoveAssignmentOperator())
6655     return;
6656 
6657   // Overload resolution is always an unevaluated context.
6658   EnterExpressionEvaluationContext Unevaluated(
6659       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6660 
6661   // Add this candidate
6662   OverloadCandidate &Candidate =
6663       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6664   Candidate.FoundDecl = FoundDecl;
6665   Candidate.Function = Method;
6666   Candidate.IsSurrogate = false;
6667   Candidate.IgnoreObjectArgument = false;
6668   Candidate.ExplicitCallArguments = Args.size();
6669 
6670   unsigned NumParams = Proto->getNumParams();
6671 
6672   // (C++ 13.3.2p2): A candidate function having fewer than m
6673   // parameters is viable only if it has an ellipsis in its parameter
6674   // list (8.3.5).
6675   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6676       !Proto->isVariadic()) {
6677     Candidate.Viable = false;
6678     Candidate.FailureKind = ovl_fail_too_many_arguments;
6679     return;
6680   }
6681 
6682   // (C++ 13.3.2p2): A candidate function having more than m parameters
6683   // is viable only if the (m+1)st parameter has a default argument
6684   // (8.3.6). For the purposes of overload resolution, the
6685   // parameter list is truncated on the right, so that there are
6686   // exactly m parameters.
6687   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6688   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6689     // Not enough arguments.
6690     Candidate.Viable = false;
6691     Candidate.FailureKind = ovl_fail_too_few_arguments;
6692     return;
6693   }
6694 
6695   Candidate.Viable = true;
6696 
6697   if (Method->isStatic() || ObjectType.isNull())
6698     // The implicit object argument is ignored.
6699     Candidate.IgnoreObjectArgument = true;
6700   else {
6701     // Determine the implicit conversion sequence for the object
6702     // parameter.
6703     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6704         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6705         Method, ActingContext);
6706     if (Candidate.Conversions[0].isBad()) {
6707       Candidate.Viable = false;
6708       Candidate.FailureKind = ovl_fail_bad_conversion;
6709       return;
6710     }
6711   }
6712 
6713   // (CUDA B.1): Check for invalid calls between targets.
6714   if (getLangOpts().CUDA)
6715     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6716       if (!IsAllowedCUDACall(Caller, Method)) {
6717         Candidate.Viable = false;
6718         Candidate.FailureKind = ovl_fail_bad_target;
6719         return;
6720       }
6721 
6722   // Determine the implicit conversion sequences for each of the
6723   // arguments.
6724   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6725     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6726       // We already formed a conversion sequence for this parameter during
6727       // template argument deduction.
6728     } else if (ArgIdx < NumParams) {
6729       // (C++ 13.3.2p3): for F to be a viable function, there shall
6730       // exist for each argument an implicit conversion sequence
6731       // (13.3.3.1) that converts that argument to the corresponding
6732       // parameter of F.
6733       QualType ParamType = Proto->getParamType(ArgIdx);
6734       Candidate.Conversions[ArgIdx + 1]
6735         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6736                                 SuppressUserConversions,
6737                                 /*InOverloadResolution=*/true,
6738                                 /*AllowObjCWritebackConversion=*/
6739                                   getLangOpts().ObjCAutoRefCount);
6740       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6741         Candidate.Viable = false;
6742         Candidate.FailureKind = ovl_fail_bad_conversion;
6743         return;
6744       }
6745     } else {
6746       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6747       // argument for which there is no corresponding parameter is
6748       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6749       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6750     }
6751   }
6752 
6753   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6754     Candidate.Viable = false;
6755     Candidate.FailureKind = ovl_fail_enable_if;
6756     Candidate.DeductionFailure.Data = FailedAttr;
6757     return;
6758   }
6759 
6760   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6761       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6762     Candidate.Viable = false;
6763     Candidate.FailureKind = ovl_non_default_multiversion_function;
6764   }
6765 }
6766 
6767 /// Add a C++ member function template as a candidate to the candidate
6768 /// set, using template argument deduction to produce an appropriate member
6769 /// function template specialization.
6770 void
6771 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6772                                  DeclAccessPair FoundDecl,
6773                                  CXXRecordDecl *ActingContext,
6774                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6775                                  QualType ObjectType,
6776                                  Expr::Classification ObjectClassification,
6777                                  ArrayRef<Expr *> Args,
6778                                  OverloadCandidateSet& CandidateSet,
6779                                  bool SuppressUserConversions,
6780                                  bool PartialOverloading) {
6781   if (!CandidateSet.isNewCandidate(MethodTmpl))
6782     return;
6783 
6784   // C++ [over.match.funcs]p7:
6785   //   In each case where a candidate is a function template, candidate
6786   //   function template specializations are generated using template argument
6787   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6788   //   candidate functions in the usual way.113) A given name can refer to one
6789   //   or more function templates and also to a set of overloaded non-template
6790   //   functions. In such a case, the candidate functions generated from each
6791   //   function template are combined with the set of non-template candidate
6792   //   functions.
6793   TemplateDeductionInfo Info(CandidateSet.getLocation());
6794   FunctionDecl *Specialization = nullptr;
6795   ConversionSequenceList Conversions;
6796   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6797           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6798           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6799             return CheckNonDependentConversions(
6800                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6801                 SuppressUserConversions, ActingContext, ObjectType,
6802                 ObjectClassification);
6803           })) {
6804     OverloadCandidate &Candidate =
6805         CandidateSet.addCandidate(Conversions.size(), Conversions);
6806     Candidate.FoundDecl = FoundDecl;
6807     Candidate.Function = MethodTmpl->getTemplatedDecl();
6808     Candidate.Viable = false;
6809     Candidate.IsSurrogate = false;
6810     Candidate.IgnoreObjectArgument =
6811         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6812         ObjectType.isNull();
6813     Candidate.ExplicitCallArguments = Args.size();
6814     if (Result == TDK_NonDependentConversionFailure)
6815       Candidate.FailureKind = ovl_fail_bad_conversion;
6816     else {
6817       Candidate.FailureKind = ovl_fail_bad_deduction;
6818       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6819                                                             Info);
6820     }
6821     return;
6822   }
6823 
6824   // Add the function template specialization produced by template argument
6825   // deduction as a candidate.
6826   assert(Specialization && "Missing member function template specialization?");
6827   assert(isa<CXXMethodDecl>(Specialization) &&
6828          "Specialization is not a member function?");
6829   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6830                      ActingContext, ObjectType, ObjectClassification, Args,
6831                      CandidateSet, SuppressUserConversions, PartialOverloading,
6832                      Conversions);
6833 }
6834 
6835 /// Add a C++ function template specialization as a candidate
6836 /// in the candidate set, using template argument deduction to produce
6837 /// an appropriate function template specialization.
6838 void Sema::AddTemplateOverloadCandidate(
6839     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6840     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6841     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6842     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) {
6843   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6844     return;
6845 
6846   // C++ [over.match.funcs]p7:
6847   //   In each case where a candidate is a function template, candidate
6848   //   function template specializations are generated using template argument
6849   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6850   //   candidate functions in the usual way.113) A given name can refer to one
6851   //   or more function templates and also to a set of overloaded non-template
6852   //   functions. In such a case, the candidate functions generated from each
6853   //   function template are combined with the set of non-template candidate
6854   //   functions.
6855   TemplateDeductionInfo Info(CandidateSet.getLocation());
6856   FunctionDecl *Specialization = nullptr;
6857   ConversionSequenceList Conversions;
6858   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6859           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6860           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6861             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6862                                                 Args, CandidateSet, Conversions,
6863                                                 SuppressUserConversions);
6864           })) {
6865     OverloadCandidate &Candidate =
6866         CandidateSet.addCandidate(Conversions.size(), Conversions);
6867     Candidate.FoundDecl = FoundDecl;
6868     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6869     Candidate.Viable = false;
6870     Candidate.IsSurrogate = false;
6871     Candidate.IsADLCandidate = IsADLCandidate;
6872     // Ignore the object argument if there is one, since we don't have an object
6873     // type.
6874     Candidate.IgnoreObjectArgument =
6875         isa<CXXMethodDecl>(Candidate.Function) &&
6876         !isa<CXXConstructorDecl>(Candidate.Function);
6877     Candidate.ExplicitCallArguments = Args.size();
6878     if (Result == TDK_NonDependentConversionFailure)
6879       Candidate.FailureKind = ovl_fail_bad_conversion;
6880     else {
6881       Candidate.FailureKind = ovl_fail_bad_deduction;
6882       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6883                                                             Info);
6884     }
6885     return;
6886   }
6887 
6888   // Add the function template specialization produced by template argument
6889   // deduction as a candidate.
6890   assert(Specialization && "Missing function template specialization?");
6891   AddOverloadCandidate(
6892       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6893       PartialOverloading, AllowExplicit,
6894       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions);
6895 }
6896 
6897 /// Check that implicit conversion sequences can be formed for each argument
6898 /// whose corresponding parameter has a non-dependent type, per DR1391's
6899 /// [temp.deduct.call]p10.
6900 bool Sema::CheckNonDependentConversions(
6901     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6902     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6903     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6904     CXXRecordDecl *ActingContext, QualType ObjectType,
6905     Expr::Classification ObjectClassification) {
6906   // FIXME: The cases in which we allow explicit conversions for constructor
6907   // arguments never consider calling a constructor template. It's not clear
6908   // that is correct.
6909   const bool AllowExplicit = false;
6910 
6911   auto *FD = FunctionTemplate->getTemplatedDecl();
6912   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6913   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6914   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6915 
6916   Conversions =
6917       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6918 
6919   // Overload resolution is always an unevaluated context.
6920   EnterExpressionEvaluationContext Unevaluated(
6921       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6922 
6923   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6924   // require that, but this check should never result in a hard error, and
6925   // overload resolution is permitted to sidestep instantiations.
6926   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6927       !ObjectType.isNull()) {
6928     Conversions[0] = TryObjectArgumentInitialization(
6929         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6930         Method, ActingContext);
6931     if (Conversions[0].isBad())
6932       return true;
6933   }
6934 
6935   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6936        ++I) {
6937     QualType ParamType = ParamTypes[I];
6938     if (!ParamType->isDependentType()) {
6939       Conversions[ThisConversions + I]
6940         = TryCopyInitialization(*this, Args[I], ParamType,
6941                                 SuppressUserConversions,
6942                                 /*InOverloadResolution=*/true,
6943                                 /*AllowObjCWritebackConversion=*/
6944                                   getLangOpts().ObjCAutoRefCount,
6945                                 AllowExplicit);
6946       if (Conversions[ThisConversions + I].isBad())
6947         return true;
6948     }
6949   }
6950 
6951   return false;
6952 }
6953 
6954 /// Determine whether this is an allowable conversion from the result
6955 /// of an explicit conversion operator to the expected type, per C++
6956 /// [over.match.conv]p1 and [over.match.ref]p1.
6957 ///
6958 /// \param ConvType The return type of the conversion function.
6959 ///
6960 /// \param ToType The type we are converting to.
6961 ///
6962 /// \param AllowObjCPointerConversion Allow a conversion from one
6963 /// Objective-C pointer to another.
6964 ///
6965 /// \returns true if the conversion is allowable, false otherwise.
6966 static bool isAllowableExplicitConversion(Sema &S,
6967                                           QualType ConvType, QualType ToType,
6968                                           bool AllowObjCPointerConversion) {
6969   QualType ToNonRefType = ToType.getNonReferenceType();
6970 
6971   // Easy case: the types are the same.
6972   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6973     return true;
6974 
6975   // Allow qualification conversions.
6976   bool ObjCLifetimeConversion;
6977   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6978                                   ObjCLifetimeConversion))
6979     return true;
6980 
6981   // If we're not allowed to consider Objective-C pointer conversions,
6982   // we're done.
6983   if (!AllowObjCPointerConversion)
6984     return false;
6985 
6986   // Is this an Objective-C pointer conversion?
6987   bool IncompatibleObjC = false;
6988   QualType ConvertedType;
6989   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6990                                    IncompatibleObjC);
6991 }
6992 
6993 /// AddConversionCandidate - Add a C++ conversion function as a
6994 /// candidate in the candidate set (C++ [over.match.conv],
6995 /// C++ [over.match.copy]). From is the expression we're converting from,
6996 /// and ToType is the type that we're eventually trying to convert to
6997 /// (which may or may not be the same type as the type that the
6998 /// conversion function produces).
6999 void Sema::AddConversionCandidate(
7000     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7001     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7002     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7003     bool AllowExplicit, bool AllowResultConversion) {
7004   assert(!Conversion->getDescribedFunctionTemplate() &&
7005          "Conversion function templates use AddTemplateConversionCandidate");
7006   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7007   if (!CandidateSet.isNewCandidate(Conversion))
7008     return;
7009 
7010   // If the conversion function has an undeduced return type, trigger its
7011   // deduction now.
7012   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7013     if (DeduceReturnType(Conversion, From->getExprLoc()))
7014       return;
7015     ConvType = Conversion->getConversionType().getNonReferenceType();
7016   }
7017 
7018   // If we don't allow any conversion of the result type, ignore conversion
7019   // functions that don't convert to exactly (possibly cv-qualified) T.
7020   if (!AllowResultConversion &&
7021       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7022     return;
7023 
7024   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7025   // operator is only a candidate if its return type is the target type or
7026   // can be converted to the target type with a qualification conversion.
7027   if (Conversion->isExplicit() &&
7028       !isAllowableExplicitConversion(*this, ConvType, ToType,
7029                                      AllowObjCConversionOnExplicit))
7030     return;
7031 
7032   // Overload resolution is always an unevaluated context.
7033   EnterExpressionEvaluationContext Unevaluated(
7034       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7035 
7036   // Add this candidate
7037   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7038   Candidate.FoundDecl = FoundDecl;
7039   Candidate.Function = Conversion;
7040   Candidate.IsSurrogate = false;
7041   Candidate.IgnoreObjectArgument = false;
7042   Candidate.FinalConversion.setAsIdentityConversion();
7043   Candidate.FinalConversion.setFromType(ConvType);
7044   Candidate.FinalConversion.setAllToTypes(ToType);
7045   Candidate.Viable = true;
7046   Candidate.ExplicitCallArguments = 1;
7047 
7048   // C++ [over.match.funcs]p4:
7049   //   For conversion functions, the function is considered to be a member of
7050   //   the class of the implicit implied object argument for the purpose of
7051   //   defining the type of the implicit object parameter.
7052   //
7053   // Determine the implicit conversion sequence for the implicit
7054   // object parameter.
7055   QualType ImplicitParamType = From->getType();
7056   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7057     ImplicitParamType = FromPtrType->getPointeeType();
7058   CXXRecordDecl *ConversionContext
7059     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7060 
7061   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7062       *this, CandidateSet.getLocation(), From->getType(),
7063       From->Classify(Context), Conversion, ConversionContext);
7064 
7065   if (Candidate.Conversions[0].isBad()) {
7066     Candidate.Viable = false;
7067     Candidate.FailureKind = ovl_fail_bad_conversion;
7068     return;
7069   }
7070 
7071   // We won't go through a user-defined type conversion function to convert a
7072   // derived to base as such conversions are given Conversion Rank. They only
7073   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7074   QualType FromCanon
7075     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7076   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7077   if (FromCanon == ToCanon ||
7078       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7079     Candidate.Viable = false;
7080     Candidate.FailureKind = ovl_fail_trivial_conversion;
7081     return;
7082   }
7083 
7084   // To determine what the conversion from the result of calling the
7085   // conversion function to the type we're eventually trying to
7086   // convert to (ToType), we need to synthesize a call to the
7087   // conversion function and attempt copy initialization from it. This
7088   // makes sure that we get the right semantics with respect to
7089   // lvalues/rvalues and the type. Fortunately, we can allocate this
7090   // call on the stack and we don't need its arguments to be
7091   // well-formed.
7092   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7093                             VK_LValue, From->getBeginLoc());
7094   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7095                                 Context.getPointerType(Conversion->getType()),
7096                                 CK_FunctionToPointerDecay,
7097                                 &ConversionRef, VK_RValue);
7098 
7099   QualType ConversionType = Conversion->getConversionType();
7100   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7101     Candidate.Viable = false;
7102     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7103     return;
7104   }
7105 
7106   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7107 
7108   // Note that it is safe to allocate CallExpr on the stack here because
7109   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7110   // allocator).
7111   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7112 
7113   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7114   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7115       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7116 
7117   ImplicitConversionSequence ICS =
7118       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7119                             /*SuppressUserConversions=*/true,
7120                             /*InOverloadResolution=*/false,
7121                             /*AllowObjCWritebackConversion=*/false);
7122 
7123   switch (ICS.getKind()) {
7124   case ImplicitConversionSequence::StandardConversion:
7125     Candidate.FinalConversion = ICS.Standard;
7126 
7127     // C++ [over.ics.user]p3:
7128     //   If the user-defined conversion is specified by a specialization of a
7129     //   conversion function template, the second standard conversion sequence
7130     //   shall have exact match rank.
7131     if (Conversion->getPrimaryTemplate() &&
7132         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7133       Candidate.Viable = false;
7134       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7135       return;
7136     }
7137 
7138     // C++0x [dcl.init.ref]p5:
7139     //    In the second case, if the reference is an rvalue reference and
7140     //    the second standard conversion sequence of the user-defined
7141     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7142     //    program is ill-formed.
7143     if (ToType->isRValueReferenceType() &&
7144         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7145       Candidate.Viable = false;
7146       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7147       return;
7148     }
7149     break;
7150 
7151   case ImplicitConversionSequence::BadConversion:
7152     Candidate.Viable = false;
7153     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7154     return;
7155 
7156   default:
7157     llvm_unreachable(
7158            "Can only end up with a standard conversion sequence or failure");
7159   }
7160 
7161   if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7162                             ExplicitSpecKind::ResolvedFalse) {
7163     Candidate.Viable = false;
7164     Candidate.FailureKind = ovl_fail_explicit_resolved;
7165     return;
7166   }
7167 
7168   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7169     Candidate.Viable = false;
7170     Candidate.FailureKind = ovl_fail_enable_if;
7171     Candidate.DeductionFailure.Data = FailedAttr;
7172     return;
7173   }
7174 
7175   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7176       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7177     Candidate.Viable = false;
7178     Candidate.FailureKind = ovl_non_default_multiversion_function;
7179   }
7180 }
7181 
7182 /// Adds a conversion function template specialization
7183 /// candidate to the overload set, using template argument deduction
7184 /// to deduce the template arguments of the conversion function
7185 /// template from the type that we are converting to (C++
7186 /// [temp.deduct.conv]).
7187 void Sema::AddTemplateConversionCandidate(
7188     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7189     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7190     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7191     bool AllowExplicit, bool AllowResultConversion) {
7192   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7193          "Only conversion function templates permitted here");
7194 
7195   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7196     return;
7197 
7198   TemplateDeductionInfo Info(CandidateSet.getLocation());
7199   CXXConversionDecl *Specialization = nullptr;
7200   if (TemplateDeductionResult Result
7201         = DeduceTemplateArguments(FunctionTemplate, ToType,
7202                                   Specialization, Info)) {
7203     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7204     Candidate.FoundDecl = FoundDecl;
7205     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7206     Candidate.Viable = false;
7207     Candidate.FailureKind = ovl_fail_bad_deduction;
7208     Candidate.IsSurrogate = false;
7209     Candidate.IgnoreObjectArgument = false;
7210     Candidate.ExplicitCallArguments = 1;
7211     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7212                                                           Info);
7213     return;
7214   }
7215 
7216   // Add the conversion function template specialization produced by
7217   // template argument deduction as a candidate.
7218   assert(Specialization && "Missing function template specialization?");
7219   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7220                          CandidateSet, AllowObjCConversionOnExplicit,
7221                          AllowExplicit, AllowResultConversion);
7222 }
7223 
7224 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7225 /// converts the given @c Object to a function pointer via the
7226 /// conversion function @c Conversion, and then attempts to call it
7227 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7228 /// the type of function that we'll eventually be calling.
7229 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7230                                  DeclAccessPair FoundDecl,
7231                                  CXXRecordDecl *ActingContext,
7232                                  const FunctionProtoType *Proto,
7233                                  Expr *Object,
7234                                  ArrayRef<Expr *> Args,
7235                                  OverloadCandidateSet& CandidateSet) {
7236   if (!CandidateSet.isNewCandidate(Conversion))
7237     return;
7238 
7239   // Overload resolution is always an unevaluated context.
7240   EnterExpressionEvaluationContext Unevaluated(
7241       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7242 
7243   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7244   Candidate.FoundDecl = FoundDecl;
7245   Candidate.Function = nullptr;
7246   Candidate.Surrogate = Conversion;
7247   Candidate.Viable = true;
7248   Candidate.IsSurrogate = true;
7249   Candidate.IgnoreObjectArgument = false;
7250   Candidate.ExplicitCallArguments = Args.size();
7251 
7252   // Determine the implicit conversion sequence for the implicit
7253   // object parameter.
7254   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7255       *this, CandidateSet.getLocation(), Object->getType(),
7256       Object->Classify(Context), Conversion, ActingContext);
7257   if (ObjectInit.isBad()) {
7258     Candidate.Viable = false;
7259     Candidate.FailureKind = ovl_fail_bad_conversion;
7260     Candidate.Conversions[0] = ObjectInit;
7261     return;
7262   }
7263 
7264   // The first conversion is actually a user-defined conversion whose
7265   // first conversion is ObjectInit's standard conversion (which is
7266   // effectively a reference binding). Record it as such.
7267   Candidate.Conversions[0].setUserDefined();
7268   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7269   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7270   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7271   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7272   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7273   Candidate.Conversions[0].UserDefined.After
7274     = Candidate.Conversions[0].UserDefined.Before;
7275   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7276 
7277   // Find the
7278   unsigned NumParams = Proto->getNumParams();
7279 
7280   // (C++ 13.3.2p2): A candidate function having fewer than m
7281   // parameters is viable only if it has an ellipsis in its parameter
7282   // list (8.3.5).
7283   if (Args.size() > NumParams && !Proto->isVariadic()) {
7284     Candidate.Viable = false;
7285     Candidate.FailureKind = ovl_fail_too_many_arguments;
7286     return;
7287   }
7288 
7289   // Function types don't have any default arguments, so just check if
7290   // we have enough arguments.
7291   if (Args.size() < NumParams) {
7292     // Not enough arguments.
7293     Candidate.Viable = false;
7294     Candidate.FailureKind = ovl_fail_too_few_arguments;
7295     return;
7296   }
7297 
7298   // Determine the implicit conversion sequences for each of the
7299   // arguments.
7300   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7301     if (ArgIdx < NumParams) {
7302       // (C++ 13.3.2p3): for F to be a viable function, there shall
7303       // exist for each argument an implicit conversion sequence
7304       // (13.3.3.1) that converts that argument to the corresponding
7305       // parameter of F.
7306       QualType ParamType = Proto->getParamType(ArgIdx);
7307       Candidate.Conversions[ArgIdx + 1]
7308         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7309                                 /*SuppressUserConversions=*/false,
7310                                 /*InOverloadResolution=*/false,
7311                                 /*AllowObjCWritebackConversion=*/
7312                                   getLangOpts().ObjCAutoRefCount);
7313       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7314         Candidate.Viable = false;
7315         Candidate.FailureKind = ovl_fail_bad_conversion;
7316         return;
7317       }
7318     } else {
7319       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7320       // argument for which there is no corresponding parameter is
7321       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7322       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7323     }
7324   }
7325 
7326   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7327     Candidate.Viable = false;
7328     Candidate.FailureKind = ovl_fail_enable_if;
7329     Candidate.DeductionFailure.Data = FailedAttr;
7330     return;
7331   }
7332 }
7333 
7334 /// Add overload candidates for overloaded operators that are
7335 /// member functions.
7336 ///
7337 /// Add the overloaded operator candidates that are member functions
7338 /// for the operator Op that was used in an operator expression such
7339 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7340 /// CandidateSet will store the added overload candidates. (C++
7341 /// [over.match.oper]).
7342 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7343                                        SourceLocation OpLoc,
7344                                        ArrayRef<Expr *> Args,
7345                                        OverloadCandidateSet& CandidateSet,
7346                                        SourceRange OpRange) {
7347   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7348 
7349   // C++ [over.match.oper]p3:
7350   //   For a unary operator @ with an operand of a type whose
7351   //   cv-unqualified version is T1, and for a binary operator @ with
7352   //   a left operand of a type whose cv-unqualified version is T1 and
7353   //   a right operand of a type whose cv-unqualified version is T2,
7354   //   three sets of candidate functions, designated member
7355   //   candidates, non-member candidates and built-in candidates, are
7356   //   constructed as follows:
7357   QualType T1 = Args[0]->getType();
7358 
7359   //     -- If T1 is a complete class type or a class currently being
7360   //        defined, the set of member candidates is the result of the
7361   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7362   //        the set of member candidates is empty.
7363   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7364     // Complete the type if it can be completed.
7365     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7366       return;
7367     // If the type is neither complete nor being defined, bail out now.
7368     if (!T1Rec->getDecl()->getDefinition())
7369       return;
7370 
7371     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7372     LookupQualifiedName(Operators, T1Rec->getDecl());
7373     Operators.suppressDiagnostics();
7374 
7375     for (LookupResult::iterator Oper = Operators.begin(),
7376                              OperEnd = Operators.end();
7377          Oper != OperEnd;
7378          ++Oper)
7379       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7380                          Args[0]->Classify(Context), Args.slice(1),
7381                          CandidateSet, /*SuppressUserConversion=*/false);
7382   }
7383 }
7384 
7385 /// AddBuiltinCandidate - Add a candidate for a built-in
7386 /// operator. ResultTy and ParamTys are the result and parameter types
7387 /// of the built-in candidate, respectively. Args and NumArgs are the
7388 /// arguments being passed to the candidate. IsAssignmentOperator
7389 /// should be true when this built-in candidate is an assignment
7390 /// operator. NumContextualBoolArguments is the number of arguments
7391 /// (at the beginning of the argument list) that will be contextually
7392 /// converted to bool.
7393 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7394                                OverloadCandidateSet& CandidateSet,
7395                                bool IsAssignmentOperator,
7396                                unsigned NumContextualBoolArguments) {
7397   // Overload resolution is always an unevaluated context.
7398   EnterExpressionEvaluationContext Unevaluated(
7399       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7400 
7401   // Add this candidate
7402   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7403   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7404   Candidate.Function = nullptr;
7405   Candidate.IsSurrogate = false;
7406   Candidate.IgnoreObjectArgument = false;
7407   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7408 
7409   // Determine the implicit conversion sequences for each of the
7410   // arguments.
7411   Candidate.Viable = true;
7412   Candidate.ExplicitCallArguments = Args.size();
7413   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7414     // C++ [over.match.oper]p4:
7415     //   For the built-in assignment operators, conversions of the
7416     //   left operand are restricted as follows:
7417     //     -- no temporaries are introduced to hold the left operand, and
7418     //     -- no user-defined conversions are applied to the left
7419     //        operand to achieve a type match with the left-most
7420     //        parameter of a built-in candidate.
7421     //
7422     // We block these conversions by turning off user-defined
7423     // conversions, since that is the only way that initialization of
7424     // a reference to a non-class type can occur from something that
7425     // is not of the same type.
7426     if (ArgIdx < NumContextualBoolArguments) {
7427       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7428              "Contextual conversion to bool requires bool type");
7429       Candidate.Conversions[ArgIdx]
7430         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7431     } else {
7432       Candidate.Conversions[ArgIdx]
7433         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7434                                 ArgIdx == 0 && IsAssignmentOperator,
7435                                 /*InOverloadResolution=*/false,
7436                                 /*AllowObjCWritebackConversion=*/
7437                                   getLangOpts().ObjCAutoRefCount);
7438     }
7439     if (Candidate.Conversions[ArgIdx].isBad()) {
7440       Candidate.Viable = false;
7441       Candidate.FailureKind = ovl_fail_bad_conversion;
7442       break;
7443     }
7444   }
7445 }
7446 
7447 namespace {
7448 
7449 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7450 /// candidate operator functions for built-in operators (C++
7451 /// [over.built]). The types are separated into pointer types and
7452 /// enumeration types.
7453 class BuiltinCandidateTypeSet  {
7454   /// TypeSet - A set of types.
7455   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7456                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7457 
7458   /// PointerTypes - The set of pointer types that will be used in the
7459   /// built-in candidates.
7460   TypeSet PointerTypes;
7461 
7462   /// MemberPointerTypes - The set of member pointer types that will be
7463   /// used in the built-in candidates.
7464   TypeSet MemberPointerTypes;
7465 
7466   /// EnumerationTypes - The set of enumeration types that will be
7467   /// used in the built-in candidates.
7468   TypeSet EnumerationTypes;
7469 
7470   /// The set of vector types that will be used in the built-in
7471   /// candidates.
7472   TypeSet VectorTypes;
7473 
7474   /// A flag indicating non-record types are viable candidates
7475   bool HasNonRecordTypes;
7476 
7477   /// A flag indicating whether either arithmetic or enumeration types
7478   /// were present in the candidate set.
7479   bool HasArithmeticOrEnumeralTypes;
7480 
7481   /// A flag indicating whether the nullptr type was present in the
7482   /// candidate set.
7483   bool HasNullPtrType;
7484 
7485   /// Sema - The semantic analysis instance where we are building the
7486   /// candidate type set.
7487   Sema &SemaRef;
7488 
7489   /// Context - The AST context in which we will build the type sets.
7490   ASTContext &Context;
7491 
7492   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7493                                                const Qualifiers &VisibleQuals);
7494   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7495 
7496 public:
7497   /// iterator - Iterates through the types that are part of the set.
7498   typedef TypeSet::iterator iterator;
7499 
7500   BuiltinCandidateTypeSet(Sema &SemaRef)
7501     : HasNonRecordTypes(false),
7502       HasArithmeticOrEnumeralTypes(false),
7503       HasNullPtrType(false),
7504       SemaRef(SemaRef),
7505       Context(SemaRef.Context) { }
7506 
7507   void AddTypesConvertedFrom(QualType Ty,
7508                              SourceLocation Loc,
7509                              bool AllowUserConversions,
7510                              bool AllowExplicitConversions,
7511                              const Qualifiers &VisibleTypeConversionsQuals);
7512 
7513   /// pointer_begin - First pointer type found;
7514   iterator pointer_begin() { return PointerTypes.begin(); }
7515 
7516   /// pointer_end - Past the last pointer type found;
7517   iterator pointer_end() { return PointerTypes.end(); }
7518 
7519   /// member_pointer_begin - First member pointer type found;
7520   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7521 
7522   /// member_pointer_end - Past the last member pointer type found;
7523   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7524 
7525   /// enumeration_begin - First enumeration type found;
7526   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7527 
7528   /// enumeration_end - Past the last enumeration type found;
7529   iterator enumeration_end() { return EnumerationTypes.end(); }
7530 
7531   iterator vector_begin() { return VectorTypes.begin(); }
7532   iterator vector_end() { return VectorTypes.end(); }
7533 
7534   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7535   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7536   bool hasNullPtrType() const { return HasNullPtrType; }
7537 };
7538 
7539 } // end anonymous namespace
7540 
7541 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7542 /// the set of pointer types along with any more-qualified variants of
7543 /// that type. For example, if @p Ty is "int const *", this routine
7544 /// will add "int const *", "int const volatile *", "int const
7545 /// restrict *", and "int const volatile restrict *" to the set of
7546 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7547 /// false otherwise.
7548 ///
7549 /// FIXME: what to do about extended qualifiers?
7550 bool
7551 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7552                                              const Qualifiers &VisibleQuals) {
7553 
7554   // Insert this type.
7555   if (!PointerTypes.insert(Ty))
7556     return false;
7557 
7558   QualType PointeeTy;
7559   const PointerType *PointerTy = Ty->getAs<PointerType>();
7560   bool buildObjCPtr = false;
7561   if (!PointerTy) {
7562     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7563     PointeeTy = PTy->getPointeeType();
7564     buildObjCPtr = true;
7565   } else {
7566     PointeeTy = PointerTy->getPointeeType();
7567   }
7568 
7569   // Don't add qualified variants of arrays. For one, they're not allowed
7570   // (the qualifier would sink to the element type), and for another, the
7571   // only overload situation where it matters is subscript or pointer +- int,
7572   // and those shouldn't have qualifier variants anyway.
7573   if (PointeeTy->isArrayType())
7574     return true;
7575 
7576   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7577   bool hasVolatile = VisibleQuals.hasVolatile();
7578   bool hasRestrict = VisibleQuals.hasRestrict();
7579 
7580   // Iterate through all strict supersets of BaseCVR.
7581   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7582     if ((CVR | BaseCVR) != CVR) continue;
7583     // Skip over volatile if no volatile found anywhere in the types.
7584     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7585 
7586     // Skip over restrict if no restrict found anywhere in the types, or if
7587     // the type cannot be restrict-qualified.
7588     if ((CVR & Qualifiers::Restrict) &&
7589         (!hasRestrict ||
7590          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7591       continue;
7592 
7593     // Build qualified pointee type.
7594     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7595 
7596     // Build qualified pointer type.
7597     QualType QPointerTy;
7598     if (!buildObjCPtr)
7599       QPointerTy = Context.getPointerType(QPointeeTy);
7600     else
7601       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7602 
7603     // Insert qualified pointer type.
7604     PointerTypes.insert(QPointerTy);
7605   }
7606 
7607   return true;
7608 }
7609 
7610 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7611 /// to the set of pointer types along with any more-qualified variants of
7612 /// that type. For example, if @p Ty is "int const *", this routine
7613 /// will add "int const *", "int const volatile *", "int const
7614 /// restrict *", and "int const volatile restrict *" to the set of
7615 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7616 /// false otherwise.
7617 ///
7618 /// FIXME: what to do about extended qualifiers?
7619 bool
7620 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7621     QualType Ty) {
7622   // Insert this type.
7623   if (!MemberPointerTypes.insert(Ty))
7624     return false;
7625 
7626   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7627   assert(PointerTy && "type was not a member pointer type!");
7628 
7629   QualType PointeeTy = PointerTy->getPointeeType();
7630   // Don't add qualified variants of arrays. For one, they're not allowed
7631   // (the qualifier would sink to the element type), and for another, the
7632   // only overload situation where it matters is subscript or pointer +- int,
7633   // and those shouldn't have qualifier variants anyway.
7634   if (PointeeTy->isArrayType())
7635     return true;
7636   const Type *ClassTy = PointerTy->getClass();
7637 
7638   // Iterate through all strict supersets of the pointee type's CVR
7639   // qualifiers.
7640   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7641   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7642     if ((CVR | BaseCVR) != CVR) continue;
7643 
7644     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7645     MemberPointerTypes.insert(
7646       Context.getMemberPointerType(QPointeeTy, ClassTy));
7647   }
7648 
7649   return true;
7650 }
7651 
7652 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7653 /// Ty can be implicit converted to the given set of @p Types. We're
7654 /// primarily interested in pointer types and enumeration types. We also
7655 /// take member pointer types, for the conditional operator.
7656 /// AllowUserConversions is true if we should look at the conversion
7657 /// functions of a class type, and AllowExplicitConversions if we
7658 /// should also include the explicit conversion functions of a class
7659 /// type.
7660 void
7661 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7662                                                SourceLocation Loc,
7663                                                bool AllowUserConversions,
7664                                                bool AllowExplicitConversions,
7665                                                const Qualifiers &VisibleQuals) {
7666   // Only deal with canonical types.
7667   Ty = Context.getCanonicalType(Ty);
7668 
7669   // Look through reference types; they aren't part of the type of an
7670   // expression for the purposes of conversions.
7671   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7672     Ty = RefTy->getPointeeType();
7673 
7674   // If we're dealing with an array type, decay to the pointer.
7675   if (Ty->isArrayType())
7676     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7677 
7678   // Otherwise, we don't care about qualifiers on the type.
7679   Ty = Ty.getLocalUnqualifiedType();
7680 
7681   // Flag if we ever add a non-record type.
7682   const RecordType *TyRec = Ty->getAs<RecordType>();
7683   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7684 
7685   // Flag if we encounter an arithmetic type.
7686   HasArithmeticOrEnumeralTypes =
7687     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7688 
7689   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7690     PointerTypes.insert(Ty);
7691   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7692     // Insert our type, and its more-qualified variants, into the set
7693     // of types.
7694     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7695       return;
7696   } else if (Ty->isMemberPointerType()) {
7697     // Member pointers are far easier, since the pointee can't be converted.
7698     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7699       return;
7700   } else if (Ty->isEnumeralType()) {
7701     HasArithmeticOrEnumeralTypes = true;
7702     EnumerationTypes.insert(Ty);
7703   } else if (Ty->isVectorType()) {
7704     // We treat vector types as arithmetic types in many contexts as an
7705     // extension.
7706     HasArithmeticOrEnumeralTypes = true;
7707     VectorTypes.insert(Ty);
7708   } else if (Ty->isNullPtrType()) {
7709     HasNullPtrType = true;
7710   } else if (AllowUserConversions && TyRec) {
7711     // No conversion functions in incomplete types.
7712     if (!SemaRef.isCompleteType(Loc, Ty))
7713       return;
7714 
7715     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7716     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7717       if (isa<UsingShadowDecl>(D))
7718         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7719 
7720       // Skip conversion function templates; they don't tell us anything
7721       // about which builtin types we can convert to.
7722       if (isa<FunctionTemplateDecl>(D))
7723         continue;
7724 
7725       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7726       if (AllowExplicitConversions || !Conv->isExplicit()) {
7727         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7728                               VisibleQuals);
7729       }
7730     }
7731   }
7732 }
7733 /// Helper function for adjusting address spaces for the pointer or reference
7734 /// operands of builtin operators depending on the argument.
7735 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7736                                                         Expr *Arg) {
7737   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7738 }
7739 
7740 /// Helper function for AddBuiltinOperatorCandidates() that adds
7741 /// the volatile- and non-volatile-qualified assignment operators for the
7742 /// given type to the candidate set.
7743 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7744                                                    QualType T,
7745                                                    ArrayRef<Expr *> Args,
7746                                     OverloadCandidateSet &CandidateSet) {
7747   QualType ParamTypes[2];
7748 
7749   // T& operator=(T&, T)
7750   ParamTypes[0] = S.Context.getLValueReferenceType(
7751       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7752   ParamTypes[1] = T;
7753   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7754                         /*IsAssignmentOperator=*/true);
7755 
7756   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7757     // volatile T& operator=(volatile T&, T)
7758     ParamTypes[0] = S.Context.getLValueReferenceType(
7759         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7760                                                 Args[0]));
7761     ParamTypes[1] = T;
7762     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7763                           /*IsAssignmentOperator=*/true);
7764   }
7765 }
7766 
7767 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7768 /// if any, found in visible type conversion functions found in ArgExpr's type.
7769 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7770     Qualifiers VRQuals;
7771     const RecordType *TyRec;
7772     if (const MemberPointerType *RHSMPType =
7773         ArgExpr->getType()->getAs<MemberPointerType>())
7774       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7775     else
7776       TyRec = ArgExpr->getType()->getAs<RecordType>();
7777     if (!TyRec) {
7778       // Just to be safe, assume the worst case.
7779       VRQuals.addVolatile();
7780       VRQuals.addRestrict();
7781       return VRQuals;
7782     }
7783 
7784     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7785     if (!ClassDecl->hasDefinition())
7786       return VRQuals;
7787 
7788     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7789       if (isa<UsingShadowDecl>(D))
7790         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7791       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7792         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7793         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7794           CanTy = ResTypeRef->getPointeeType();
7795         // Need to go down the pointer/mempointer chain and add qualifiers
7796         // as see them.
7797         bool done = false;
7798         while (!done) {
7799           if (CanTy.isRestrictQualified())
7800             VRQuals.addRestrict();
7801           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7802             CanTy = ResTypePtr->getPointeeType();
7803           else if (const MemberPointerType *ResTypeMPtr =
7804                 CanTy->getAs<MemberPointerType>())
7805             CanTy = ResTypeMPtr->getPointeeType();
7806           else
7807             done = true;
7808           if (CanTy.isVolatileQualified())
7809             VRQuals.addVolatile();
7810           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7811             return VRQuals;
7812         }
7813       }
7814     }
7815     return VRQuals;
7816 }
7817 
7818 namespace {
7819 
7820 /// Helper class to manage the addition of builtin operator overload
7821 /// candidates. It provides shared state and utility methods used throughout
7822 /// the process, as well as a helper method to add each group of builtin
7823 /// operator overloads from the standard to a candidate set.
7824 class BuiltinOperatorOverloadBuilder {
7825   // Common instance state available to all overload candidate addition methods.
7826   Sema &S;
7827   ArrayRef<Expr *> Args;
7828   Qualifiers VisibleTypeConversionsQuals;
7829   bool HasArithmeticOrEnumeralCandidateType;
7830   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7831   OverloadCandidateSet &CandidateSet;
7832 
7833   static constexpr int ArithmeticTypesCap = 24;
7834   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7835 
7836   // Define some indices used to iterate over the arithmetic types in
7837   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7838   // types are that preserved by promotion (C++ [over.built]p2).
7839   unsigned FirstIntegralType,
7840            LastIntegralType;
7841   unsigned FirstPromotedIntegralType,
7842            LastPromotedIntegralType;
7843   unsigned FirstPromotedArithmeticType,
7844            LastPromotedArithmeticType;
7845   unsigned NumArithmeticTypes;
7846 
7847   void InitArithmeticTypes() {
7848     // Start of promoted types.
7849     FirstPromotedArithmeticType = 0;
7850     ArithmeticTypes.push_back(S.Context.FloatTy);
7851     ArithmeticTypes.push_back(S.Context.DoubleTy);
7852     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7853     if (S.Context.getTargetInfo().hasFloat128Type())
7854       ArithmeticTypes.push_back(S.Context.Float128Ty);
7855 
7856     // Start of integral types.
7857     FirstIntegralType = ArithmeticTypes.size();
7858     FirstPromotedIntegralType = ArithmeticTypes.size();
7859     ArithmeticTypes.push_back(S.Context.IntTy);
7860     ArithmeticTypes.push_back(S.Context.LongTy);
7861     ArithmeticTypes.push_back(S.Context.LongLongTy);
7862     if (S.Context.getTargetInfo().hasInt128Type())
7863       ArithmeticTypes.push_back(S.Context.Int128Ty);
7864     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7865     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7866     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7867     if (S.Context.getTargetInfo().hasInt128Type())
7868       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7869     LastPromotedIntegralType = ArithmeticTypes.size();
7870     LastPromotedArithmeticType = ArithmeticTypes.size();
7871     // End of promoted types.
7872 
7873     ArithmeticTypes.push_back(S.Context.BoolTy);
7874     ArithmeticTypes.push_back(S.Context.CharTy);
7875     ArithmeticTypes.push_back(S.Context.WCharTy);
7876     if (S.Context.getLangOpts().Char8)
7877       ArithmeticTypes.push_back(S.Context.Char8Ty);
7878     ArithmeticTypes.push_back(S.Context.Char16Ty);
7879     ArithmeticTypes.push_back(S.Context.Char32Ty);
7880     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7881     ArithmeticTypes.push_back(S.Context.ShortTy);
7882     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7883     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7884     LastIntegralType = ArithmeticTypes.size();
7885     NumArithmeticTypes = ArithmeticTypes.size();
7886     // End of integral types.
7887     // FIXME: What about complex? What about half?
7888 
7889     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7890            "Enough inline storage for all arithmetic types.");
7891   }
7892 
7893   /// Helper method to factor out the common pattern of adding overloads
7894   /// for '++' and '--' builtin operators.
7895   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7896                                            bool HasVolatile,
7897                                            bool HasRestrict) {
7898     QualType ParamTypes[2] = {
7899       S.Context.getLValueReferenceType(CandidateTy),
7900       S.Context.IntTy
7901     };
7902 
7903     // Non-volatile version.
7904     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7905 
7906     // Use a heuristic to reduce number of builtin candidates in the set:
7907     // add volatile version only if there are conversions to a volatile type.
7908     if (HasVolatile) {
7909       ParamTypes[0] =
7910         S.Context.getLValueReferenceType(
7911           S.Context.getVolatileType(CandidateTy));
7912       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7913     }
7914 
7915     // Add restrict version only if there are conversions to a restrict type
7916     // and our candidate type is a non-restrict-qualified pointer.
7917     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7918         !CandidateTy.isRestrictQualified()) {
7919       ParamTypes[0]
7920         = S.Context.getLValueReferenceType(
7921             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7922       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7923 
7924       if (HasVolatile) {
7925         ParamTypes[0]
7926           = S.Context.getLValueReferenceType(
7927               S.Context.getCVRQualifiedType(CandidateTy,
7928                                             (Qualifiers::Volatile |
7929                                              Qualifiers::Restrict)));
7930         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7931       }
7932     }
7933 
7934   }
7935 
7936 public:
7937   BuiltinOperatorOverloadBuilder(
7938     Sema &S, ArrayRef<Expr *> Args,
7939     Qualifiers VisibleTypeConversionsQuals,
7940     bool HasArithmeticOrEnumeralCandidateType,
7941     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7942     OverloadCandidateSet &CandidateSet)
7943     : S(S), Args(Args),
7944       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7945       HasArithmeticOrEnumeralCandidateType(
7946         HasArithmeticOrEnumeralCandidateType),
7947       CandidateTypes(CandidateTypes),
7948       CandidateSet(CandidateSet) {
7949 
7950     InitArithmeticTypes();
7951   }
7952 
7953   // Increment is deprecated for bool since C++17.
7954   //
7955   // C++ [over.built]p3:
7956   //
7957   //   For every pair (T, VQ), where T is an arithmetic type other
7958   //   than bool, and VQ is either volatile or empty, there exist
7959   //   candidate operator functions of the form
7960   //
7961   //       VQ T&      operator++(VQ T&);
7962   //       T          operator++(VQ T&, int);
7963   //
7964   // C++ [over.built]p4:
7965   //
7966   //   For every pair (T, VQ), where T is an arithmetic type other
7967   //   than bool, and VQ is either volatile or empty, there exist
7968   //   candidate operator functions of the form
7969   //
7970   //       VQ T&      operator--(VQ T&);
7971   //       T          operator--(VQ T&, int);
7972   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7973     if (!HasArithmeticOrEnumeralCandidateType)
7974       return;
7975 
7976     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7977       const auto TypeOfT = ArithmeticTypes[Arith];
7978       if (TypeOfT == S.Context.BoolTy) {
7979         if (Op == OO_MinusMinus)
7980           continue;
7981         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7982           continue;
7983       }
7984       addPlusPlusMinusMinusStyleOverloads(
7985         TypeOfT,
7986         VisibleTypeConversionsQuals.hasVolatile(),
7987         VisibleTypeConversionsQuals.hasRestrict());
7988     }
7989   }
7990 
7991   // C++ [over.built]p5:
7992   //
7993   //   For every pair (T, VQ), where T is a cv-qualified or
7994   //   cv-unqualified object type, and VQ is either volatile or
7995   //   empty, there exist candidate operator functions of the form
7996   //
7997   //       T*VQ&      operator++(T*VQ&);
7998   //       T*VQ&      operator--(T*VQ&);
7999   //       T*         operator++(T*VQ&, int);
8000   //       T*         operator--(T*VQ&, int);
8001   void addPlusPlusMinusMinusPointerOverloads() {
8002     for (BuiltinCandidateTypeSet::iterator
8003               Ptr = CandidateTypes[0].pointer_begin(),
8004            PtrEnd = CandidateTypes[0].pointer_end();
8005          Ptr != PtrEnd; ++Ptr) {
8006       // Skip pointer types that aren't pointers to object types.
8007       if (!(*Ptr)->getPointeeType()->isObjectType())
8008         continue;
8009 
8010       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8011         (!(*Ptr).isVolatileQualified() &&
8012          VisibleTypeConversionsQuals.hasVolatile()),
8013         (!(*Ptr).isRestrictQualified() &&
8014          VisibleTypeConversionsQuals.hasRestrict()));
8015     }
8016   }
8017 
8018   // C++ [over.built]p6:
8019   //   For every cv-qualified or cv-unqualified object type T, there
8020   //   exist candidate operator functions of the form
8021   //
8022   //       T&         operator*(T*);
8023   //
8024   // C++ [over.built]p7:
8025   //   For every function type T that does not have cv-qualifiers or a
8026   //   ref-qualifier, there exist candidate operator functions of the form
8027   //       T&         operator*(T*);
8028   void addUnaryStarPointerOverloads() {
8029     for (BuiltinCandidateTypeSet::iterator
8030               Ptr = CandidateTypes[0].pointer_begin(),
8031            PtrEnd = CandidateTypes[0].pointer_end();
8032          Ptr != PtrEnd; ++Ptr) {
8033       QualType ParamTy = *Ptr;
8034       QualType PointeeTy = ParamTy->getPointeeType();
8035       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8036         continue;
8037 
8038       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8039         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8040           continue;
8041 
8042       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8043     }
8044   }
8045 
8046   // C++ [over.built]p9:
8047   //  For every promoted arithmetic type T, there exist candidate
8048   //  operator functions of the form
8049   //
8050   //       T         operator+(T);
8051   //       T         operator-(T);
8052   void addUnaryPlusOrMinusArithmeticOverloads() {
8053     if (!HasArithmeticOrEnumeralCandidateType)
8054       return;
8055 
8056     for (unsigned Arith = FirstPromotedArithmeticType;
8057          Arith < LastPromotedArithmeticType; ++Arith) {
8058       QualType ArithTy = ArithmeticTypes[Arith];
8059       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8060     }
8061 
8062     // Extension: We also add these operators for vector types.
8063     for (BuiltinCandidateTypeSet::iterator
8064               Vec = CandidateTypes[0].vector_begin(),
8065            VecEnd = CandidateTypes[0].vector_end();
8066          Vec != VecEnd; ++Vec) {
8067       QualType VecTy = *Vec;
8068       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8069     }
8070   }
8071 
8072   // C++ [over.built]p8:
8073   //   For every type T, there exist candidate operator functions of
8074   //   the form
8075   //
8076   //       T*         operator+(T*);
8077   void addUnaryPlusPointerOverloads() {
8078     for (BuiltinCandidateTypeSet::iterator
8079               Ptr = CandidateTypes[0].pointer_begin(),
8080            PtrEnd = CandidateTypes[0].pointer_end();
8081          Ptr != PtrEnd; ++Ptr) {
8082       QualType ParamTy = *Ptr;
8083       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8084     }
8085   }
8086 
8087   // C++ [over.built]p10:
8088   //   For every promoted integral type T, there exist candidate
8089   //   operator functions of the form
8090   //
8091   //        T         operator~(T);
8092   void addUnaryTildePromotedIntegralOverloads() {
8093     if (!HasArithmeticOrEnumeralCandidateType)
8094       return;
8095 
8096     for (unsigned Int = FirstPromotedIntegralType;
8097          Int < LastPromotedIntegralType; ++Int) {
8098       QualType IntTy = ArithmeticTypes[Int];
8099       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8100     }
8101 
8102     // Extension: We also add this operator for vector types.
8103     for (BuiltinCandidateTypeSet::iterator
8104               Vec = CandidateTypes[0].vector_begin(),
8105            VecEnd = CandidateTypes[0].vector_end();
8106          Vec != VecEnd; ++Vec) {
8107       QualType VecTy = *Vec;
8108       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8109     }
8110   }
8111 
8112   // C++ [over.match.oper]p16:
8113   //   For every pointer to member type T or type std::nullptr_t, there
8114   //   exist candidate operator functions of the form
8115   //
8116   //        bool operator==(T,T);
8117   //        bool operator!=(T,T);
8118   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8119     /// Set of (canonical) types that we've already handled.
8120     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8121 
8122     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8123       for (BuiltinCandidateTypeSet::iterator
8124                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8125              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8126            MemPtr != MemPtrEnd;
8127            ++MemPtr) {
8128         // Don't add the same builtin candidate twice.
8129         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8130           continue;
8131 
8132         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8133         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8134       }
8135 
8136       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8137         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8138         if (AddedTypes.insert(NullPtrTy).second) {
8139           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8140           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8141         }
8142       }
8143     }
8144   }
8145 
8146   // C++ [over.built]p15:
8147   //
8148   //   For every T, where T is an enumeration type or a pointer type,
8149   //   there exist candidate operator functions of the form
8150   //
8151   //        bool       operator<(T, T);
8152   //        bool       operator>(T, T);
8153   //        bool       operator<=(T, T);
8154   //        bool       operator>=(T, T);
8155   //        bool       operator==(T, T);
8156   //        bool       operator!=(T, T);
8157   //           R       operator<=>(T, T)
8158   void addGenericBinaryPointerOrEnumeralOverloads() {
8159     // C++ [over.match.oper]p3:
8160     //   [...]the built-in candidates include all of the candidate operator
8161     //   functions defined in 13.6 that, compared to the given operator, [...]
8162     //   do not have the same parameter-type-list as any non-template non-member
8163     //   candidate.
8164     //
8165     // Note that in practice, this only affects enumeration types because there
8166     // aren't any built-in candidates of record type, and a user-defined operator
8167     // must have an operand of record or enumeration type. Also, the only other
8168     // overloaded operator with enumeration arguments, operator=,
8169     // cannot be overloaded for enumeration types, so this is the only place
8170     // where we must suppress candidates like this.
8171     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8172       UserDefinedBinaryOperators;
8173 
8174     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8175       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8176           CandidateTypes[ArgIdx].enumeration_end()) {
8177         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8178                                          CEnd = CandidateSet.end();
8179              C != CEnd; ++C) {
8180           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8181             continue;
8182 
8183           if (C->Function->isFunctionTemplateSpecialization())
8184             continue;
8185 
8186           QualType FirstParamType =
8187             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8188           QualType SecondParamType =
8189             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8190 
8191           // Skip if either parameter isn't of enumeral type.
8192           if (!FirstParamType->isEnumeralType() ||
8193               !SecondParamType->isEnumeralType())
8194             continue;
8195 
8196           // Add this operator to the set of known user-defined operators.
8197           UserDefinedBinaryOperators.insert(
8198             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8199                            S.Context.getCanonicalType(SecondParamType)));
8200         }
8201       }
8202     }
8203 
8204     /// Set of (canonical) types that we've already handled.
8205     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8206 
8207     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8208       for (BuiltinCandidateTypeSet::iterator
8209                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8210              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8211            Ptr != PtrEnd; ++Ptr) {
8212         // Don't add the same builtin candidate twice.
8213         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8214           continue;
8215 
8216         QualType ParamTypes[2] = { *Ptr, *Ptr };
8217         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8218       }
8219       for (BuiltinCandidateTypeSet::iterator
8220                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8221              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8222            Enum != EnumEnd; ++Enum) {
8223         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8224 
8225         // Don't add the same builtin candidate twice, or if a user defined
8226         // candidate exists.
8227         if (!AddedTypes.insert(CanonType).second ||
8228             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8229                                                             CanonType)))
8230           continue;
8231         QualType ParamTypes[2] = { *Enum, *Enum };
8232         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8233       }
8234     }
8235   }
8236 
8237   // C++ [over.built]p13:
8238   //
8239   //   For every cv-qualified or cv-unqualified object type T
8240   //   there exist candidate operator functions of the form
8241   //
8242   //      T*         operator+(T*, ptrdiff_t);
8243   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8244   //      T*         operator-(T*, ptrdiff_t);
8245   //      T*         operator+(ptrdiff_t, T*);
8246   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8247   //
8248   // C++ [over.built]p14:
8249   //
8250   //   For every T, where T is a pointer to object type, there
8251   //   exist candidate operator functions of the form
8252   //
8253   //      ptrdiff_t  operator-(T, T);
8254   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8255     /// Set of (canonical) types that we've already handled.
8256     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8257 
8258     for (int Arg = 0; Arg < 2; ++Arg) {
8259       QualType AsymmetricParamTypes[2] = {
8260         S.Context.getPointerDiffType(),
8261         S.Context.getPointerDiffType(),
8262       };
8263       for (BuiltinCandidateTypeSet::iterator
8264                 Ptr = CandidateTypes[Arg].pointer_begin(),
8265              PtrEnd = CandidateTypes[Arg].pointer_end();
8266            Ptr != PtrEnd; ++Ptr) {
8267         QualType PointeeTy = (*Ptr)->getPointeeType();
8268         if (!PointeeTy->isObjectType())
8269           continue;
8270 
8271         AsymmetricParamTypes[Arg] = *Ptr;
8272         if (Arg == 0 || Op == OO_Plus) {
8273           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8274           // T* operator+(ptrdiff_t, T*);
8275           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8276         }
8277         if (Op == OO_Minus) {
8278           // ptrdiff_t operator-(T, T);
8279           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8280             continue;
8281 
8282           QualType ParamTypes[2] = { *Ptr, *Ptr };
8283           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8284         }
8285       }
8286     }
8287   }
8288 
8289   // C++ [over.built]p12:
8290   //
8291   //   For every pair of promoted arithmetic types L and R, there
8292   //   exist candidate operator functions of the form
8293   //
8294   //        LR         operator*(L, R);
8295   //        LR         operator/(L, R);
8296   //        LR         operator+(L, R);
8297   //        LR         operator-(L, R);
8298   //        bool       operator<(L, R);
8299   //        bool       operator>(L, R);
8300   //        bool       operator<=(L, R);
8301   //        bool       operator>=(L, R);
8302   //        bool       operator==(L, R);
8303   //        bool       operator!=(L, R);
8304   //
8305   //   where LR is the result of the usual arithmetic conversions
8306   //   between types L and R.
8307   //
8308   // C++ [over.built]p24:
8309   //
8310   //   For every pair of promoted arithmetic types L and R, there exist
8311   //   candidate operator functions of the form
8312   //
8313   //        LR       operator?(bool, L, R);
8314   //
8315   //   where LR is the result of the usual arithmetic conversions
8316   //   between types L and R.
8317   // Our candidates ignore the first parameter.
8318   void addGenericBinaryArithmeticOverloads() {
8319     if (!HasArithmeticOrEnumeralCandidateType)
8320       return;
8321 
8322     for (unsigned Left = FirstPromotedArithmeticType;
8323          Left < LastPromotedArithmeticType; ++Left) {
8324       for (unsigned Right = FirstPromotedArithmeticType;
8325            Right < LastPromotedArithmeticType; ++Right) {
8326         QualType LandR[2] = { ArithmeticTypes[Left],
8327                               ArithmeticTypes[Right] };
8328         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8329       }
8330     }
8331 
8332     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8333     // conditional operator for vector types.
8334     for (BuiltinCandidateTypeSet::iterator
8335               Vec1 = CandidateTypes[0].vector_begin(),
8336            Vec1End = CandidateTypes[0].vector_end();
8337          Vec1 != Vec1End; ++Vec1) {
8338       for (BuiltinCandidateTypeSet::iterator
8339                 Vec2 = CandidateTypes[1].vector_begin(),
8340              Vec2End = CandidateTypes[1].vector_end();
8341            Vec2 != Vec2End; ++Vec2) {
8342         QualType LandR[2] = { *Vec1, *Vec2 };
8343         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8344       }
8345     }
8346   }
8347 
8348   // C++2a [over.built]p14:
8349   //
8350   //   For every integral type T there exists a candidate operator function
8351   //   of the form
8352   //
8353   //        std::strong_ordering operator<=>(T, T)
8354   //
8355   // C++2a [over.built]p15:
8356   //
8357   //   For every pair of floating-point types L and R, there exists a candidate
8358   //   operator function of the form
8359   //
8360   //       std::partial_ordering operator<=>(L, R);
8361   //
8362   // FIXME: The current specification for integral types doesn't play nice with
8363   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8364   // comparisons. Under the current spec this can lead to ambiguity during
8365   // overload resolution. For example:
8366   //
8367   //   enum A : int {a};
8368   //   auto x = (a <=> (long)42);
8369   //
8370   //   error: call is ambiguous for arguments 'A' and 'long'.
8371   //   note: candidate operator<=>(int, int)
8372   //   note: candidate operator<=>(long, long)
8373   //
8374   // To avoid this error, this function deviates from the specification and adds
8375   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8376   // arithmetic types (the same as the generic relational overloads).
8377   //
8378   // For now this function acts as a placeholder.
8379   void addThreeWayArithmeticOverloads() {
8380     addGenericBinaryArithmeticOverloads();
8381   }
8382 
8383   // C++ [over.built]p17:
8384   //
8385   //   For every pair of promoted integral types L and R, there
8386   //   exist candidate operator functions of the form
8387   //
8388   //      LR         operator%(L, R);
8389   //      LR         operator&(L, R);
8390   //      LR         operator^(L, R);
8391   //      LR         operator|(L, R);
8392   //      L          operator<<(L, R);
8393   //      L          operator>>(L, R);
8394   //
8395   //   where LR is the result of the usual arithmetic conversions
8396   //   between types L and R.
8397   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8398     if (!HasArithmeticOrEnumeralCandidateType)
8399       return;
8400 
8401     for (unsigned Left = FirstPromotedIntegralType;
8402          Left < LastPromotedIntegralType; ++Left) {
8403       for (unsigned Right = FirstPromotedIntegralType;
8404            Right < LastPromotedIntegralType; ++Right) {
8405         QualType LandR[2] = { ArithmeticTypes[Left],
8406                               ArithmeticTypes[Right] };
8407         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8408       }
8409     }
8410   }
8411 
8412   // C++ [over.built]p20:
8413   //
8414   //   For every pair (T, VQ), where T is an enumeration or
8415   //   pointer to member type and VQ is either volatile or
8416   //   empty, there exist candidate operator functions of the form
8417   //
8418   //        VQ T&      operator=(VQ T&, T);
8419   void addAssignmentMemberPointerOrEnumeralOverloads() {
8420     /// Set of (canonical) types that we've already handled.
8421     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8422 
8423     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8424       for (BuiltinCandidateTypeSet::iterator
8425                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8426              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8427            Enum != EnumEnd; ++Enum) {
8428         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8429           continue;
8430 
8431         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8432       }
8433 
8434       for (BuiltinCandidateTypeSet::iterator
8435                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8436              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8437            MemPtr != MemPtrEnd; ++MemPtr) {
8438         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8439           continue;
8440 
8441         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8442       }
8443     }
8444   }
8445 
8446   // C++ [over.built]p19:
8447   //
8448   //   For every pair (T, VQ), where T is any type and VQ is either
8449   //   volatile or empty, there exist candidate operator functions
8450   //   of the form
8451   //
8452   //        T*VQ&      operator=(T*VQ&, T*);
8453   //
8454   // C++ [over.built]p21:
8455   //
8456   //   For every pair (T, VQ), where T is a cv-qualified or
8457   //   cv-unqualified object type and VQ is either volatile or
8458   //   empty, there exist candidate operator functions of the form
8459   //
8460   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8461   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8462   void addAssignmentPointerOverloads(bool isEqualOp) {
8463     /// Set of (canonical) types that we've already handled.
8464     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8465 
8466     for (BuiltinCandidateTypeSet::iterator
8467               Ptr = CandidateTypes[0].pointer_begin(),
8468            PtrEnd = CandidateTypes[0].pointer_end();
8469          Ptr != PtrEnd; ++Ptr) {
8470       // If this is operator=, keep track of the builtin candidates we added.
8471       if (isEqualOp)
8472         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8473       else if (!(*Ptr)->getPointeeType()->isObjectType())
8474         continue;
8475 
8476       // non-volatile version
8477       QualType ParamTypes[2] = {
8478         S.Context.getLValueReferenceType(*Ptr),
8479         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8480       };
8481       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8482                             /*IsAssignmentOperator=*/ isEqualOp);
8483 
8484       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8485                           VisibleTypeConversionsQuals.hasVolatile();
8486       if (NeedVolatile) {
8487         // volatile version
8488         ParamTypes[0] =
8489           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8490         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8491                               /*IsAssignmentOperator=*/isEqualOp);
8492       }
8493 
8494       if (!(*Ptr).isRestrictQualified() &&
8495           VisibleTypeConversionsQuals.hasRestrict()) {
8496         // restrict version
8497         ParamTypes[0]
8498           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8499         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8500                               /*IsAssignmentOperator=*/isEqualOp);
8501 
8502         if (NeedVolatile) {
8503           // volatile restrict version
8504           ParamTypes[0]
8505             = S.Context.getLValueReferenceType(
8506                 S.Context.getCVRQualifiedType(*Ptr,
8507                                               (Qualifiers::Volatile |
8508                                                Qualifiers::Restrict)));
8509           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8510                                 /*IsAssignmentOperator=*/isEqualOp);
8511         }
8512       }
8513     }
8514 
8515     if (isEqualOp) {
8516       for (BuiltinCandidateTypeSet::iterator
8517                 Ptr = CandidateTypes[1].pointer_begin(),
8518              PtrEnd = CandidateTypes[1].pointer_end();
8519            Ptr != PtrEnd; ++Ptr) {
8520         // Make sure we don't add the same candidate twice.
8521         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8522           continue;
8523 
8524         QualType ParamTypes[2] = {
8525           S.Context.getLValueReferenceType(*Ptr),
8526           *Ptr,
8527         };
8528 
8529         // non-volatile version
8530         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8531                               /*IsAssignmentOperator=*/true);
8532 
8533         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8534                            VisibleTypeConversionsQuals.hasVolatile();
8535         if (NeedVolatile) {
8536           // volatile version
8537           ParamTypes[0] =
8538             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8539           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8540                                 /*IsAssignmentOperator=*/true);
8541         }
8542 
8543         if (!(*Ptr).isRestrictQualified() &&
8544             VisibleTypeConversionsQuals.hasRestrict()) {
8545           // restrict version
8546           ParamTypes[0]
8547             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8548           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8549                                 /*IsAssignmentOperator=*/true);
8550 
8551           if (NeedVolatile) {
8552             // volatile restrict version
8553             ParamTypes[0]
8554               = S.Context.getLValueReferenceType(
8555                   S.Context.getCVRQualifiedType(*Ptr,
8556                                                 (Qualifiers::Volatile |
8557                                                  Qualifiers::Restrict)));
8558             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8559                                   /*IsAssignmentOperator=*/true);
8560           }
8561         }
8562       }
8563     }
8564   }
8565 
8566   // C++ [over.built]p18:
8567   //
8568   //   For every triple (L, VQ, R), where L is an arithmetic type,
8569   //   VQ is either volatile or empty, and R is a promoted
8570   //   arithmetic type, there exist candidate operator functions of
8571   //   the form
8572   //
8573   //        VQ L&      operator=(VQ L&, R);
8574   //        VQ L&      operator*=(VQ L&, R);
8575   //        VQ L&      operator/=(VQ L&, R);
8576   //        VQ L&      operator+=(VQ L&, R);
8577   //        VQ L&      operator-=(VQ L&, R);
8578   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8579     if (!HasArithmeticOrEnumeralCandidateType)
8580       return;
8581 
8582     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8583       for (unsigned Right = FirstPromotedArithmeticType;
8584            Right < LastPromotedArithmeticType; ++Right) {
8585         QualType ParamTypes[2];
8586         ParamTypes[1] = ArithmeticTypes[Right];
8587         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8588             S, ArithmeticTypes[Left], Args[0]);
8589         // Add this built-in operator as a candidate (VQ is empty).
8590         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8591         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8592                               /*IsAssignmentOperator=*/isEqualOp);
8593 
8594         // Add this built-in operator as a candidate (VQ is 'volatile').
8595         if (VisibleTypeConversionsQuals.hasVolatile()) {
8596           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8597           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8598           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8599                                 /*IsAssignmentOperator=*/isEqualOp);
8600         }
8601       }
8602     }
8603 
8604     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8605     for (BuiltinCandidateTypeSet::iterator
8606               Vec1 = CandidateTypes[0].vector_begin(),
8607            Vec1End = CandidateTypes[0].vector_end();
8608          Vec1 != Vec1End; ++Vec1) {
8609       for (BuiltinCandidateTypeSet::iterator
8610                 Vec2 = CandidateTypes[1].vector_begin(),
8611              Vec2End = CandidateTypes[1].vector_end();
8612            Vec2 != Vec2End; ++Vec2) {
8613         QualType ParamTypes[2];
8614         ParamTypes[1] = *Vec2;
8615         // Add this built-in operator as a candidate (VQ is empty).
8616         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8617         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8618                               /*IsAssignmentOperator=*/isEqualOp);
8619 
8620         // Add this built-in operator as a candidate (VQ is 'volatile').
8621         if (VisibleTypeConversionsQuals.hasVolatile()) {
8622           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8623           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8624           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8625                                 /*IsAssignmentOperator=*/isEqualOp);
8626         }
8627       }
8628     }
8629   }
8630 
8631   // C++ [over.built]p22:
8632   //
8633   //   For every triple (L, VQ, R), where L is an integral type, VQ
8634   //   is either volatile or empty, and R is a promoted integral
8635   //   type, there exist candidate operator functions of the form
8636   //
8637   //        VQ L&       operator%=(VQ L&, R);
8638   //        VQ L&       operator<<=(VQ L&, R);
8639   //        VQ L&       operator>>=(VQ L&, R);
8640   //        VQ L&       operator&=(VQ L&, R);
8641   //        VQ L&       operator^=(VQ L&, R);
8642   //        VQ L&       operator|=(VQ L&, R);
8643   void addAssignmentIntegralOverloads() {
8644     if (!HasArithmeticOrEnumeralCandidateType)
8645       return;
8646 
8647     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8648       for (unsigned Right = FirstPromotedIntegralType;
8649            Right < LastPromotedIntegralType; ++Right) {
8650         QualType ParamTypes[2];
8651         ParamTypes[1] = ArithmeticTypes[Right];
8652         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8653             S, ArithmeticTypes[Left], Args[0]);
8654         // Add this built-in operator as a candidate (VQ is empty).
8655         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8656         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8657         if (VisibleTypeConversionsQuals.hasVolatile()) {
8658           // Add this built-in operator as a candidate (VQ is 'volatile').
8659           ParamTypes[0] = LeftBaseTy;
8660           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8661           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8662           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8663         }
8664       }
8665     }
8666   }
8667 
8668   // C++ [over.operator]p23:
8669   //
8670   //   There also exist candidate operator functions of the form
8671   //
8672   //        bool        operator!(bool);
8673   //        bool        operator&&(bool, bool);
8674   //        bool        operator||(bool, bool);
8675   void addExclaimOverload() {
8676     QualType ParamTy = S.Context.BoolTy;
8677     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8678                           /*IsAssignmentOperator=*/false,
8679                           /*NumContextualBoolArguments=*/1);
8680   }
8681   void addAmpAmpOrPipePipeOverload() {
8682     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8683     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8684                           /*IsAssignmentOperator=*/false,
8685                           /*NumContextualBoolArguments=*/2);
8686   }
8687 
8688   // C++ [over.built]p13:
8689   //
8690   //   For every cv-qualified or cv-unqualified object type T there
8691   //   exist candidate operator functions of the form
8692   //
8693   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8694   //        T&         operator[](T*, ptrdiff_t);
8695   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8696   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8697   //        T&         operator[](ptrdiff_t, T*);
8698   void addSubscriptOverloads() {
8699     for (BuiltinCandidateTypeSet::iterator
8700               Ptr = CandidateTypes[0].pointer_begin(),
8701            PtrEnd = CandidateTypes[0].pointer_end();
8702          Ptr != PtrEnd; ++Ptr) {
8703       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8704       QualType PointeeType = (*Ptr)->getPointeeType();
8705       if (!PointeeType->isObjectType())
8706         continue;
8707 
8708       // T& operator[](T*, ptrdiff_t)
8709       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8710     }
8711 
8712     for (BuiltinCandidateTypeSet::iterator
8713               Ptr = CandidateTypes[1].pointer_begin(),
8714            PtrEnd = CandidateTypes[1].pointer_end();
8715          Ptr != PtrEnd; ++Ptr) {
8716       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8717       QualType PointeeType = (*Ptr)->getPointeeType();
8718       if (!PointeeType->isObjectType())
8719         continue;
8720 
8721       // T& operator[](ptrdiff_t, T*)
8722       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8723     }
8724   }
8725 
8726   // C++ [over.built]p11:
8727   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8728   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8729   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8730   //    there exist candidate operator functions of the form
8731   //
8732   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8733   //
8734   //    where CV12 is the union of CV1 and CV2.
8735   void addArrowStarOverloads() {
8736     for (BuiltinCandidateTypeSet::iterator
8737              Ptr = CandidateTypes[0].pointer_begin(),
8738            PtrEnd = CandidateTypes[0].pointer_end();
8739          Ptr != PtrEnd; ++Ptr) {
8740       QualType C1Ty = (*Ptr);
8741       QualType C1;
8742       QualifierCollector Q1;
8743       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8744       if (!isa<RecordType>(C1))
8745         continue;
8746       // heuristic to reduce number of builtin candidates in the set.
8747       // Add volatile/restrict version only if there are conversions to a
8748       // volatile/restrict type.
8749       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8750         continue;
8751       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8752         continue;
8753       for (BuiltinCandidateTypeSet::iterator
8754                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8755              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8756            MemPtr != MemPtrEnd; ++MemPtr) {
8757         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8758         QualType C2 = QualType(mptr->getClass(), 0);
8759         C2 = C2.getUnqualifiedType();
8760         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8761           break;
8762         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8763         // build CV12 T&
8764         QualType T = mptr->getPointeeType();
8765         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8766             T.isVolatileQualified())
8767           continue;
8768         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8769             T.isRestrictQualified())
8770           continue;
8771         T = Q1.apply(S.Context, T);
8772         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8773       }
8774     }
8775   }
8776 
8777   // Note that we don't consider the first argument, since it has been
8778   // contextually converted to bool long ago. The candidates below are
8779   // therefore added as binary.
8780   //
8781   // C++ [over.built]p25:
8782   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8783   //   enumeration type, there exist candidate operator functions of the form
8784   //
8785   //        T        operator?(bool, T, T);
8786   //
8787   void addConditionalOperatorOverloads() {
8788     /// Set of (canonical) types that we've already handled.
8789     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8790 
8791     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8792       for (BuiltinCandidateTypeSet::iterator
8793                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8794              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8795            Ptr != PtrEnd; ++Ptr) {
8796         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8797           continue;
8798 
8799         QualType ParamTypes[2] = { *Ptr, *Ptr };
8800         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8801       }
8802 
8803       for (BuiltinCandidateTypeSet::iterator
8804                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8805              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8806            MemPtr != MemPtrEnd; ++MemPtr) {
8807         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8808           continue;
8809 
8810         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8811         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8812       }
8813 
8814       if (S.getLangOpts().CPlusPlus11) {
8815         for (BuiltinCandidateTypeSet::iterator
8816                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8817                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8818              Enum != EnumEnd; ++Enum) {
8819           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
8820             continue;
8821 
8822           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8823             continue;
8824 
8825           QualType ParamTypes[2] = { *Enum, *Enum };
8826           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8827         }
8828       }
8829     }
8830   }
8831 };
8832 
8833 } // end anonymous namespace
8834 
8835 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8836 /// operator overloads to the candidate set (C++ [over.built]), based
8837 /// on the operator @p Op and the arguments given. For example, if the
8838 /// operator is a binary '+', this routine might add "int
8839 /// operator+(int, int)" to cover integer addition.
8840 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8841                                         SourceLocation OpLoc,
8842                                         ArrayRef<Expr *> Args,
8843                                         OverloadCandidateSet &CandidateSet) {
8844   // Find all of the types that the arguments can convert to, but only
8845   // if the operator we're looking at has built-in operator candidates
8846   // that make use of these types. Also record whether we encounter non-record
8847   // candidate types or either arithmetic or enumeral candidate types.
8848   Qualifiers VisibleTypeConversionsQuals;
8849   VisibleTypeConversionsQuals.addConst();
8850   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8851     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8852 
8853   bool HasNonRecordCandidateType = false;
8854   bool HasArithmeticOrEnumeralCandidateType = false;
8855   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8856   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8857     CandidateTypes.emplace_back(*this);
8858     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8859                                                  OpLoc,
8860                                                  true,
8861                                                  (Op == OO_Exclaim ||
8862                                                   Op == OO_AmpAmp ||
8863                                                   Op == OO_PipePipe),
8864                                                  VisibleTypeConversionsQuals);
8865     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8866         CandidateTypes[ArgIdx].hasNonRecordTypes();
8867     HasArithmeticOrEnumeralCandidateType =
8868         HasArithmeticOrEnumeralCandidateType ||
8869         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8870   }
8871 
8872   // Exit early when no non-record types have been added to the candidate set
8873   // for any of the arguments to the operator.
8874   //
8875   // We can't exit early for !, ||, or &&, since there we have always have
8876   // 'bool' overloads.
8877   if (!HasNonRecordCandidateType &&
8878       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8879     return;
8880 
8881   // Setup an object to manage the common state for building overloads.
8882   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8883                                            VisibleTypeConversionsQuals,
8884                                            HasArithmeticOrEnumeralCandidateType,
8885                                            CandidateTypes, CandidateSet);
8886 
8887   // Dispatch over the operation to add in only those overloads which apply.
8888   switch (Op) {
8889   case OO_None:
8890   case NUM_OVERLOADED_OPERATORS:
8891     llvm_unreachable("Expected an overloaded operator");
8892 
8893   case OO_New:
8894   case OO_Delete:
8895   case OO_Array_New:
8896   case OO_Array_Delete:
8897   case OO_Call:
8898     llvm_unreachable(
8899                     "Special operators don't use AddBuiltinOperatorCandidates");
8900 
8901   case OO_Comma:
8902   case OO_Arrow:
8903   case OO_Coawait:
8904     // C++ [over.match.oper]p3:
8905     //   -- For the operator ',', the unary operator '&', the
8906     //      operator '->', or the operator 'co_await', the
8907     //      built-in candidates set is empty.
8908     break;
8909 
8910   case OO_Plus: // '+' is either unary or binary
8911     if (Args.size() == 1)
8912       OpBuilder.addUnaryPlusPointerOverloads();
8913     LLVM_FALLTHROUGH;
8914 
8915   case OO_Minus: // '-' is either unary or binary
8916     if (Args.size() == 1) {
8917       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8918     } else {
8919       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8920       OpBuilder.addGenericBinaryArithmeticOverloads();
8921     }
8922     break;
8923 
8924   case OO_Star: // '*' is either unary or binary
8925     if (Args.size() == 1)
8926       OpBuilder.addUnaryStarPointerOverloads();
8927     else
8928       OpBuilder.addGenericBinaryArithmeticOverloads();
8929     break;
8930 
8931   case OO_Slash:
8932     OpBuilder.addGenericBinaryArithmeticOverloads();
8933     break;
8934 
8935   case OO_PlusPlus:
8936   case OO_MinusMinus:
8937     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8938     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8939     break;
8940 
8941   case OO_EqualEqual:
8942   case OO_ExclaimEqual:
8943     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8944     LLVM_FALLTHROUGH;
8945 
8946   case OO_Less:
8947   case OO_Greater:
8948   case OO_LessEqual:
8949   case OO_GreaterEqual:
8950     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8951     OpBuilder.addGenericBinaryArithmeticOverloads();
8952     break;
8953 
8954   case OO_Spaceship:
8955     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8956     OpBuilder.addThreeWayArithmeticOverloads();
8957     break;
8958 
8959   case OO_Percent:
8960   case OO_Caret:
8961   case OO_Pipe:
8962   case OO_LessLess:
8963   case OO_GreaterGreater:
8964     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8965     break;
8966 
8967   case OO_Amp: // '&' is either unary or binary
8968     if (Args.size() == 1)
8969       // C++ [over.match.oper]p3:
8970       //   -- For the operator ',', the unary operator '&', or the
8971       //      operator '->', the built-in candidates set is empty.
8972       break;
8973 
8974     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8975     break;
8976 
8977   case OO_Tilde:
8978     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8979     break;
8980 
8981   case OO_Equal:
8982     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8983     LLVM_FALLTHROUGH;
8984 
8985   case OO_PlusEqual:
8986   case OO_MinusEqual:
8987     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8988     LLVM_FALLTHROUGH;
8989 
8990   case OO_StarEqual:
8991   case OO_SlashEqual:
8992     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8993     break;
8994 
8995   case OO_PercentEqual:
8996   case OO_LessLessEqual:
8997   case OO_GreaterGreaterEqual:
8998   case OO_AmpEqual:
8999   case OO_CaretEqual:
9000   case OO_PipeEqual:
9001     OpBuilder.addAssignmentIntegralOverloads();
9002     break;
9003 
9004   case OO_Exclaim:
9005     OpBuilder.addExclaimOverload();
9006     break;
9007 
9008   case OO_AmpAmp:
9009   case OO_PipePipe:
9010     OpBuilder.addAmpAmpOrPipePipeOverload();
9011     break;
9012 
9013   case OO_Subscript:
9014     OpBuilder.addSubscriptOverloads();
9015     break;
9016 
9017   case OO_ArrowStar:
9018     OpBuilder.addArrowStarOverloads();
9019     break;
9020 
9021   case OO_Conditional:
9022     OpBuilder.addConditionalOperatorOverloads();
9023     OpBuilder.addGenericBinaryArithmeticOverloads();
9024     break;
9025   }
9026 }
9027 
9028 /// Add function candidates found via argument-dependent lookup
9029 /// to the set of overloading candidates.
9030 ///
9031 /// This routine performs argument-dependent name lookup based on the
9032 /// given function name (which may also be an operator name) and adds
9033 /// all of the overload candidates found by ADL to the overload
9034 /// candidate set (C++ [basic.lookup.argdep]).
9035 void
9036 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9037                                            SourceLocation Loc,
9038                                            ArrayRef<Expr *> Args,
9039                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9040                                            OverloadCandidateSet& CandidateSet,
9041                                            bool PartialOverloading) {
9042   ADLResult Fns;
9043 
9044   // FIXME: This approach for uniquing ADL results (and removing
9045   // redundant candidates from the set) relies on pointer-equality,
9046   // which means we need to key off the canonical decl.  However,
9047   // always going back to the canonical decl might not get us the
9048   // right set of default arguments.  What default arguments are
9049   // we supposed to consider on ADL candidates, anyway?
9050 
9051   // FIXME: Pass in the explicit template arguments?
9052   ArgumentDependentLookup(Name, Loc, Args, Fns);
9053 
9054   // Erase all of the candidates we already knew about.
9055   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9056                                    CandEnd = CandidateSet.end();
9057        Cand != CandEnd; ++Cand)
9058     if (Cand->Function) {
9059       Fns.erase(Cand->Function);
9060       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9061         Fns.erase(FunTmpl);
9062     }
9063 
9064   // For each of the ADL candidates we found, add it to the overload
9065   // set.
9066   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9067     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9068 
9069     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9070       if (ExplicitTemplateArgs)
9071         continue;
9072 
9073       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9074                            /*SuppressUserConversions=*/false, PartialOverloading,
9075                            /*AllowExplicit*/ true,
9076                            /*AllowExplicitConversions*/ false,
9077                            ADLCallKind::UsesADL);
9078     } else {
9079       AddTemplateOverloadCandidate(
9080           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9081           CandidateSet,
9082           /*SuppressUserConversions=*/false, PartialOverloading,
9083           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9084     }
9085   }
9086 }
9087 
9088 namespace {
9089 enum class Comparison { Equal, Better, Worse };
9090 }
9091 
9092 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9093 /// overload resolution.
9094 ///
9095 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9096 /// Cand1's first N enable_if attributes have precisely the same conditions as
9097 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9098 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9099 ///
9100 /// Note that you can have a pair of candidates such that Cand1's enable_if
9101 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9102 /// worse than Cand1's.
9103 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9104                                        const FunctionDecl *Cand2) {
9105   // Common case: One (or both) decls don't have enable_if attrs.
9106   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9107   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9108   if (!Cand1Attr || !Cand2Attr) {
9109     if (Cand1Attr == Cand2Attr)
9110       return Comparison::Equal;
9111     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9112   }
9113 
9114   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9115   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9116 
9117   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9118   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9119     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9120     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9121 
9122     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9123     // has fewer enable_if attributes than Cand2, and vice versa.
9124     if (!Cand1A)
9125       return Comparison::Worse;
9126     if (!Cand2A)
9127       return Comparison::Better;
9128 
9129     Cand1ID.clear();
9130     Cand2ID.clear();
9131 
9132     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9133     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9134     if (Cand1ID != Cand2ID)
9135       return Comparison::Worse;
9136   }
9137 
9138   return Comparison::Equal;
9139 }
9140 
9141 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9142                                           const OverloadCandidate &Cand2) {
9143   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9144       !Cand2.Function->isMultiVersion())
9145     return false;
9146 
9147   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9148   // is obviously better.
9149   if (Cand1.Function->isInvalidDecl()) return false;
9150   if (Cand2.Function->isInvalidDecl()) return true;
9151 
9152   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9153   // cpu_dispatch, else arbitrarily based on the identifiers.
9154   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9155   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9156   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9157   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9158 
9159   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9160     return false;
9161 
9162   if (Cand1CPUDisp && !Cand2CPUDisp)
9163     return true;
9164   if (Cand2CPUDisp && !Cand1CPUDisp)
9165     return false;
9166 
9167   if (Cand1CPUSpec && Cand2CPUSpec) {
9168     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9169       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9170 
9171     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9172         FirstDiff = std::mismatch(
9173             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9174             Cand2CPUSpec->cpus_begin(),
9175             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9176               return LHS->getName() == RHS->getName();
9177             });
9178 
9179     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9180            "Two different cpu-specific versions should not have the same "
9181            "identifier list, otherwise they'd be the same decl!");
9182     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9183   }
9184   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9185 }
9186 
9187 /// isBetterOverloadCandidate - Determines whether the first overload
9188 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9189 bool clang::isBetterOverloadCandidate(
9190     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9191     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9192   // Define viable functions to be better candidates than non-viable
9193   // functions.
9194   if (!Cand2.Viable)
9195     return Cand1.Viable;
9196   else if (!Cand1.Viable)
9197     return false;
9198 
9199   // C++ [over.match.best]p1:
9200   //
9201   //   -- if F is a static member function, ICS1(F) is defined such
9202   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9203   //      any function G, and, symmetrically, ICS1(G) is neither
9204   //      better nor worse than ICS1(F).
9205   unsigned StartArg = 0;
9206   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9207     StartArg = 1;
9208 
9209   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9210     // We don't allow incompatible pointer conversions in C++.
9211     if (!S.getLangOpts().CPlusPlus)
9212       return ICS.isStandard() &&
9213              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9214 
9215     // The only ill-formed conversion we allow in C++ is the string literal to
9216     // char* conversion, which is only considered ill-formed after C++11.
9217     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9218            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9219   };
9220 
9221   // Define functions that don't require ill-formed conversions for a given
9222   // argument to be better candidates than functions that do.
9223   unsigned NumArgs = Cand1.Conversions.size();
9224   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9225   bool HasBetterConversion = false;
9226   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9227     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9228     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9229     if (Cand1Bad != Cand2Bad) {
9230       if (Cand1Bad)
9231         return false;
9232       HasBetterConversion = true;
9233     }
9234   }
9235 
9236   if (HasBetterConversion)
9237     return true;
9238 
9239   // C++ [over.match.best]p1:
9240   //   A viable function F1 is defined to be a better function than another
9241   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9242   //   conversion sequence than ICSi(F2), and then...
9243   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9244     switch (CompareImplicitConversionSequences(S, Loc,
9245                                                Cand1.Conversions[ArgIdx],
9246                                                Cand2.Conversions[ArgIdx])) {
9247     case ImplicitConversionSequence::Better:
9248       // Cand1 has a better conversion sequence.
9249       HasBetterConversion = true;
9250       break;
9251 
9252     case ImplicitConversionSequence::Worse:
9253       // Cand1 can't be better than Cand2.
9254       return false;
9255 
9256     case ImplicitConversionSequence::Indistinguishable:
9257       // Do nothing.
9258       break;
9259     }
9260   }
9261 
9262   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9263   //       ICSj(F2), or, if not that,
9264   if (HasBetterConversion)
9265     return true;
9266 
9267   //   -- the context is an initialization by user-defined conversion
9268   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9269   //      from the return type of F1 to the destination type (i.e.,
9270   //      the type of the entity being initialized) is a better
9271   //      conversion sequence than the standard conversion sequence
9272   //      from the return type of F2 to the destination type.
9273   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9274       Cand1.Function && Cand2.Function &&
9275       isa<CXXConversionDecl>(Cand1.Function) &&
9276       isa<CXXConversionDecl>(Cand2.Function)) {
9277     // First check whether we prefer one of the conversion functions over the
9278     // other. This only distinguishes the results in non-standard, extension
9279     // cases such as the conversion from a lambda closure type to a function
9280     // pointer or block.
9281     ImplicitConversionSequence::CompareKind Result =
9282         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9283     if (Result == ImplicitConversionSequence::Indistinguishable)
9284       Result = CompareStandardConversionSequences(S, Loc,
9285                                                   Cand1.FinalConversion,
9286                                                   Cand2.FinalConversion);
9287 
9288     if (Result != ImplicitConversionSequence::Indistinguishable)
9289       return Result == ImplicitConversionSequence::Better;
9290 
9291     // FIXME: Compare kind of reference binding if conversion functions
9292     // convert to a reference type used in direct reference binding, per
9293     // C++14 [over.match.best]p1 section 2 bullet 3.
9294   }
9295 
9296   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9297   // as combined with the resolution to CWG issue 243.
9298   //
9299   // When the context is initialization by constructor ([over.match.ctor] or
9300   // either phase of [over.match.list]), a constructor is preferred over
9301   // a conversion function.
9302   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9303       Cand1.Function && Cand2.Function &&
9304       isa<CXXConstructorDecl>(Cand1.Function) !=
9305           isa<CXXConstructorDecl>(Cand2.Function))
9306     return isa<CXXConstructorDecl>(Cand1.Function);
9307 
9308   //    -- F1 is a non-template function and F2 is a function template
9309   //       specialization, or, if not that,
9310   bool Cand1IsSpecialization = Cand1.Function &&
9311                                Cand1.Function->getPrimaryTemplate();
9312   bool Cand2IsSpecialization = Cand2.Function &&
9313                                Cand2.Function->getPrimaryTemplate();
9314   if (Cand1IsSpecialization != Cand2IsSpecialization)
9315     return Cand2IsSpecialization;
9316 
9317   //   -- F1 and F2 are function template specializations, and the function
9318   //      template for F1 is more specialized than the template for F2
9319   //      according to the partial ordering rules described in 14.5.5.2, or,
9320   //      if not that,
9321   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9322     if (FunctionTemplateDecl *BetterTemplate
9323           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9324                                          Cand2.Function->getPrimaryTemplate(),
9325                                          Loc,
9326                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9327                                                              : TPOC_Call,
9328                                          Cand1.ExplicitCallArguments,
9329                                          Cand2.ExplicitCallArguments))
9330       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9331   }
9332 
9333   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9334   // A derived-class constructor beats an (inherited) base class constructor.
9335   bool Cand1IsInherited =
9336       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9337   bool Cand2IsInherited =
9338       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9339   if (Cand1IsInherited != Cand2IsInherited)
9340     return Cand2IsInherited;
9341   else if (Cand1IsInherited) {
9342     assert(Cand2IsInherited);
9343     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9344     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9345     if (Cand1Class->isDerivedFrom(Cand2Class))
9346       return true;
9347     if (Cand2Class->isDerivedFrom(Cand1Class))
9348       return false;
9349     // Inherited from sibling base classes: still ambiguous.
9350   }
9351 
9352   // Check C++17 tie-breakers for deduction guides.
9353   {
9354     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9355     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9356     if (Guide1 && Guide2) {
9357       //  -- F1 is generated from a deduction-guide and F2 is not
9358       if (Guide1->isImplicit() != Guide2->isImplicit())
9359         return Guide2->isImplicit();
9360 
9361       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9362       if (Guide1->isCopyDeductionCandidate())
9363         return true;
9364     }
9365   }
9366 
9367   // Check for enable_if value-based overload resolution.
9368   if (Cand1.Function && Cand2.Function) {
9369     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9370     if (Cmp != Comparison::Equal)
9371       return Cmp == Comparison::Better;
9372   }
9373 
9374   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9375     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9376     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9377            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9378   }
9379 
9380   bool HasPS1 = Cand1.Function != nullptr &&
9381                 functionHasPassObjectSizeParams(Cand1.Function);
9382   bool HasPS2 = Cand2.Function != nullptr &&
9383                 functionHasPassObjectSizeParams(Cand2.Function);
9384   if (HasPS1 != HasPS2 && HasPS1)
9385     return true;
9386 
9387   return isBetterMultiversionCandidate(Cand1, Cand2);
9388 }
9389 
9390 /// Determine whether two declarations are "equivalent" for the purposes of
9391 /// name lookup and overload resolution. This applies when the same internal/no
9392 /// linkage entity is defined by two modules (probably by textually including
9393 /// the same header). In such a case, we don't consider the declarations to
9394 /// declare the same entity, but we also don't want lookups with both
9395 /// declarations visible to be ambiguous in some cases (this happens when using
9396 /// a modularized libstdc++).
9397 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9398                                                   const NamedDecl *B) {
9399   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9400   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9401   if (!VA || !VB)
9402     return false;
9403 
9404   // The declarations must be declaring the same name as an internal linkage
9405   // entity in different modules.
9406   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9407           VB->getDeclContext()->getRedeclContext()) ||
9408       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9409           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9410       VA->isExternallyVisible() || VB->isExternallyVisible())
9411     return false;
9412 
9413   // Check that the declarations appear to be equivalent.
9414   //
9415   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9416   // For constants and functions, we should check the initializer or body is
9417   // the same. For non-constant variables, we shouldn't allow it at all.
9418   if (Context.hasSameType(VA->getType(), VB->getType()))
9419     return true;
9420 
9421   // Enum constants within unnamed enumerations will have different types, but
9422   // may still be similar enough to be interchangeable for our purposes.
9423   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9424     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9425       // Only handle anonymous enums. If the enumerations were named and
9426       // equivalent, they would have been merged to the same type.
9427       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9428       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9429       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9430           !Context.hasSameType(EnumA->getIntegerType(),
9431                                EnumB->getIntegerType()))
9432         return false;
9433       // Allow this only if the value is the same for both enumerators.
9434       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9435     }
9436   }
9437 
9438   // Nothing else is sufficiently similar.
9439   return false;
9440 }
9441 
9442 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9443     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9444   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9445 
9446   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9447   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9448       << !M << (M ? M->getFullModuleName() : "");
9449 
9450   for (auto *E : Equiv) {
9451     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9452     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9453         << !M << (M ? M->getFullModuleName() : "");
9454   }
9455 }
9456 
9457 /// Computes the best viable function (C++ 13.3.3)
9458 /// within an overload candidate set.
9459 ///
9460 /// \param Loc The location of the function name (or operator symbol) for
9461 /// which overload resolution occurs.
9462 ///
9463 /// \param Best If overload resolution was successful or found a deleted
9464 /// function, \p Best points to the candidate function found.
9465 ///
9466 /// \returns The result of overload resolution.
9467 OverloadingResult
9468 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9469                                          iterator &Best) {
9470   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9471   std::transform(begin(), end(), std::back_inserter(Candidates),
9472                  [](OverloadCandidate &Cand) { return &Cand; });
9473 
9474   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9475   // are accepted by both clang and NVCC. However, during a particular
9476   // compilation mode only one call variant is viable. We need to
9477   // exclude non-viable overload candidates from consideration based
9478   // only on their host/device attributes. Specifically, if one
9479   // candidate call is WrongSide and the other is SameSide, we ignore
9480   // the WrongSide candidate.
9481   if (S.getLangOpts().CUDA) {
9482     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9483     bool ContainsSameSideCandidate =
9484         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9485           // Check viable function only.
9486           return Cand->Viable && Cand->Function &&
9487                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9488                      Sema::CFP_SameSide;
9489         });
9490     if (ContainsSameSideCandidate) {
9491       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9492         // Check viable function only to avoid unnecessary data copying/moving.
9493         return Cand->Viable && Cand->Function &&
9494                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9495                    Sema::CFP_WrongSide;
9496       };
9497       llvm::erase_if(Candidates, IsWrongSideCandidate);
9498     }
9499   }
9500 
9501   // Find the best viable function.
9502   Best = end();
9503   for (auto *Cand : Candidates)
9504     if (Cand->Viable)
9505       if (Best == end() ||
9506           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9507         Best = Cand;
9508 
9509   // If we didn't find any viable functions, abort.
9510   if (Best == end())
9511     return OR_No_Viable_Function;
9512 
9513   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9514 
9515   // Make sure that this function is better than every other viable
9516   // function. If not, we have an ambiguity.
9517   for (auto *Cand : Candidates) {
9518     if (Cand->Viable && Cand != Best &&
9519         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9520       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9521                                                    Cand->Function)) {
9522         EquivalentCands.push_back(Cand->Function);
9523         continue;
9524       }
9525 
9526       Best = end();
9527       return OR_Ambiguous;
9528     }
9529   }
9530 
9531   // Best is the best viable function.
9532   if (Best->Function && Best->Function->isDeleted())
9533     return OR_Deleted;
9534 
9535   if (!EquivalentCands.empty())
9536     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9537                                                     EquivalentCands);
9538 
9539   return OR_Success;
9540 }
9541 
9542 namespace {
9543 
9544 enum OverloadCandidateKind {
9545   oc_function,
9546   oc_method,
9547   oc_constructor,
9548   oc_implicit_default_constructor,
9549   oc_implicit_copy_constructor,
9550   oc_implicit_move_constructor,
9551   oc_implicit_copy_assignment,
9552   oc_implicit_move_assignment,
9553   oc_inherited_constructor
9554 };
9555 
9556 enum OverloadCandidateSelect {
9557   ocs_non_template,
9558   ocs_template,
9559   ocs_described_template,
9560 };
9561 
9562 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9563 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9564                           std::string &Description) {
9565 
9566   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9567   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9568     isTemplate = true;
9569     Description = S.getTemplateArgumentBindingsText(
9570         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9571   }
9572 
9573   OverloadCandidateSelect Select = [&]() {
9574     if (!Description.empty())
9575       return ocs_described_template;
9576     return isTemplate ? ocs_template : ocs_non_template;
9577   }();
9578 
9579   OverloadCandidateKind Kind = [&]() {
9580     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9581       if (!Ctor->isImplicit()) {
9582         if (isa<ConstructorUsingShadowDecl>(Found))
9583           return oc_inherited_constructor;
9584         else
9585           return oc_constructor;
9586       }
9587 
9588       if (Ctor->isDefaultConstructor())
9589         return oc_implicit_default_constructor;
9590 
9591       if (Ctor->isMoveConstructor())
9592         return oc_implicit_move_constructor;
9593 
9594       assert(Ctor->isCopyConstructor() &&
9595              "unexpected sort of implicit constructor");
9596       return oc_implicit_copy_constructor;
9597     }
9598 
9599     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9600       // This actually gets spelled 'candidate function' for now, but
9601       // it doesn't hurt to split it out.
9602       if (!Meth->isImplicit())
9603         return oc_method;
9604 
9605       if (Meth->isMoveAssignmentOperator())
9606         return oc_implicit_move_assignment;
9607 
9608       if (Meth->isCopyAssignmentOperator())
9609         return oc_implicit_copy_assignment;
9610 
9611       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9612       return oc_method;
9613     }
9614 
9615     return oc_function;
9616   }();
9617 
9618   return std::make_pair(Kind, Select);
9619 }
9620 
9621 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9622   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9623   // set.
9624   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9625     S.Diag(FoundDecl->getLocation(),
9626            diag::note_ovl_candidate_inherited_constructor)
9627       << Shadow->getNominatedBaseClass();
9628 }
9629 
9630 } // end anonymous namespace
9631 
9632 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9633                                     const FunctionDecl *FD) {
9634   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9635     bool AlwaysTrue;
9636     if (EnableIf->getCond()->isValueDependent() ||
9637         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9638       return false;
9639     if (!AlwaysTrue)
9640       return false;
9641   }
9642   return true;
9643 }
9644 
9645 /// Returns true if we can take the address of the function.
9646 ///
9647 /// \param Complain - If true, we'll emit a diagnostic
9648 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9649 ///   we in overload resolution?
9650 /// \param Loc - The location of the statement we're complaining about. Ignored
9651 ///   if we're not complaining, or if we're in overload resolution.
9652 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9653                                               bool Complain,
9654                                               bool InOverloadResolution,
9655                                               SourceLocation Loc) {
9656   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9657     if (Complain) {
9658       if (InOverloadResolution)
9659         S.Diag(FD->getBeginLoc(),
9660                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9661       else
9662         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9663     }
9664     return false;
9665   }
9666 
9667   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9668     return P->hasAttr<PassObjectSizeAttr>();
9669   });
9670   if (I == FD->param_end())
9671     return true;
9672 
9673   if (Complain) {
9674     // Add one to ParamNo because it's user-facing
9675     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9676     if (InOverloadResolution)
9677       S.Diag(FD->getLocation(),
9678              diag::note_ovl_candidate_has_pass_object_size_params)
9679           << ParamNo;
9680     else
9681       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9682           << FD << ParamNo;
9683   }
9684   return false;
9685 }
9686 
9687 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9688                                                const FunctionDecl *FD) {
9689   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9690                                            /*InOverloadResolution=*/true,
9691                                            /*Loc=*/SourceLocation());
9692 }
9693 
9694 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9695                                              bool Complain,
9696                                              SourceLocation Loc) {
9697   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9698                                              /*InOverloadResolution=*/false,
9699                                              Loc);
9700 }
9701 
9702 // Notes the location of an overload candidate.
9703 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9704                                  QualType DestType, bool TakingAddress) {
9705   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9706     return;
9707   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9708       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9709     return;
9710 
9711   std::string FnDesc;
9712   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9713       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9714   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9715                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9716                          << Fn << FnDesc;
9717 
9718   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9719   Diag(Fn->getLocation(), PD);
9720   MaybeEmitInheritedConstructorNote(*this, Found);
9721 }
9722 
9723 // Notes the location of all overload candidates designated through
9724 // OverloadedExpr
9725 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9726                                      bool TakingAddress) {
9727   assert(OverloadedExpr->getType() == Context.OverloadTy);
9728 
9729   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9730   OverloadExpr *OvlExpr = Ovl.Expression;
9731 
9732   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9733                             IEnd = OvlExpr->decls_end();
9734        I != IEnd; ++I) {
9735     if (FunctionTemplateDecl *FunTmpl =
9736                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9737       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9738                             TakingAddress);
9739     } else if (FunctionDecl *Fun
9740                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9741       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9742     }
9743   }
9744 }
9745 
9746 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9747 /// "lead" diagnostic; it will be given two arguments, the source and
9748 /// target types of the conversion.
9749 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9750                                  Sema &S,
9751                                  SourceLocation CaretLoc,
9752                                  const PartialDiagnostic &PDiag) const {
9753   S.Diag(CaretLoc, PDiag)
9754     << Ambiguous.getFromType() << Ambiguous.getToType();
9755   // FIXME: The note limiting machinery is borrowed from
9756   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9757   // refactoring here.
9758   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9759   unsigned CandsShown = 0;
9760   AmbiguousConversionSequence::const_iterator I, E;
9761   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9762     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9763       break;
9764     ++CandsShown;
9765     S.NoteOverloadCandidate(I->first, I->second);
9766   }
9767   if (I != E)
9768     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9769 }
9770 
9771 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9772                                   unsigned I, bool TakingCandidateAddress) {
9773   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9774   assert(Conv.isBad());
9775   assert(Cand->Function && "for now, candidate must be a function");
9776   FunctionDecl *Fn = Cand->Function;
9777 
9778   // There's a conversion slot for the object argument if this is a
9779   // non-constructor method.  Note that 'I' corresponds the
9780   // conversion-slot index.
9781   bool isObjectArgument = false;
9782   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9783     if (I == 0)
9784       isObjectArgument = true;
9785     else
9786       I--;
9787   }
9788 
9789   std::string FnDesc;
9790   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9791       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9792 
9793   Expr *FromExpr = Conv.Bad.FromExpr;
9794   QualType FromTy = Conv.Bad.getFromType();
9795   QualType ToTy = Conv.Bad.getToType();
9796 
9797   if (FromTy == S.Context.OverloadTy) {
9798     assert(FromExpr && "overload set argument came from implicit argument?");
9799     Expr *E = FromExpr->IgnoreParens();
9800     if (isa<UnaryOperator>(E))
9801       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9802     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9803 
9804     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9805         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9806         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9807         << Name << I + 1;
9808     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9809     return;
9810   }
9811 
9812   // Do some hand-waving analysis to see if the non-viability is due
9813   // to a qualifier mismatch.
9814   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9815   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9816   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9817     CToTy = RT->getPointeeType();
9818   else {
9819     // TODO: detect and diagnose the full richness of const mismatches.
9820     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9821       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9822         CFromTy = FromPT->getPointeeType();
9823         CToTy = ToPT->getPointeeType();
9824       }
9825   }
9826 
9827   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9828       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9829     Qualifiers FromQs = CFromTy.getQualifiers();
9830     Qualifiers ToQs = CToTy.getQualifiers();
9831 
9832     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9833       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9834           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9835           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9836           << ToTy << (unsigned)isObjectArgument << I + 1;
9837       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9838       return;
9839     }
9840 
9841     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9842       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9843           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9844           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9845           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9846           << (unsigned)isObjectArgument << I + 1;
9847       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9848       return;
9849     }
9850 
9851     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9852       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9853           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9854           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9855           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9856           << (unsigned)isObjectArgument << I + 1;
9857       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9858       return;
9859     }
9860 
9861     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9862       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9863           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9864           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9865           << FromQs.hasUnaligned() << I + 1;
9866       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9867       return;
9868     }
9869 
9870     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9871     assert(CVR && "unexpected qualifiers mismatch");
9872 
9873     if (isObjectArgument) {
9874       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9875           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9876           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9877           << (CVR - 1);
9878     } else {
9879       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9880           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9881           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9882           << (CVR - 1) << I + 1;
9883     }
9884     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9885     return;
9886   }
9887 
9888   // Special diagnostic for failure to convert an initializer list, since
9889   // telling the user that it has type void is not useful.
9890   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9891     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9892         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9893         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9894         << ToTy << (unsigned)isObjectArgument << I + 1;
9895     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9896     return;
9897   }
9898 
9899   // Diagnose references or pointers to incomplete types differently,
9900   // since it's far from impossible that the incompleteness triggered
9901   // the failure.
9902   QualType TempFromTy = FromTy.getNonReferenceType();
9903   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9904     TempFromTy = PTy->getPointeeType();
9905   if (TempFromTy->isIncompleteType()) {
9906     // Emit the generic diagnostic and, optionally, add the hints to it.
9907     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9908         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9909         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9910         << ToTy << (unsigned)isObjectArgument << I + 1
9911         << (unsigned)(Cand->Fix.Kind);
9912 
9913     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9914     return;
9915   }
9916 
9917   // Diagnose base -> derived pointer conversions.
9918   unsigned BaseToDerivedConversion = 0;
9919   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9920     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9921       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9922                                                FromPtrTy->getPointeeType()) &&
9923           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9924           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9925           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9926                           FromPtrTy->getPointeeType()))
9927         BaseToDerivedConversion = 1;
9928     }
9929   } else if (const ObjCObjectPointerType *FromPtrTy
9930                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9931     if (const ObjCObjectPointerType *ToPtrTy
9932                                         = ToTy->getAs<ObjCObjectPointerType>())
9933       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9934         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9935           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9936                                                 FromPtrTy->getPointeeType()) &&
9937               FromIface->isSuperClassOf(ToIface))
9938             BaseToDerivedConversion = 2;
9939   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9940     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9941         !FromTy->isIncompleteType() &&
9942         !ToRefTy->getPointeeType()->isIncompleteType() &&
9943         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9944       BaseToDerivedConversion = 3;
9945     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9946                ToTy.getNonReferenceType().getCanonicalType() ==
9947                FromTy.getNonReferenceType().getCanonicalType()) {
9948       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9949           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9950           << (unsigned)isObjectArgument << I + 1
9951           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9952       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9953       return;
9954     }
9955   }
9956 
9957   if (BaseToDerivedConversion) {
9958     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9959         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9960         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9961         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9962     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9963     return;
9964   }
9965 
9966   if (isa<ObjCObjectPointerType>(CFromTy) &&
9967       isa<PointerType>(CToTy)) {
9968       Qualifiers FromQs = CFromTy.getQualifiers();
9969       Qualifiers ToQs = CToTy.getQualifiers();
9970       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9971         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9972             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9973             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9974             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9975         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9976         return;
9977       }
9978   }
9979 
9980   if (TakingCandidateAddress &&
9981       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9982     return;
9983 
9984   // Emit the generic diagnostic and, optionally, add the hints to it.
9985   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9986   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9987         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9988         << ToTy << (unsigned)isObjectArgument << I + 1
9989         << (unsigned)(Cand->Fix.Kind);
9990 
9991   // If we can fix the conversion, suggest the FixIts.
9992   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9993        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9994     FDiag << *HI;
9995   S.Diag(Fn->getLocation(), FDiag);
9996 
9997   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9998 }
9999 
10000 /// Additional arity mismatch diagnosis specific to a function overload
10001 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10002 /// over a candidate in any candidate set.
10003 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10004                                unsigned NumArgs) {
10005   FunctionDecl *Fn = Cand->Function;
10006   unsigned MinParams = Fn->getMinRequiredArguments();
10007 
10008   // With invalid overloaded operators, it's possible that we think we
10009   // have an arity mismatch when in fact it looks like we have the
10010   // right number of arguments, because only overloaded operators have
10011   // the weird behavior of overloading member and non-member functions.
10012   // Just don't report anything.
10013   if (Fn->isInvalidDecl() &&
10014       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10015     return true;
10016 
10017   if (NumArgs < MinParams) {
10018     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10019            (Cand->FailureKind == ovl_fail_bad_deduction &&
10020             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10021   } else {
10022     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10023            (Cand->FailureKind == ovl_fail_bad_deduction &&
10024             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10025   }
10026 
10027   return false;
10028 }
10029 
10030 /// General arity mismatch diagnosis over a candidate in a candidate set.
10031 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10032                                   unsigned NumFormalArgs) {
10033   assert(isa<FunctionDecl>(D) &&
10034       "The templated declaration should at least be a function"
10035       " when diagnosing bad template argument deduction due to too many"
10036       " or too few arguments");
10037 
10038   FunctionDecl *Fn = cast<FunctionDecl>(D);
10039 
10040   // TODO: treat calls to a missing default constructor as a special case
10041   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10042   unsigned MinParams = Fn->getMinRequiredArguments();
10043 
10044   // at least / at most / exactly
10045   unsigned mode, modeCount;
10046   if (NumFormalArgs < MinParams) {
10047     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10048         FnTy->isTemplateVariadic())
10049       mode = 0; // "at least"
10050     else
10051       mode = 2; // "exactly"
10052     modeCount = MinParams;
10053   } else {
10054     if (MinParams != FnTy->getNumParams())
10055       mode = 1; // "at most"
10056     else
10057       mode = 2; // "exactly"
10058     modeCount = FnTy->getNumParams();
10059   }
10060 
10061   std::string Description;
10062   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10063       ClassifyOverloadCandidate(S, Found, Fn, Description);
10064 
10065   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10066     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10067         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10068         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10069   else
10070     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10071         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10072         << Description << mode << modeCount << NumFormalArgs;
10073 
10074   MaybeEmitInheritedConstructorNote(S, Found);
10075 }
10076 
10077 /// Arity mismatch diagnosis specific to a function overload candidate.
10078 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10079                                   unsigned NumFormalArgs) {
10080   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10081     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10082 }
10083 
10084 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10085   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10086     return TD;
10087   llvm_unreachable("Unsupported: Getting the described template declaration"
10088                    " for bad deduction diagnosis");
10089 }
10090 
10091 /// Diagnose a failed template-argument deduction.
10092 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10093                                  DeductionFailureInfo &DeductionFailure,
10094                                  unsigned NumArgs,
10095                                  bool TakingCandidateAddress) {
10096   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10097   NamedDecl *ParamD;
10098   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10099   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10100   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10101   switch (DeductionFailure.Result) {
10102   case Sema::TDK_Success:
10103     llvm_unreachable("TDK_success while diagnosing bad deduction");
10104 
10105   case Sema::TDK_Incomplete: {
10106     assert(ParamD && "no parameter found for incomplete deduction result");
10107     S.Diag(Templated->getLocation(),
10108            diag::note_ovl_candidate_incomplete_deduction)
10109         << ParamD->getDeclName();
10110     MaybeEmitInheritedConstructorNote(S, Found);
10111     return;
10112   }
10113 
10114   case Sema::TDK_IncompletePack: {
10115     assert(ParamD && "no parameter found for incomplete deduction result");
10116     S.Diag(Templated->getLocation(),
10117            diag::note_ovl_candidate_incomplete_deduction_pack)
10118         << ParamD->getDeclName()
10119         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10120         << *DeductionFailure.getFirstArg();
10121     MaybeEmitInheritedConstructorNote(S, Found);
10122     return;
10123   }
10124 
10125   case Sema::TDK_Underqualified: {
10126     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10127     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10128 
10129     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10130 
10131     // Param will have been canonicalized, but it should just be a
10132     // qualified version of ParamD, so move the qualifiers to that.
10133     QualifierCollector Qs;
10134     Qs.strip(Param);
10135     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10136     assert(S.Context.hasSameType(Param, NonCanonParam));
10137 
10138     // Arg has also been canonicalized, but there's nothing we can do
10139     // about that.  It also doesn't matter as much, because it won't
10140     // have any template parameters in it (because deduction isn't
10141     // done on dependent types).
10142     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10143 
10144     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10145         << ParamD->getDeclName() << Arg << NonCanonParam;
10146     MaybeEmitInheritedConstructorNote(S, Found);
10147     return;
10148   }
10149 
10150   case Sema::TDK_Inconsistent: {
10151     assert(ParamD && "no parameter found for inconsistent deduction result");
10152     int which = 0;
10153     if (isa<TemplateTypeParmDecl>(ParamD))
10154       which = 0;
10155     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10156       // Deduction might have failed because we deduced arguments of two
10157       // different types for a non-type template parameter.
10158       // FIXME: Use a different TDK value for this.
10159       QualType T1 =
10160           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10161       QualType T2 =
10162           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10163       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10164         S.Diag(Templated->getLocation(),
10165                diag::note_ovl_candidate_inconsistent_deduction_types)
10166           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10167           << *DeductionFailure.getSecondArg() << T2;
10168         MaybeEmitInheritedConstructorNote(S, Found);
10169         return;
10170       }
10171 
10172       which = 1;
10173     } else {
10174       which = 2;
10175     }
10176 
10177     S.Diag(Templated->getLocation(),
10178            diag::note_ovl_candidate_inconsistent_deduction)
10179         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10180         << *DeductionFailure.getSecondArg();
10181     MaybeEmitInheritedConstructorNote(S, Found);
10182     return;
10183   }
10184 
10185   case Sema::TDK_InvalidExplicitArguments:
10186     assert(ParamD && "no parameter found for invalid explicit arguments");
10187     if (ParamD->getDeclName())
10188       S.Diag(Templated->getLocation(),
10189              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10190           << ParamD->getDeclName();
10191     else {
10192       int index = 0;
10193       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10194         index = TTP->getIndex();
10195       else if (NonTypeTemplateParmDecl *NTTP
10196                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10197         index = NTTP->getIndex();
10198       else
10199         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10200       S.Diag(Templated->getLocation(),
10201              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10202           << (index + 1);
10203     }
10204     MaybeEmitInheritedConstructorNote(S, Found);
10205     return;
10206 
10207   case Sema::TDK_TooManyArguments:
10208   case Sema::TDK_TooFewArguments:
10209     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10210     return;
10211 
10212   case Sema::TDK_InstantiationDepth:
10213     S.Diag(Templated->getLocation(),
10214            diag::note_ovl_candidate_instantiation_depth);
10215     MaybeEmitInheritedConstructorNote(S, Found);
10216     return;
10217 
10218   case Sema::TDK_SubstitutionFailure: {
10219     // Format the template argument list into the argument string.
10220     SmallString<128> TemplateArgString;
10221     if (TemplateArgumentList *Args =
10222             DeductionFailure.getTemplateArgumentList()) {
10223       TemplateArgString = " ";
10224       TemplateArgString += S.getTemplateArgumentBindingsText(
10225           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10226     }
10227 
10228     // If this candidate was disabled by enable_if, say so.
10229     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10230     if (PDiag && PDiag->second.getDiagID() ==
10231           diag::err_typename_nested_not_found_enable_if) {
10232       // FIXME: Use the source range of the condition, and the fully-qualified
10233       //        name of the enable_if template. These are both present in PDiag.
10234       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10235         << "'enable_if'" << TemplateArgString;
10236       return;
10237     }
10238 
10239     // We found a specific requirement that disabled the enable_if.
10240     if (PDiag && PDiag->second.getDiagID() ==
10241         diag::err_typename_nested_not_found_requirement) {
10242       S.Diag(Templated->getLocation(),
10243              diag::note_ovl_candidate_disabled_by_requirement)
10244         << PDiag->second.getStringArg(0) << TemplateArgString;
10245       return;
10246     }
10247 
10248     // Format the SFINAE diagnostic into the argument string.
10249     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10250     //        formatted message in another diagnostic.
10251     SmallString<128> SFINAEArgString;
10252     SourceRange R;
10253     if (PDiag) {
10254       SFINAEArgString = ": ";
10255       R = SourceRange(PDiag->first, PDiag->first);
10256       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10257     }
10258 
10259     S.Diag(Templated->getLocation(),
10260            diag::note_ovl_candidate_substitution_failure)
10261         << TemplateArgString << SFINAEArgString << R;
10262     MaybeEmitInheritedConstructorNote(S, Found);
10263     return;
10264   }
10265 
10266   case Sema::TDK_DeducedMismatch:
10267   case Sema::TDK_DeducedMismatchNested: {
10268     // Format the template argument list into the argument string.
10269     SmallString<128> TemplateArgString;
10270     if (TemplateArgumentList *Args =
10271             DeductionFailure.getTemplateArgumentList()) {
10272       TemplateArgString = " ";
10273       TemplateArgString += S.getTemplateArgumentBindingsText(
10274           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10275     }
10276 
10277     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10278         << (*DeductionFailure.getCallArgIndex() + 1)
10279         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10280         << TemplateArgString
10281         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10282     break;
10283   }
10284 
10285   case Sema::TDK_NonDeducedMismatch: {
10286     // FIXME: Provide a source location to indicate what we couldn't match.
10287     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10288     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10289     if (FirstTA.getKind() == TemplateArgument::Template &&
10290         SecondTA.getKind() == TemplateArgument::Template) {
10291       TemplateName FirstTN = FirstTA.getAsTemplate();
10292       TemplateName SecondTN = SecondTA.getAsTemplate();
10293       if (FirstTN.getKind() == TemplateName::Template &&
10294           SecondTN.getKind() == TemplateName::Template) {
10295         if (FirstTN.getAsTemplateDecl()->getName() ==
10296             SecondTN.getAsTemplateDecl()->getName()) {
10297           // FIXME: This fixes a bad diagnostic where both templates are named
10298           // the same.  This particular case is a bit difficult since:
10299           // 1) It is passed as a string to the diagnostic printer.
10300           // 2) The diagnostic printer only attempts to find a better
10301           //    name for types, not decls.
10302           // Ideally, this should folded into the diagnostic printer.
10303           S.Diag(Templated->getLocation(),
10304                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10305               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10306           return;
10307         }
10308       }
10309     }
10310 
10311     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10312         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10313       return;
10314 
10315     // FIXME: For generic lambda parameters, check if the function is a lambda
10316     // call operator, and if so, emit a prettier and more informative
10317     // diagnostic that mentions 'auto' and lambda in addition to
10318     // (or instead of?) the canonical template type parameters.
10319     S.Diag(Templated->getLocation(),
10320            diag::note_ovl_candidate_non_deduced_mismatch)
10321         << FirstTA << SecondTA;
10322     return;
10323   }
10324   // TODO: diagnose these individually, then kill off
10325   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10326   case Sema::TDK_MiscellaneousDeductionFailure:
10327     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10328     MaybeEmitInheritedConstructorNote(S, Found);
10329     return;
10330   case Sema::TDK_CUDATargetMismatch:
10331     S.Diag(Templated->getLocation(),
10332            diag::note_cuda_ovl_candidate_target_mismatch);
10333     return;
10334   }
10335 }
10336 
10337 /// Diagnose a failed template-argument deduction, for function calls.
10338 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10339                                  unsigned NumArgs,
10340                                  bool TakingCandidateAddress) {
10341   unsigned TDK = Cand->DeductionFailure.Result;
10342   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10343     if (CheckArityMismatch(S, Cand, NumArgs))
10344       return;
10345   }
10346   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10347                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10348 }
10349 
10350 /// CUDA: diagnose an invalid call across targets.
10351 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10352   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10353   FunctionDecl *Callee = Cand->Function;
10354 
10355   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10356                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10357 
10358   std::string FnDesc;
10359   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10360       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10361 
10362   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10363       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10364       << FnDesc /* Ignored */
10365       << CalleeTarget << CallerTarget;
10366 
10367   // This could be an implicit constructor for which we could not infer the
10368   // target due to a collsion. Diagnose that case.
10369   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10370   if (Meth != nullptr && Meth->isImplicit()) {
10371     CXXRecordDecl *ParentClass = Meth->getParent();
10372     Sema::CXXSpecialMember CSM;
10373 
10374     switch (FnKindPair.first) {
10375     default:
10376       return;
10377     case oc_implicit_default_constructor:
10378       CSM = Sema::CXXDefaultConstructor;
10379       break;
10380     case oc_implicit_copy_constructor:
10381       CSM = Sema::CXXCopyConstructor;
10382       break;
10383     case oc_implicit_move_constructor:
10384       CSM = Sema::CXXMoveConstructor;
10385       break;
10386     case oc_implicit_copy_assignment:
10387       CSM = Sema::CXXCopyAssignment;
10388       break;
10389     case oc_implicit_move_assignment:
10390       CSM = Sema::CXXMoveAssignment;
10391       break;
10392     };
10393 
10394     bool ConstRHS = false;
10395     if (Meth->getNumParams()) {
10396       if (const ReferenceType *RT =
10397               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10398         ConstRHS = RT->getPointeeType().isConstQualified();
10399       }
10400     }
10401 
10402     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10403                                               /* ConstRHS */ ConstRHS,
10404                                               /* Diagnose */ true);
10405   }
10406 }
10407 
10408 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10409   FunctionDecl *Callee = Cand->Function;
10410   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10411 
10412   S.Diag(Callee->getLocation(),
10413          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10414       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10415 }
10416 
10417 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10418   ExplicitSpecifier ES;
10419   const char *DeclName;
10420   switch (Cand->Function->getDeclKind()) {
10421   case Decl::Kind::CXXConstructor:
10422     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10423     DeclName = "constructor";
10424     break;
10425   case Decl::Kind::CXXConversion:
10426     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10427     DeclName = "conversion operator";
10428     break;
10429   case Decl::Kind::CXXDeductionGuide:
10430     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10431     DeclName = "deductiong guide";
10432     break;
10433   default:
10434     llvm_unreachable("invalid Decl");
10435   }
10436   assert(ES.getExpr() && "null expression should be handled before");
10437   S.Diag(Cand->Function->getLocation(),
10438          diag::note_ovl_candidate_explicit_forbidden)
10439       << DeclName;
10440   S.Diag(ES.getExpr()->getBeginLoc(),
10441          diag::note_explicit_bool_resolved_to_true);
10442 }
10443 
10444 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10445   FunctionDecl *Callee = Cand->Function;
10446 
10447   S.Diag(Callee->getLocation(),
10448          diag::note_ovl_candidate_disabled_by_extension)
10449     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10450 }
10451 
10452 /// Generates a 'note' diagnostic for an overload candidate.  We've
10453 /// already generated a primary error at the call site.
10454 ///
10455 /// It really does need to be a single diagnostic with its caret
10456 /// pointed at the candidate declaration.  Yes, this creates some
10457 /// major challenges of technical writing.  Yes, this makes pointing
10458 /// out problems with specific arguments quite awkward.  It's still
10459 /// better than generating twenty screens of text for every failed
10460 /// overload.
10461 ///
10462 /// It would be great to be able to express per-candidate problems
10463 /// more richly for those diagnostic clients that cared, but we'd
10464 /// still have to be just as careful with the default diagnostics.
10465 /// \param CtorDestAS Addr space of object being constructed (for ctor
10466 /// candidates only).
10467 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10468                                   unsigned NumArgs,
10469                                   bool TakingCandidateAddress,
10470                                   LangAS CtorDestAS = LangAS::Default) {
10471   FunctionDecl *Fn = Cand->Function;
10472 
10473   // Note deleted candidates, but only if they're viable.
10474   if (Cand->Viable) {
10475     if (Fn->isDeleted()) {
10476       std::string FnDesc;
10477       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10478           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10479 
10480       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10481           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10482           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10483       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10484       return;
10485     }
10486 
10487     // We don't really have anything else to say about viable candidates.
10488     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10489     return;
10490   }
10491 
10492   switch (Cand->FailureKind) {
10493   case ovl_fail_too_many_arguments:
10494   case ovl_fail_too_few_arguments:
10495     return DiagnoseArityMismatch(S, Cand, NumArgs);
10496 
10497   case ovl_fail_bad_deduction:
10498     return DiagnoseBadDeduction(S, Cand, NumArgs,
10499                                 TakingCandidateAddress);
10500 
10501   case ovl_fail_illegal_constructor: {
10502     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10503       << (Fn->getPrimaryTemplate() ? 1 : 0);
10504     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10505     return;
10506   }
10507 
10508   case ovl_fail_object_addrspace_mismatch: {
10509     Qualifiers QualsForPrinting;
10510     QualsForPrinting.setAddressSpace(CtorDestAS);
10511     S.Diag(Fn->getLocation(),
10512            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10513         << QualsForPrinting;
10514     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10515     return;
10516   }
10517 
10518   case ovl_fail_trivial_conversion:
10519   case ovl_fail_bad_final_conversion:
10520   case ovl_fail_final_conversion_not_exact:
10521     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10522 
10523   case ovl_fail_bad_conversion: {
10524     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10525     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10526       if (Cand->Conversions[I].isBad())
10527         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10528 
10529     // FIXME: this currently happens when we're called from SemaInit
10530     // when user-conversion overload fails.  Figure out how to handle
10531     // those conditions and diagnose them well.
10532     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10533   }
10534 
10535   case ovl_fail_bad_target:
10536     return DiagnoseBadTarget(S, Cand);
10537 
10538   case ovl_fail_enable_if:
10539     return DiagnoseFailedEnableIfAttr(S, Cand);
10540 
10541   case ovl_fail_explicit_resolved:
10542     return DiagnoseFailedExplicitSpec(S, Cand);
10543 
10544   case ovl_fail_ext_disabled:
10545     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10546 
10547   case ovl_fail_inhctor_slice:
10548     // It's generally not interesting to note copy/move constructors here.
10549     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10550       return;
10551     S.Diag(Fn->getLocation(),
10552            diag::note_ovl_candidate_inherited_constructor_slice)
10553       << (Fn->getPrimaryTemplate() ? 1 : 0)
10554       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10555     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10556     return;
10557 
10558   case ovl_fail_addr_not_available: {
10559     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10560     (void)Available;
10561     assert(!Available);
10562     break;
10563   }
10564   case ovl_non_default_multiversion_function:
10565     // Do nothing, these should simply be ignored.
10566     break;
10567   }
10568 }
10569 
10570 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10571   // Desugar the type of the surrogate down to a function type,
10572   // retaining as many typedefs as possible while still showing
10573   // the function type (and, therefore, its parameter types).
10574   QualType FnType = Cand->Surrogate->getConversionType();
10575   bool isLValueReference = false;
10576   bool isRValueReference = false;
10577   bool isPointer = false;
10578   if (const LValueReferenceType *FnTypeRef =
10579         FnType->getAs<LValueReferenceType>()) {
10580     FnType = FnTypeRef->getPointeeType();
10581     isLValueReference = true;
10582   } else if (const RValueReferenceType *FnTypeRef =
10583                FnType->getAs<RValueReferenceType>()) {
10584     FnType = FnTypeRef->getPointeeType();
10585     isRValueReference = true;
10586   }
10587   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10588     FnType = FnTypePtr->getPointeeType();
10589     isPointer = true;
10590   }
10591   // Desugar down to a function type.
10592   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10593   // Reconstruct the pointer/reference as appropriate.
10594   if (isPointer) FnType = S.Context.getPointerType(FnType);
10595   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10596   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10597 
10598   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10599     << FnType;
10600 }
10601 
10602 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10603                                          SourceLocation OpLoc,
10604                                          OverloadCandidate *Cand) {
10605   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10606   std::string TypeStr("operator");
10607   TypeStr += Opc;
10608   TypeStr += "(";
10609   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10610   if (Cand->Conversions.size() == 1) {
10611     TypeStr += ")";
10612     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10613   } else {
10614     TypeStr += ", ";
10615     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10616     TypeStr += ")";
10617     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10618   }
10619 }
10620 
10621 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10622                                          OverloadCandidate *Cand) {
10623   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10624     if (ICS.isBad()) break; // all meaningless after first invalid
10625     if (!ICS.isAmbiguous()) continue;
10626 
10627     ICS.DiagnoseAmbiguousConversion(
10628         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10629   }
10630 }
10631 
10632 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10633   if (Cand->Function)
10634     return Cand->Function->getLocation();
10635   if (Cand->IsSurrogate)
10636     return Cand->Surrogate->getLocation();
10637   return SourceLocation();
10638 }
10639 
10640 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10641   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10642   case Sema::TDK_Success:
10643   case Sema::TDK_NonDependentConversionFailure:
10644     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10645 
10646   case Sema::TDK_Invalid:
10647   case Sema::TDK_Incomplete:
10648   case Sema::TDK_IncompletePack:
10649     return 1;
10650 
10651   case Sema::TDK_Underqualified:
10652   case Sema::TDK_Inconsistent:
10653     return 2;
10654 
10655   case Sema::TDK_SubstitutionFailure:
10656   case Sema::TDK_DeducedMismatch:
10657   case Sema::TDK_DeducedMismatchNested:
10658   case Sema::TDK_NonDeducedMismatch:
10659   case Sema::TDK_MiscellaneousDeductionFailure:
10660   case Sema::TDK_CUDATargetMismatch:
10661     return 3;
10662 
10663   case Sema::TDK_InstantiationDepth:
10664     return 4;
10665 
10666   case Sema::TDK_InvalidExplicitArguments:
10667     return 5;
10668 
10669   case Sema::TDK_TooManyArguments:
10670   case Sema::TDK_TooFewArguments:
10671     return 6;
10672   }
10673   llvm_unreachable("Unhandled deduction result");
10674 }
10675 
10676 namespace {
10677 struct CompareOverloadCandidatesForDisplay {
10678   Sema &S;
10679   SourceLocation Loc;
10680   size_t NumArgs;
10681   OverloadCandidateSet::CandidateSetKind CSK;
10682 
10683   CompareOverloadCandidatesForDisplay(
10684       Sema &S, SourceLocation Loc, size_t NArgs,
10685       OverloadCandidateSet::CandidateSetKind CSK)
10686       : S(S), NumArgs(NArgs), CSK(CSK) {}
10687 
10688   bool operator()(const OverloadCandidate *L,
10689                   const OverloadCandidate *R) {
10690     // Fast-path this check.
10691     if (L == R) return false;
10692 
10693     // Order first by viability.
10694     if (L->Viable) {
10695       if (!R->Viable) return true;
10696 
10697       // TODO: introduce a tri-valued comparison for overload
10698       // candidates.  Would be more worthwhile if we had a sort
10699       // that could exploit it.
10700       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10701         return true;
10702       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10703         return false;
10704     } else if (R->Viable)
10705       return false;
10706 
10707     assert(L->Viable == R->Viable);
10708 
10709     // Criteria by which we can sort non-viable candidates:
10710     if (!L->Viable) {
10711       // 1. Arity mismatches come after other candidates.
10712       if (L->FailureKind == ovl_fail_too_many_arguments ||
10713           L->FailureKind == ovl_fail_too_few_arguments) {
10714         if (R->FailureKind == ovl_fail_too_many_arguments ||
10715             R->FailureKind == ovl_fail_too_few_arguments) {
10716           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10717           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10718           if (LDist == RDist) {
10719             if (L->FailureKind == R->FailureKind)
10720               // Sort non-surrogates before surrogates.
10721               return !L->IsSurrogate && R->IsSurrogate;
10722             // Sort candidates requiring fewer parameters than there were
10723             // arguments given after candidates requiring more parameters
10724             // than there were arguments given.
10725             return L->FailureKind == ovl_fail_too_many_arguments;
10726           }
10727           return LDist < RDist;
10728         }
10729         return false;
10730       }
10731       if (R->FailureKind == ovl_fail_too_many_arguments ||
10732           R->FailureKind == ovl_fail_too_few_arguments)
10733         return true;
10734 
10735       // 2. Bad conversions come first and are ordered by the number
10736       // of bad conversions and quality of good conversions.
10737       if (L->FailureKind == ovl_fail_bad_conversion) {
10738         if (R->FailureKind != ovl_fail_bad_conversion)
10739           return true;
10740 
10741         // The conversion that can be fixed with a smaller number of changes,
10742         // comes first.
10743         unsigned numLFixes = L->Fix.NumConversionsFixed;
10744         unsigned numRFixes = R->Fix.NumConversionsFixed;
10745         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10746         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10747         if (numLFixes != numRFixes) {
10748           return numLFixes < numRFixes;
10749         }
10750 
10751         // If there's any ordering between the defined conversions...
10752         // FIXME: this might not be transitive.
10753         assert(L->Conversions.size() == R->Conversions.size());
10754 
10755         int leftBetter = 0;
10756         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10757         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10758           switch (CompareImplicitConversionSequences(S, Loc,
10759                                                      L->Conversions[I],
10760                                                      R->Conversions[I])) {
10761           case ImplicitConversionSequence::Better:
10762             leftBetter++;
10763             break;
10764 
10765           case ImplicitConversionSequence::Worse:
10766             leftBetter--;
10767             break;
10768 
10769           case ImplicitConversionSequence::Indistinguishable:
10770             break;
10771           }
10772         }
10773         if (leftBetter > 0) return true;
10774         if (leftBetter < 0) return false;
10775 
10776       } else if (R->FailureKind == ovl_fail_bad_conversion)
10777         return false;
10778 
10779       if (L->FailureKind == ovl_fail_bad_deduction) {
10780         if (R->FailureKind != ovl_fail_bad_deduction)
10781           return true;
10782 
10783         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10784           return RankDeductionFailure(L->DeductionFailure)
10785                < RankDeductionFailure(R->DeductionFailure);
10786       } else if (R->FailureKind == ovl_fail_bad_deduction)
10787         return false;
10788 
10789       // TODO: others?
10790     }
10791 
10792     // Sort everything else by location.
10793     SourceLocation LLoc = GetLocationForCandidate(L);
10794     SourceLocation RLoc = GetLocationForCandidate(R);
10795 
10796     // Put candidates without locations (e.g. builtins) at the end.
10797     if (LLoc.isInvalid()) return false;
10798     if (RLoc.isInvalid()) return true;
10799 
10800     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10801   }
10802 };
10803 }
10804 
10805 /// CompleteNonViableCandidate - Normally, overload resolution only
10806 /// computes up to the first bad conversion. Produces the FixIt set if
10807 /// possible.
10808 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10809                                        ArrayRef<Expr *> Args) {
10810   assert(!Cand->Viable);
10811 
10812   // Don't do anything on failures other than bad conversion.
10813   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10814 
10815   // We only want the FixIts if all the arguments can be corrected.
10816   bool Unfixable = false;
10817   // Use a implicit copy initialization to check conversion fixes.
10818   Cand->Fix.setConversionChecker(TryCopyInitialization);
10819 
10820   // Attempt to fix the bad conversion.
10821   unsigned ConvCount = Cand->Conversions.size();
10822   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10823        ++ConvIdx) {
10824     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10825     if (Cand->Conversions[ConvIdx].isInitialized() &&
10826         Cand->Conversions[ConvIdx].isBad()) {
10827       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10828       break;
10829     }
10830   }
10831 
10832   // FIXME: this should probably be preserved from the overload
10833   // operation somehow.
10834   bool SuppressUserConversions = false;
10835 
10836   unsigned ConvIdx = 0;
10837   ArrayRef<QualType> ParamTypes;
10838 
10839   if (Cand->IsSurrogate) {
10840     QualType ConvType
10841       = Cand->Surrogate->getConversionType().getNonReferenceType();
10842     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10843       ConvType = ConvPtrType->getPointeeType();
10844     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
10845     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10846     ConvIdx = 1;
10847   } else if (Cand->Function) {
10848     ParamTypes =
10849         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
10850     if (isa<CXXMethodDecl>(Cand->Function) &&
10851         !isa<CXXConstructorDecl>(Cand->Function)) {
10852       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10853       ConvIdx = 1;
10854     }
10855   } else {
10856     // Builtin operator.
10857     assert(ConvCount <= 3);
10858     ParamTypes = Cand->BuiltinParamTypes;
10859   }
10860 
10861   // Fill in the rest of the conversions.
10862   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10863     if (Cand->Conversions[ConvIdx].isInitialized()) {
10864       // We've already checked this conversion.
10865     } else if (ArgIdx < ParamTypes.size()) {
10866       if (ParamTypes[ArgIdx]->isDependentType())
10867         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10868             Args[ArgIdx]->getType());
10869       else {
10870         Cand->Conversions[ConvIdx] =
10871             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10872                                   SuppressUserConversions,
10873                                   /*InOverloadResolution=*/true,
10874                                   /*AllowObjCWritebackConversion=*/
10875                                   S.getLangOpts().ObjCAutoRefCount);
10876         // Store the FixIt in the candidate if it exists.
10877         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10878           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10879       }
10880     } else
10881       Cand->Conversions[ConvIdx].setEllipsis();
10882   }
10883 }
10884 
10885 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
10886     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10887     SourceLocation OpLoc,
10888     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10889   // Sort the candidates by viability and position.  Sorting directly would
10890   // be prohibitive, so we make a set of pointers and sort those.
10891   SmallVector<OverloadCandidate*, 32> Cands;
10892   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10893   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10894     if (!Filter(*Cand))
10895       continue;
10896     if (Cand->Viable)
10897       Cands.push_back(Cand);
10898     else if (OCD == OCD_AllCandidates) {
10899       CompleteNonViableCandidate(S, Cand, Args);
10900       if (Cand->Function || Cand->IsSurrogate)
10901         Cands.push_back(Cand);
10902       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10903       // want to list every possible builtin candidate.
10904     }
10905   }
10906 
10907   llvm::stable_sort(
10908       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10909 
10910   return Cands;
10911 }
10912 
10913 /// When overload resolution fails, prints diagnostic messages containing the
10914 /// candidates in the candidate set.
10915 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
10916     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10917     StringRef Opc, SourceLocation OpLoc,
10918     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10919 
10920   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
10921 
10922   S.Diag(PD.first, PD.second);
10923 
10924   NoteCandidates(S, Args, Cands, Opc, OpLoc);
10925 }
10926 
10927 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
10928                                           ArrayRef<OverloadCandidate *> Cands,
10929                                           StringRef Opc, SourceLocation OpLoc) {
10930   bool ReportedAmbiguousConversions = false;
10931 
10932   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10933   unsigned CandsShown = 0;
10934   auto I = Cands.begin(), E = Cands.end();
10935   for (; I != E; ++I) {
10936     OverloadCandidate *Cand = *I;
10937 
10938     // Set an arbitrary limit on the number of candidate functions we'll spam
10939     // the user with.  FIXME: This limit should depend on details of the
10940     // candidate list.
10941     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10942       break;
10943     }
10944     ++CandsShown;
10945 
10946     if (Cand->Function)
10947       NoteFunctionCandidate(S, Cand, Args.size(),
10948                             /*TakingCandidateAddress=*/false, DestAS);
10949     else if (Cand->IsSurrogate)
10950       NoteSurrogateCandidate(S, Cand);
10951     else {
10952       assert(Cand->Viable &&
10953              "Non-viable built-in candidates are not added to Cands.");
10954       // Generally we only see ambiguities including viable builtin
10955       // operators if overload resolution got screwed up by an
10956       // ambiguous user-defined conversion.
10957       //
10958       // FIXME: It's quite possible for different conversions to see
10959       // different ambiguities, though.
10960       if (!ReportedAmbiguousConversions) {
10961         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10962         ReportedAmbiguousConversions = true;
10963       }
10964 
10965       // If this is a viable builtin, print it.
10966       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10967     }
10968   }
10969 
10970   if (I != E)
10971     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10972 }
10973 
10974 static SourceLocation
10975 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10976   return Cand->Specialization ? Cand->Specialization->getLocation()
10977                               : SourceLocation();
10978 }
10979 
10980 namespace {
10981 struct CompareTemplateSpecCandidatesForDisplay {
10982   Sema &S;
10983   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10984 
10985   bool operator()(const TemplateSpecCandidate *L,
10986                   const TemplateSpecCandidate *R) {
10987     // Fast-path this check.
10988     if (L == R)
10989       return false;
10990 
10991     // Assuming that both candidates are not matches...
10992 
10993     // Sort by the ranking of deduction failures.
10994     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10995       return RankDeductionFailure(L->DeductionFailure) <
10996              RankDeductionFailure(R->DeductionFailure);
10997 
10998     // Sort everything else by location.
10999     SourceLocation LLoc = GetLocationForCandidate(L);
11000     SourceLocation RLoc = GetLocationForCandidate(R);
11001 
11002     // Put candidates without locations (e.g. builtins) at the end.
11003     if (LLoc.isInvalid())
11004       return false;
11005     if (RLoc.isInvalid())
11006       return true;
11007 
11008     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11009   }
11010 };
11011 }
11012 
11013 /// Diagnose a template argument deduction failure.
11014 /// We are treating these failures as overload failures due to bad
11015 /// deductions.
11016 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11017                                                  bool ForTakingAddress) {
11018   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11019                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11020 }
11021 
11022 void TemplateSpecCandidateSet::destroyCandidates() {
11023   for (iterator i = begin(), e = end(); i != e; ++i) {
11024     i->DeductionFailure.Destroy();
11025   }
11026 }
11027 
11028 void TemplateSpecCandidateSet::clear() {
11029   destroyCandidates();
11030   Candidates.clear();
11031 }
11032 
11033 /// NoteCandidates - When no template specialization match is found, prints
11034 /// diagnostic messages containing the non-matching specializations that form
11035 /// the candidate set.
11036 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11037 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11038 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11039   // Sort the candidates by position (assuming no candidate is a match).
11040   // Sorting directly would be prohibitive, so we make a set of pointers
11041   // and sort those.
11042   SmallVector<TemplateSpecCandidate *, 32> Cands;
11043   Cands.reserve(size());
11044   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11045     if (Cand->Specialization)
11046       Cands.push_back(Cand);
11047     // Otherwise, this is a non-matching builtin candidate.  We do not,
11048     // in general, want to list every possible builtin candidate.
11049   }
11050 
11051   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11052 
11053   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11054   // for generalization purposes (?).
11055   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11056 
11057   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11058   unsigned CandsShown = 0;
11059   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11060     TemplateSpecCandidate *Cand = *I;
11061 
11062     // Set an arbitrary limit on the number of candidates we'll spam
11063     // the user with.  FIXME: This limit should depend on details of the
11064     // candidate list.
11065     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11066       break;
11067     ++CandsShown;
11068 
11069     assert(Cand->Specialization &&
11070            "Non-matching built-in candidates are not added to Cands.");
11071     Cand->NoteDeductionFailure(S, ForTakingAddress);
11072   }
11073 
11074   if (I != E)
11075     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11076 }
11077 
11078 // [PossiblyAFunctionType]  -->   [Return]
11079 // NonFunctionType --> NonFunctionType
11080 // R (A) --> R(A)
11081 // R (*)(A) --> R (A)
11082 // R (&)(A) --> R (A)
11083 // R (S::*)(A) --> R (A)
11084 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11085   QualType Ret = PossiblyAFunctionType;
11086   if (const PointerType *ToTypePtr =
11087     PossiblyAFunctionType->getAs<PointerType>())
11088     Ret = ToTypePtr->getPointeeType();
11089   else if (const ReferenceType *ToTypeRef =
11090     PossiblyAFunctionType->getAs<ReferenceType>())
11091     Ret = ToTypeRef->getPointeeType();
11092   else if (const MemberPointerType *MemTypePtr =
11093     PossiblyAFunctionType->getAs<MemberPointerType>())
11094     Ret = MemTypePtr->getPointeeType();
11095   Ret =
11096     Context.getCanonicalType(Ret).getUnqualifiedType();
11097   return Ret;
11098 }
11099 
11100 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11101                                  bool Complain = true) {
11102   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11103       S.DeduceReturnType(FD, Loc, Complain))
11104     return true;
11105 
11106   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11107   if (S.getLangOpts().CPlusPlus17 &&
11108       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11109       !S.ResolveExceptionSpec(Loc, FPT))
11110     return true;
11111 
11112   return false;
11113 }
11114 
11115 namespace {
11116 // A helper class to help with address of function resolution
11117 // - allows us to avoid passing around all those ugly parameters
11118 class AddressOfFunctionResolver {
11119   Sema& S;
11120   Expr* SourceExpr;
11121   const QualType& TargetType;
11122   QualType TargetFunctionType; // Extracted function type from target type
11123 
11124   bool Complain;
11125   //DeclAccessPair& ResultFunctionAccessPair;
11126   ASTContext& Context;
11127 
11128   bool TargetTypeIsNonStaticMemberFunction;
11129   bool FoundNonTemplateFunction;
11130   bool StaticMemberFunctionFromBoundPointer;
11131   bool HasComplained;
11132 
11133   OverloadExpr::FindResult OvlExprInfo;
11134   OverloadExpr *OvlExpr;
11135   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11136   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11137   TemplateSpecCandidateSet FailedCandidates;
11138 
11139 public:
11140   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11141                             const QualType &TargetType, bool Complain)
11142       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11143         Complain(Complain), Context(S.getASTContext()),
11144         TargetTypeIsNonStaticMemberFunction(
11145             !!TargetType->getAs<MemberPointerType>()),
11146         FoundNonTemplateFunction(false),
11147         StaticMemberFunctionFromBoundPointer(false),
11148         HasComplained(false),
11149         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11150         OvlExpr(OvlExprInfo.Expression),
11151         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11152     ExtractUnqualifiedFunctionTypeFromTargetType();
11153 
11154     if (TargetFunctionType->isFunctionType()) {
11155       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11156         if (!UME->isImplicitAccess() &&
11157             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11158           StaticMemberFunctionFromBoundPointer = true;
11159     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11160       DeclAccessPair dap;
11161       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11162               OvlExpr, false, &dap)) {
11163         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11164           if (!Method->isStatic()) {
11165             // If the target type is a non-function type and the function found
11166             // is a non-static member function, pretend as if that was the
11167             // target, it's the only possible type to end up with.
11168             TargetTypeIsNonStaticMemberFunction = true;
11169 
11170             // And skip adding the function if its not in the proper form.
11171             // We'll diagnose this due to an empty set of functions.
11172             if (!OvlExprInfo.HasFormOfMemberPointer)
11173               return;
11174           }
11175 
11176         Matches.push_back(std::make_pair(dap, Fn));
11177       }
11178       return;
11179     }
11180 
11181     if (OvlExpr->hasExplicitTemplateArgs())
11182       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11183 
11184     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11185       // C++ [over.over]p4:
11186       //   If more than one function is selected, [...]
11187       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11188         if (FoundNonTemplateFunction)
11189           EliminateAllTemplateMatches();
11190         else
11191           EliminateAllExceptMostSpecializedTemplate();
11192       }
11193     }
11194 
11195     if (S.getLangOpts().CUDA && Matches.size() > 1)
11196       EliminateSuboptimalCudaMatches();
11197   }
11198 
11199   bool hasComplained() const { return HasComplained; }
11200 
11201 private:
11202   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11203     QualType Discard;
11204     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11205            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11206   }
11207 
11208   /// \return true if A is considered a better overload candidate for the
11209   /// desired type than B.
11210   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11211     // If A doesn't have exactly the correct type, we don't want to classify it
11212     // as "better" than anything else. This way, the user is required to
11213     // disambiguate for us if there are multiple candidates and no exact match.
11214     return candidateHasExactlyCorrectType(A) &&
11215            (!candidateHasExactlyCorrectType(B) ||
11216             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11217   }
11218 
11219   /// \return true if we were able to eliminate all but one overload candidate,
11220   /// false otherwise.
11221   bool eliminiateSuboptimalOverloadCandidates() {
11222     // Same algorithm as overload resolution -- one pass to pick the "best",
11223     // another pass to be sure that nothing is better than the best.
11224     auto Best = Matches.begin();
11225     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11226       if (isBetterCandidate(I->second, Best->second))
11227         Best = I;
11228 
11229     const FunctionDecl *BestFn = Best->second;
11230     auto IsBestOrInferiorToBest = [this, BestFn](
11231         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11232       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11233     };
11234 
11235     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11236     // option, so we can potentially give the user a better error
11237     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11238       return false;
11239     Matches[0] = *Best;
11240     Matches.resize(1);
11241     return true;
11242   }
11243 
11244   bool isTargetTypeAFunction() const {
11245     return TargetFunctionType->isFunctionType();
11246   }
11247 
11248   // [ToType]     [Return]
11249 
11250   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11251   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11252   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11253   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11254     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11255   }
11256 
11257   // return true if any matching specializations were found
11258   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11259                                    const DeclAccessPair& CurAccessFunPair) {
11260     if (CXXMethodDecl *Method
11261               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11262       // Skip non-static function templates when converting to pointer, and
11263       // static when converting to member pointer.
11264       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11265         return false;
11266     }
11267     else if (TargetTypeIsNonStaticMemberFunction)
11268       return false;
11269 
11270     // C++ [over.over]p2:
11271     //   If the name is a function template, template argument deduction is
11272     //   done (14.8.2.2), and if the argument deduction succeeds, the
11273     //   resulting template argument list is used to generate a single
11274     //   function template specialization, which is added to the set of
11275     //   overloaded functions considered.
11276     FunctionDecl *Specialization = nullptr;
11277     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11278     if (Sema::TemplateDeductionResult Result
11279           = S.DeduceTemplateArguments(FunctionTemplate,
11280                                       &OvlExplicitTemplateArgs,
11281                                       TargetFunctionType, Specialization,
11282                                       Info, /*IsAddressOfFunction*/true)) {
11283       // Make a note of the failed deduction for diagnostics.
11284       FailedCandidates.addCandidate()
11285           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11286                MakeDeductionFailureInfo(Context, Result, Info));
11287       return false;
11288     }
11289 
11290     // Template argument deduction ensures that we have an exact match or
11291     // compatible pointer-to-function arguments that would be adjusted by ICS.
11292     // This function template specicalization works.
11293     assert(S.isSameOrCompatibleFunctionType(
11294               Context.getCanonicalType(Specialization->getType()),
11295               Context.getCanonicalType(TargetFunctionType)));
11296 
11297     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11298       return false;
11299 
11300     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11301     return true;
11302   }
11303 
11304   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11305                                       const DeclAccessPair& CurAccessFunPair) {
11306     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11307       // Skip non-static functions when converting to pointer, and static
11308       // when converting to member pointer.
11309       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11310         return false;
11311     }
11312     else if (TargetTypeIsNonStaticMemberFunction)
11313       return false;
11314 
11315     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11316       if (S.getLangOpts().CUDA)
11317         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11318           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11319             return false;
11320       if (FunDecl->isMultiVersion()) {
11321         const auto *TA = FunDecl->getAttr<TargetAttr>();
11322         if (TA && !TA->isDefaultVersion())
11323           return false;
11324       }
11325 
11326       // If any candidate has a placeholder return type, trigger its deduction
11327       // now.
11328       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11329                                Complain)) {
11330         HasComplained |= Complain;
11331         return false;
11332       }
11333 
11334       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11335         return false;
11336 
11337       // If we're in C, we need to support types that aren't exactly identical.
11338       if (!S.getLangOpts().CPlusPlus ||
11339           candidateHasExactlyCorrectType(FunDecl)) {
11340         Matches.push_back(std::make_pair(
11341             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11342         FoundNonTemplateFunction = true;
11343         return true;
11344       }
11345     }
11346 
11347     return false;
11348   }
11349 
11350   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11351     bool Ret = false;
11352 
11353     // If the overload expression doesn't have the form of a pointer to
11354     // member, don't try to convert it to a pointer-to-member type.
11355     if (IsInvalidFormOfPointerToMemberFunction())
11356       return false;
11357 
11358     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11359                                E = OvlExpr->decls_end();
11360          I != E; ++I) {
11361       // Look through any using declarations to find the underlying function.
11362       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11363 
11364       // C++ [over.over]p3:
11365       //   Non-member functions and static member functions match
11366       //   targets of type "pointer-to-function" or "reference-to-function."
11367       //   Nonstatic member functions match targets of
11368       //   type "pointer-to-member-function."
11369       // Note that according to DR 247, the containing class does not matter.
11370       if (FunctionTemplateDecl *FunctionTemplate
11371                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11372         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11373           Ret = true;
11374       }
11375       // If we have explicit template arguments supplied, skip non-templates.
11376       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11377                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11378         Ret = true;
11379     }
11380     assert(Ret || Matches.empty());
11381     return Ret;
11382   }
11383 
11384   void EliminateAllExceptMostSpecializedTemplate() {
11385     //   [...] and any given function template specialization F1 is
11386     //   eliminated if the set contains a second function template
11387     //   specialization whose function template is more specialized
11388     //   than the function template of F1 according to the partial
11389     //   ordering rules of 14.5.5.2.
11390 
11391     // The algorithm specified above is quadratic. We instead use a
11392     // two-pass algorithm (similar to the one used to identify the
11393     // best viable function in an overload set) that identifies the
11394     // best function template (if it exists).
11395 
11396     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11397     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11398       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11399 
11400     // TODO: It looks like FailedCandidates does not serve much purpose
11401     // here, since the no_viable diagnostic has index 0.
11402     UnresolvedSetIterator Result = S.getMostSpecialized(
11403         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11404         SourceExpr->getBeginLoc(), S.PDiag(),
11405         S.PDiag(diag::err_addr_ovl_ambiguous)
11406             << Matches[0].second->getDeclName(),
11407         S.PDiag(diag::note_ovl_candidate)
11408             << (unsigned)oc_function << (unsigned)ocs_described_template,
11409         Complain, TargetFunctionType);
11410 
11411     if (Result != MatchesCopy.end()) {
11412       // Make it the first and only element
11413       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11414       Matches[0].second = cast<FunctionDecl>(*Result);
11415       Matches.resize(1);
11416     } else
11417       HasComplained |= Complain;
11418   }
11419 
11420   void EliminateAllTemplateMatches() {
11421     //   [...] any function template specializations in the set are
11422     //   eliminated if the set also contains a non-template function, [...]
11423     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11424       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11425         ++I;
11426       else {
11427         Matches[I] = Matches[--N];
11428         Matches.resize(N);
11429       }
11430     }
11431   }
11432 
11433   void EliminateSuboptimalCudaMatches() {
11434     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11435   }
11436 
11437 public:
11438   void ComplainNoMatchesFound() const {
11439     assert(Matches.empty());
11440     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11441         << OvlExpr->getName() << TargetFunctionType
11442         << OvlExpr->getSourceRange();
11443     if (FailedCandidates.empty())
11444       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11445                                   /*TakingAddress=*/true);
11446     else {
11447       // We have some deduction failure messages. Use them to diagnose
11448       // the function templates, and diagnose the non-template candidates
11449       // normally.
11450       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11451                                  IEnd = OvlExpr->decls_end();
11452            I != IEnd; ++I)
11453         if (FunctionDecl *Fun =
11454                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11455           if (!functionHasPassObjectSizeParams(Fun))
11456             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11457                                     /*TakingAddress=*/true);
11458       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11459     }
11460   }
11461 
11462   bool IsInvalidFormOfPointerToMemberFunction() const {
11463     return TargetTypeIsNonStaticMemberFunction &&
11464       !OvlExprInfo.HasFormOfMemberPointer;
11465   }
11466 
11467   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11468       // TODO: Should we condition this on whether any functions might
11469       // have matched, or is it more appropriate to do that in callers?
11470       // TODO: a fixit wouldn't hurt.
11471       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11472         << TargetType << OvlExpr->getSourceRange();
11473   }
11474 
11475   bool IsStaticMemberFunctionFromBoundPointer() const {
11476     return StaticMemberFunctionFromBoundPointer;
11477   }
11478 
11479   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11480     S.Diag(OvlExpr->getBeginLoc(),
11481            diag::err_invalid_form_pointer_member_function)
11482         << OvlExpr->getSourceRange();
11483   }
11484 
11485   void ComplainOfInvalidConversion() const {
11486     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11487         << OvlExpr->getName() << TargetType;
11488   }
11489 
11490   void ComplainMultipleMatchesFound() const {
11491     assert(Matches.size() > 1);
11492     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11493         << OvlExpr->getName() << OvlExpr->getSourceRange();
11494     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11495                                 /*TakingAddress=*/true);
11496   }
11497 
11498   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11499 
11500   int getNumMatches() const { return Matches.size(); }
11501 
11502   FunctionDecl* getMatchingFunctionDecl() const {
11503     if (Matches.size() != 1) return nullptr;
11504     return Matches[0].second;
11505   }
11506 
11507   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11508     if (Matches.size() != 1) return nullptr;
11509     return &Matches[0].first;
11510   }
11511 };
11512 }
11513 
11514 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11515 /// an overloaded function (C++ [over.over]), where @p From is an
11516 /// expression with overloaded function type and @p ToType is the type
11517 /// we're trying to resolve to. For example:
11518 ///
11519 /// @code
11520 /// int f(double);
11521 /// int f(int);
11522 ///
11523 /// int (*pfd)(double) = f; // selects f(double)
11524 /// @endcode
11525 ///
11526 /// This routine returns the resulting FunctionDecl if it could be
11527 /// resolved, and NULL otherwise. When @p Complain is true, this
11528 /// routine will emit diagnostics if there is an error.
11529 FunctionDecl *
11530 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11531                                          QualType TargetType,
11532                                          bool Complain,
11533                                          DeclAccessPair &FoundResult,
11534                                          bool *pHadMultipleCandidates) {
11535   assert(AddressOfExpr->getType() == Context.OverloadTy);
11536 
11537   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11538                                      Complain);
11539   int NumMatches = Resolver.getNumMatches();
11540   FunctionDecl *Fn = nullptr;
11541   bool ShouldComplain = Complain && !Resolver.hasComplained();
11542   if (NumMatches == 0 && ShouldComplain) {
11543     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11544       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11545     else
11546       Resolver.ComplainNoMatchesFound();
11547   }
11548   else if (NumMatches > 1 && ShouldComplain)
11549     Resolver.ComplainMultipleMatchesFound();
11550   else if (NumMatches == 1) {
11551     Fn = Resolver.getMatchingFunctionDecl();
11552     assert(Fn);
11553     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11554       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11555     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11556     if (Complain) {
11557       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11558         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11559       else
11560         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11561     }
11562   }
11563 
11564   if (pHadMultipleCandidates)
11565     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11566   return Fn;
11567 }
11568 
11569 /// Given an expression that refers to an overloaded function, try to
11570 /// resolve that function to a single function that can have its address taken.
11571 /// This will modify `Pair` iff it returns non-null.
11572 ///
11573 /// This routine can only realistically succeed if all but one candidates in the
11574 /// overload set for SrcExpr cannot have their addresses taken.
11575 FunctionDecl *
11576 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11577                                                   DeclAccessPair &Pair) {
11578   OverloadExpr::FindResult R = OverloadExpr::find(E);
11579   OverloadExpr *Ovl = R.Expression;
11580   FunctionDecl *Result = nullptr;
11581   DeclAccessPair DAP;
11582   // Don't use the AddressOfResolver because we're specifically looking for
11583   // cases where we have one overload candidate that lacks
11584   // enable_if/pass_object_size/...
11585   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11586     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11587     if (!FD)
11588       return nullptr;
11589 
11590     if (!checkAddressOfFunctionIsAvailable(FD))
11591       continue;
11592 
11593     // We have more than one result; quit.
11594     if (Result)
11595       return nullptr;
11596     DAP = I.getPair();
11597     Result = FD;
11598   }
11599 
11600   if (Result)
11601     Pair = DAP;
11602   return Result;
11603 }
11604 
11605 /// Given an overloaded function, tries to turn it into a non-overloaded
11606 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11607 /// will perform access checks, diagnose the use of the resultant decl, and, if
11608 /// requested, potentially perform a function-to-pointer decay.
11609 ///
11610 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11611 /// Otherwise, returns true. This may emit diagnostics and return true.
11612 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11613     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11614   Expr *E = SrcExpr.get();
11615   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11616 
11617   DeclAccessPair DAP;
11618   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11619   if (!Found || Found->isCPUDispatchMultiVersion() ||
11620       Found->isCPUSpecificMultiVersion())
11621     return false;
11622 
11623   // Emitting multiple diagnostics for a function that is both inaccessible and
11624   // unavailable is consistent with our behavior elsewhere. So, always check
11625   // for both.
11626   DiagnoseUseOfDecl(Found, E->getExprLoc());
11627   CheckAddressOfMemberAccess(E, DAP);
11628   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11629   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11630     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11631   else
11632     SrcExpr = Fixed;
11633   return true;
11634 }
11635 
11636 /// Given an expression that refers to an overloaded function, try to
11637 /// resolve that overloaded function expression down to a single function.
11638 ///
11639 /// This routine can only resolve template-ids that refer to a single function
11640 /// template, where that template-id refers to a single template whose template
11641 /// arguments are either provided by the template-id or have defaults,
11642 /// as described in C++0x [temp.arg.explicit]p3.
11643 ///
11644 /// If no template-ids are found, no diagnostics are emitted and NULL is
11645 /// returned.
11646 FunctionDecl *
11647 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11648                                                   bool Complain,
11649                                                   DeclAccessPair *FoundResult) {
11650   // C++ [over.over]p1:
11651   //   [...] [Note: any redundant set of parentheses surrounding the
11652   //   overloaded function name is ignored (5.1). ]
11653   // C++ [over.over]p1:
11654   //   [...] The overloaded function name can be preceded by the &
11655   //   operator.
11656 
11657   // If we didn't actually find any template-ids, we're done.
11658   if (!ovl->hasExplicitTemplateArgs())
11659     return nullptr;
11660 
11661   TemplateArgumentListInfo ExplicitTemplateArgs;
11662   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11663   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11664 
11665   // Look through all of the overloaded functions, searching for one
11666   // whose type matches exactly.
11667   FunctionDecl *Matched = nullptr;
11668   for (UnresolvedSetIterator I = ovl->decls_begin(),
11669          E = ovl->decls_end(); I != E; ++I) {
11670     // C++0x [temp.arg.explicit]p3:
11671     //   [...] In contexts where deduction is done and fails, or in contexts
11672     //   where deduction is not done, if a template argument list is
11673     //   specified and it, along with any default template arguments,
11674     //   identifies a single function template specialization, then the
11675     //   template-id is an lvalue for the function template specialization.
11676     FunctionTemplateDecl *FunctionTemplate
11677       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11678 
11679     // C++ [over.over]p2:
11680     //   If the name is a function template, template argument deduction is
11681     //   done (14.8.2.2), and if the argument deduction succeeds, the
11682     //   resulting template argument list is used to generate a single
11683     //   function template specialization, which is added to the set of
11684     //   overloaded functions considered.
11685     FunctionDecl *Specialization = nullptr;
11686     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11687     if (TemplateDeductionResult Result
11688           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11689                                     Specialization, Info,
11690                                     /*IsAddressOfFunction*/true)) {
11691       // Make a note of the failed deduction for diagnostics.
11692       // TODO: Actually use the failed-deduction info?
11693       FailedCandidates.addCandidate()
11694           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11695                MakeDeductionFailureInfo(Context, Result, Info));
11696       continue;
11697     }
11698 
11699     assert(Specialization && "no specialization and no error?");
11700 
11701     // Multiple matches; we can't resolve to a single declaration.
11702     if (Matched) {
11703       if (Complain) {
11704         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11705           << ovl->getName();
11706         NoteAllOverloadCandidates(ovl);
11707       }
11708       return nullptr;
11709     }
11710 
11711     Matched = Specialization;
11712     if (FoundResult) *FoundResult = I.getPair();
11713   }
11714 
11715   if (Matched &&
11716       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11717     return nullptr;
11718 
11719   return Matched;
11720 }
11721 
11722 // Resolve and fix an overloaded expression that can be resolved
11723 // because it identifies a single function template specialization.
11724 //
11725 // Last three arguments should only be supplied if Complain = true
11726 //
11727 // Return true if it was logically possible to so resolve the
11728 // expression, regardless of whether or not it succeeded.  Always
11729 // returns true if 'complain' is set.
11730 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11731                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11732                       bool complain, SourceRange OpRangeForComplaining,
11733                                            QualType DestTypeForComplaining,
11734                                             unsigned DiagIDForComplaining) {
11735   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11736 
11737   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11738 
11739   DeclAccessPair found;
11740   ExprResult SingleFunctionExpression;
11741   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11742                            ovl.Expression, /*complain*/ false, &found)) {
11743     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11744       SrcExpr = ExprError();
11745       return true;
11746     }
11747 
11748     // It is only correct to resolve to an instance method if we're
11749     // resolving a form that's permitted to be a pointer to member.
11750     // Otherwise we'll end up making a bound member expression, which
11751     // is illegal in all the contexts we resolve like this.
11752     if (!ovl.HasFormOfMemberPointer &&
11753         isa<CXXMethodDecl>(fn) &&
11754         cast<CXXMethodDecl>(fn)->isInstance()) {
11755       if (!complain) return false;
11756 
11757       Diag(ovl.Expression->getExprLoc(),
11758            diag::err_bound_member_function)
11759         << 0 << ovl.Expression->getSourceRange();
11760 
11761       // TODO: I believe we only end up here if there's a mix of
11762       // static and non-static candidates (otherwise the expression
11763       // would have 'bound member' type, not 'overload' type).
11764       // Ideally we would note which candidate was chosen and why
11765       // the static candidates were rejected.
11766       SrcExpr = ExprError();
11767       return true;
11768     }
11769 
11770     // Fix the expression to refer to 'fn'.
11771     SingleFunctionExpression =
11772         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11773 
11774     // If desired, do function-to-pointer decay.
11775     if (doFunctionPointerConverion) {
11776       SingleFunctionExpression =
11777         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11778       if (SingleFunctionExpression.isInvalid()) {
11779         SrcExpr = ExprError();
11780         return true;
11781       }
11782     }
11783   }
11784 
11785   if (!SingleFunctionExpression.isUsable()) {
11786     if (complain) {
11787       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11788         << ovl.Expression->getName()
11789         << DestTypeForComplaining
11790         << OpRangeForComplaining
11791         << ovl.Expression->getQualifierLoc().getSourceRange();
11792       NoteAllOverloadCandidates(SrcExpr.get());
11793 
11794       SrcExpr = ExprError();
11795       return true;
11796     }
11797 
11798     return false;
11799   }
11800 
11801   SrcExpr = SingleFunctionExpression;
11802   return true;
11803 }
11804 
11805 /// Add a single candidate to the overload set.
11806 static void AddOverloadedCallCandidate(Sema &S,
11807                                        DeclAccessPair FoundDecl,
11808                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11809                                        ArrayRef<Expr *> Args,
11810                                        OverloadCandidateSet &CandidateSet,
11811                                        bool PartialOverloading,
11812                                        bool KnownValid) {
11813   NamedDecl *Callee = FoundDecl.getDecl();
11814   if (isa<UsingShadowDecl>(Callee))
11815     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11816 
11817   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11818     if (ExplicitTemplateArgs) {
11819       assert(!KnownValid && "Explicit template arguments?");
11820       return;
11821     }
11822     // Prevent ill-formed function decls to be added as overload candidates.
11823     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11824       return;
11825 
11826     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11827                            /*SuppressUserConversions=*/false,
11828                            PartialOverloading);
11829     return;
11830   }
11831 
11832   if (FunctionTemplateDecl *FuncTemplate
11833       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11834     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11835                                    ExplicitTemplateArgs, Args, CandidateSet,
11836                                    /*SuppressUserConversions=*/false,
11837                                    PartialOverloading);
11838     return;
11839   }
11840 
11841   assert(!KnownValid && "unhandled case in overloaded call candidate");
11842 }
11843 
11844 /// Add the overload candidates named by callee and/or found by argument
11845 /// dependent lookup to the given overload set.
11846 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11847                                        ArrayRef<Expr *> Args,
11848                                        OverloadCandidateSet &CandidateSet,
11849                                        bool PartialOverloading) {
11850 
11851 #ifndef NDEBUG
11852   // Verify that ArgumentDependentLookup is consistent with the rules
11853   // in C++0x [basic.lookup.argdep]p3:
11854   //
11855   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11856   //   and let Y be the lookup set produced by argument dependent
11857   //   lookup (defined as follows). If X contains
11858   //
11859   //     -- a declaration of a class member, or
11860   //
11861   //     -- a block-scope function declaration that is not a
11862   //        using-declaration, or
11863   //
11864   //     -- a declaration that is neither a function or a function
11865   //        template
11866   //
11867   //   then Y is empty.
11868 
11869   if (ULE->requiresADL()) {
11870     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11871            E = ULE->decls_end(); I != E; ++I) {
11872       assert(!(*I)->getDeclContext()->isRecord());
11873       assert(isa<UsingShadowDecl>(*I) ||
11874              !(*I)->getDeclContext()->isFunctionOrMethod());
11875       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11876     }
11877   }
11878 #endif
11879 
11880   // It would be nice to avoid this copy.
11881   TemplateArgumentListInfo TABuffer;
11882   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11883   if (ULE->hasExplicitTemplateArgs()) {
11884     ULE->copyTemplateArgumentsInto(TABuffer);
11885     ExplicitTemplateArgs = &TABuffer;
11886   }
11887 
11888   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11889          E = ULE->decls_end(); I != E; ++I)
11890     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11891                                CandidateSet, PartialOverloading,
11892                                /*KnownValid*/ true);
11893 
11894   if (ULE->requiresADL())
11895     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11896                                          Args, ExplicitTemplateArgs,
11897                                          CandidateSet, PartialOverloading);
11898 }
11899 
11900 /// Determine whether a declaration with the specified name could be moved into
11901 /// a different namespace.
11902 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11903   switch (Name.getCXXOverloadedOperator()) {
11904   case OO_New: case OO_Array_New:
11905   case OO_Delete: case OO_Array_Delete:
11906     return false;
11907 
11908   default:
11909     return true;
11910   }
11911 }
11912 
11913 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11914 /// template, where the non-dependent name was declared after the template
11915 /// was defined. This is common in code written for a compilers which do not
11916 /// correctly implement two-stage name lookup.
11917 ///
11918 /// Returns true if a viable candidate was found and a diagnostic was issued.
11919 static bool
11920 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11921                        const CXXScopeSpec &SS, LookupResult &R,
11922                        OverloadCandidateSet::CandidateSetKind CSK,
11923                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11924                        ArrayRef<Expr *> Args,
11925                        bool *DoDiagnoseEmptyLookup = nullptr) {
11926   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11927     return false;
11928 
11929   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11930     if (DC->isTransparentContext())
11931       continue;
11932 
11933     SemaRef.LookupQualifiedName(R, DC);
11934 
11935     if (!R.empty()) {
11936       R.suppressDiagnostics();
11937 
11938       if (isa<CXXRecordDecl>(DC)) {
11939         // Don't diagnose names we find in classes; we get much better
11940         // diagnostics for these from DiagnoseEmptyLookup.
11941         R.clear();
11942         if (DoDiagnoseEmptyLookup)
11943           *DoDiagnoseEmptyLookup = true;
11944         return false;
11945       }
11946 
11947       OverloadCandidateSet Candidates(FnLoc, CSK);
11948       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11949         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11950                                    ExplicitTemplateArgs, Args,
11951                                    Candidates, false, /*KnownValid*/ false);
11952 
11953       OverloadCandidateSet::iterator Best;
11954       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11955         // No viable functions. Don't bother the user with notes for functions
11956         // which don't work and shouldn't be found anyway.
11957         R.clear();
11958         return false;
11959       }
11960 
11961       // Find the namespaces where ADL would have looked, and suggest
11962       // declaring the function there instead.
11963       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11964       Sema::AssociatedClassSet AssociatedClasses;
11965       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11966                                                  AssociatedNamespaces,
11967                                                  AssociatedClasses);
11968       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11969       if (canBeDeclaredInNamespace(R.getLookupName())) {
11970         DeclContext *Std = SemaRef.getStdNamespace();
11971         for (Sema::AssociatedNamespaceSet::iterator
11972                it = AssociatedNamespaces.begin(),
11973                end = AssociatedNamespaces.end(); it != end; ++it) {
11974           // Never suggest declaring a function within namespace 'std'.
11975           if (Std && Std->Encloses(*it))
11976             continue;
11977 
11978           // Never suggest declaring a function within a namespace with a
11979           // reserved name, like __gnu_cxx.
11980           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11981           if (NS &&
11982               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11983             continue;
11984 
11985           SuggestedNamespaces.insert(*it);
11986         }
11987       }
11988 
11989       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11990         << R.getLookupName();
11991       if (SuggestedNamespaces.empty()) {
11992         SemaRef.Diag(Best->Function->getLocation(),
11993                      diag::note_not_found_by_two_phase_lookup)
11994           << R.getLookupName() << 0;
11995       } else if (SuggestedNamespaces.size() == 1) {
11996         SemaRef.Diag(Best->Function->getLocation(),
11997                      diag::note_not_found_by_two_phase_lookup)
11998           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11999       } else {
12000         // FIXME: It would be useful to list the associated namespaces here,
12001         // but the diagnostics infrastructure doesn't provide a way to produce
12002         // a localized representation of a list of items.
12003         SemaRef.Diag(Best->Function->getLocation(),
12004                      diag::note_not_found_by_two_phase_lookup)
12005           << R.getLookupName() << 2;
12006       }
12007 
12008       // Try to recover by calling this function.
12009       return true;
12010     }
12011 
12012     R.clear();
12013   }
12014 
12015   return false;
12016 }
12017 
12018 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12019 /// template, where the non-dependent operator was declared after the template
12020 /// was defined.
12021 ///
12022 /// Returns true if a viable candidate was found and a diagnostic was issued.
12023 static bool
12024 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12025                                SourceLocation OpLoc,
12026                                ArrayRef<Expr *> Args) {
12027   DeclarationName OpName =
12028     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12029   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12030   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12031                                 OverloadCandidateSet::CSK_Operator,
12032                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12033 }
12034 
12035 namespace {
12036 class BuildRecoveryCallExprRAII {
12037   Sema &SemaRef;
12038 public:
12039   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12040     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12041     SemaRef.IsBuildingRecoveryCallExpr = true;
12042   }
12043 
12044   ~BuildRecoveryCallExprRAII() {
12045     SemaRef.IsBuildingRecoveryCallExpr = false;
12046   }
12047 };
12048 
12049 }
12050 
12051 /// Attempts to recover from a call where no functions were found.
12052 ///
12053 /// Returns true if new candidates were found.
12054 static ExprResult
12055 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12056                       UnresolvedLookupExpr *ULE,
12057                       SourceLocation LParenLoc,
12058                       MutableArrayRef<Expr *> Args,
12059                       SourceLocation RParenLoc,
12060                       bool EmptyLookup, bool AllowTypoCorrection) {
12061   // Do not try to recover if it is already building a recovery call.
12062   // This stops infinite loops for template instantiations like
12063   //
12064   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12065   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12066   //
12067   if (SemaRef.IsBuildingRecoveryCallExpr)
12068     return ExprError();
12069   BuildRecoveryCallExprRAII RCE(SemaRef);
12070 
12071   CXXScopeSpec SS;
12072   SS.Adopt(ULE->getQualifierLoc());
12073   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12074 
12075   TemplateArgumentListInfo TABuffer;
12076   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12077   if (ULE->hasExplicitTemplateArgs()) {
12078     ULE->copyTemplateArgumentsInto(TABuffer);
12079     ExplicitTemplateArgs = &TABuffer;
12080   }
12081 
12082   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12083                  Sema::LookupOrdinaryName);
12084   bool DoDiagnoseEmptyLookup = EmptyLookup;
12085   if (!DiagnoseTwoPhaseLookup(
12086           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12087           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12088     NoTypoCorrectionCCC NoTypoValidator{};
12089     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12090                                                 ExplicitTemplateArgs != nullptr,
12091                                                 dyn_cast<MemberExpr>(Fn));
12092     CorrectionCandidateCallback &Validator =
12093         AllowTypoCorrection
12094             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12095             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12096     if (!DoDiagnoseEmptyLookup ||
12097         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12098                                     Args))
12099       return ExprError();
12100   }
12101 
12102   assert(!R.empty() && "lookup results empty despite recovery");
12103 
12104   // If recovery created an ambiguity, just bail out.
12105   if (R.isAmbiguous()) {
12106     R.suppressDiagnostics();
12107     return ExprError();
12108   }
12109 
12110   // Build an implicit member call if appropriate.  Just drop the
12111   // casts and such from the call, we don't really care.
12112   ExprResult NewFn = ExprError();
12113   if ((*R.begin())->isCXXClassMember())
12114     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12115                                                     ExplicitTemplateArgs, S);
12116   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12117     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12118                                         ExplicitTemplateArgs);
12119   else
12120     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12121 
12122   if (NewFn.isInvalid())
12123     return ExprError();
12124 
12125   // This shouldn't cause an infinite loop because we're giving it
12126   // an expression with viable lookup results, which should never
12127   // end up here.
12128   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12129                                MultiExprArg(Args.data(), Args.size()),
12130                                RParenLoc);
12131 }
12132 
12133 /// Constructs and populates an OverloadedCandidateSet from
12134 /// the given function.
12135 /// \returns true when an the ExprResult output parameter has been set.
12136 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12137                                   UnresolvedLookupExpr *ULE,
12138                                   MultiExprArg Args,
12139                                   SourceLocation RParenLoc,
12140                                   OverloadCandidateSet *CandidateSet,
12141                                   ExprResult *Result) {
12142 #ifndef NDEBUG
12143   if (ULE->requiresADL()) {
12144     // To do ADL, we must have found an unqualified name.
12145     assert(!ULE->getQualifier() && "qualified name with ADL");
12146 
12147     // We don't perform ADL for implicit declarations of builtins.
12148     // Verify that this was correctly set up.
12149     FunctionDecl *F;
12150     if (ULE->decls_begin() != ULE->decls_end() &&
12151         ULE->decls_begin() + 1 == ULE->decls_end() &&
12152         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12153         F->getBuiltinID() && F->isImplicit())
12154       llvm_unreachable("performing ADL for builtin");
12155 
12156     // We don't perform ADL in C.
12157     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12158   }
12159 #endif
12160 
12161   UnbridgedCastsSet UnbridgedCasts;
12162   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12163     *Result = ExprError();
12164     return true;
12165   }
12166 
12167   // Add the functions denoted by the callee to the set of candidate
12168   // functions, including those from argument-dependent lookup.
12169   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12170 
12171   if (getLangOpts().MSVCCompat &&
12172       CurContext->isDependentContext() && !isSFINAEContext() &&
12173       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12174 
12175     OverloadCandidateSet::iterator Best;
12176     if (CandidateSet->empty() ||
12177         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12178             OR_No_Viable_Function) {
12179       // In Microsoft mode, if we are inside a template class member function
12180       // then create a type dependent CallExpr. The goal is to postpone name
12181       // lookup to instantiation time to be able to search into type dependent
12182       // base classes.
12183       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12184                                       VK_RValue, RParenLoc);
12185       CE->setTypeDependent(true);
12186       CE->setValueDependent(true);
12187       CE->setInstantiationDependent(true);
12188       *Result = CE;
12189       return true;
12190     }
12191   }
12192 
12193   if (CandidateSet->empty())
12194     return false;
12195 
12196   UnbridgedCasts.restore();
12197   return false;
12198 }
12199 
12200 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12201 /// the completed call expression. If overload resolution fails, emits
12202 /// diagnostics and returns ExprError()
12203 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12204                                            UnresolvedLookupExpr *ULE,
12205                                            SourceLocation LParenLoc,
12206                                            MultiExprArg Args,
12207                                            SourceLocation RParenLoc,
12208                                            Expr *ExecConfig,
12209                                            OverloadCandidateSet *CandidateSet,
12210                                            OverloadCandidateSet::iterator *Best,
12211                                            OverloadingResult OverloadResult,
12212                                            bool AllowTypoCorrection) {
12213   if (CandidateSet->empty())
12214     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12215                                  RParenLoc, /*EmptyLookup=*/true,
12216                                  AllowTypoCorrection);
12217 
12218   switch (OverloadResult) {
12219   case OR_Success: {
12220     FunctionDecl *FDecl = (*Best)->Function;
12221     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12222     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12223       return ExprError();
12224     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12225     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12226                                          ExecConfig, /*IsExecConfig=*/false,
12227                                          (*Best)->IsADLCandidate);
12228   }
12229 
12230   case OR_No_Viable_Function: {
12231     // Try to recover by looking for viable functions which the user might
12232     // have meant to call.
12233     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12234                                                 Args, RParenLoc,
12235                                                 /*EmptyLookup=*/false,
12236                                                 AllowTypoCorrection);
12237     if (!Recovery.isInvalid())
12238       return Recovery;
12239 
12240     // If the user passes in a function that we can't take the address of, we
12241     // generally end up emitting really bad error messages. Here, we attempt to
12242     // emit better ones.
12243     for (const Expr *Arg : Args) {
12244       if (!Arg->getType()->isFunctionType())
12245         continue;
12246       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12247         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12248         if (FD &&
12249             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12250                                                        Arg->getExprLoc()))
12251           return ExprError();
12252       }
12253     }
12254 
12255     CandidateSet->NoteCandidates(
12256         PartialDiagnosticAt(
12257             Fn->getBeginLoc(),
12258             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12259                 << ULE->getName() << Fn->getSourceRange()),
12260         SemaRef, OCD_AllCandidates, Args);
12261     break;
12262   }
12263 
12264   case OR_Ambiguous:
12265     CandidateSet->NoteCandidates(
12266         PartialDiagnosticAt(Fn->getBeginLoc(),
12267                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12268                                 << ULE->getName() << Fn->getSourceRange()),
12269         SemaRef, OCD_ViableCandidates, Args);
12270     break;
12271 
12272   case OR_Deleted: {
12273     CandidateSet->NoteCandidates(
12274         PartialDiagnosticAt(Fn->getBeginLoc(),
12275                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12276                                 << ULE->getName() << Fn->getSourceRange()),
12277         SemaRef, OCD_AllCandidates, Args);
12278 
12279     // We emitted an error for the unavailable/deleted function call but keep
12280     // the call in the AST.
12281     FunctionDecl *FDecl = (*Best)->Function;
12282     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12283     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12284                                          ExecConfig, /*IsExecConfig=*/false,
12285                                          (*Best)->IsADLCandidate);
12286   }
12287   }
12288 
12289   // Overload resolution failed.
12290   return ExprError();
12291 }
12292 
12293 static void markUnaddressableCandidatesUnviable(Sema &S,
12294                                                 OverloadCandidateSet &CS) {
12295   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12296     if (I->Viable &&
12297         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12298       I->Viable = false;
12299       I->FailureKind = ovl_fail_addr_not_available;
12300     }
12301   }
12302 }
12303 
12304 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12305 /// (which eventually refers to the declaration Func) and the call
12306 /// arguments Args/NumArgs, attempt to resolve the function call down
12307 /// to a specific function. If overload resolution succeeds, returns
12308 /// the call expression produced by overload resolution.
12309 /// Otherwise, emits diagnostics and returns ExprError.
12310 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12311                                          UnresolvedLookupExpr *ULE,
12312                                          SourceLocation LParenLoc,
12313                                          MultiExprArg Args,
12314                                          SourceLocation RParenLoc,
12315                                          Expr *ExecConfig,
12316                                          bool AllowTypoCorrection,
12317                                          bool CalleesAddressIsTaken) {
12318   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12319                                     OverloadCandidateSet::CSK_Normal);
12320   ExprResult result;
12321 
12322   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12323                              &result))
12324     return result;
12325 
12326   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12327   // functions that aren't addressible are considered unviable.
12328   if (CalleesAddressIsTaken)
12329     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12330 
12331   OverloadCandidateSet::iterator Best;
12332   OverloadingResult OverloadResult =
12333       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12334 
12335   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12336                                   ExecConfig, &CandidateSet, &Best,
12337                                   OverloadResult, AllowTypoCorrection);
12338 }
12339 
12340 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12341   return Functions.size() > 1 ||
12342     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12343 }
12344 
12345 /// Create a unary operation that may resolve to an overloaded
12346 /// operator.
12347 ///
12348 /// \param OpLoc The location of the operator itself (e.g., '*').
12349 ///
12350 /// \param Opc The UnaryOperatorKind that describes this operator.
12351 ///
12352 /// \param Fns The set of non-member functions that will be
12353 /// considered by overload resolution. The caller needs to build this
12354 /// set based on the context using, e.g.,
12355 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12356 /// set should not contain any member functions; those will be added
12357 /// by CreateOverloadedUnaryOp().
12358 ///
12359 /// \param Input The input argument.
12360 ExprResult
12361 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12362                               const UnresolvedSetImpl &Fns,
12363                               Expr *Input, bool PerformADL) {
12364   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12365   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12366   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12367   // TODO: provide better source location info.
12368   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12369 
12370   if (checkPlaceholderForOverload(*this, Input))
12371     return ExprError();
12372 
12373   Expr *Args[2] = { Input, nullptr };
12374   unsigned NumArgs = 1;
12375 
12376   // For post-increment and post-decrement, add the implicit '0' as
12377   // the second argument, so that we know this is a post-increment or
12378   // post-decrement.
12379   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12380     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12381     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12382                                      SourceLocation());
12383     NumArgs = 2;
12384   }
12385 
12386   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12387 
12388   if (Input->isTypeDependent()) {
12389     if (Fns.empty())
12390       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12391                                          VK_RValue, OK_Ordinary, OpLoc, false);
12392 
12393     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12394     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12395         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12396         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12397     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12398                                        Context.DependentTy, VK_RValue, OpLoc,
12399                                        FPOptions());
12400   }
12401 
12402   // Build an empty overload set.
12403   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12404 
12405   // Add the candidates from the given function set.
12406   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12407 
12408   // Add operator candidates that are member functions.
12409   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12410 
12411   // Add candidates from ADL.
12412   if (PerformADL) {
12413     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12414                                          /*ExplicitTemplateArgs*/nullptr,
12415                                          CandidateSet);
12416   }
12417 
12418   // Add builtin operator candidates.
12419   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12420 
12421   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12422 
12423   // Perform overload resolution.
12424   OverloadCandidateSet::iterator Best;
12425   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12426   case OR_Success: {
12427     // We found a built-in operator or an overloaded operator.
12428     FunctionDecl *FnDecl = Best->Function;
12429 
12430     if (FnDecl) {
12431       Expr *Base = nullptr;
12432       // We matched an overloaded operator. Build a call to that
12433       // operator.
12434 
12435       // Convert the arguments.
12436       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12437         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12438 
12439         ExprResult InputRes =
12440           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12441                                               Best->FoundDecl, Method);
12442         if (InputRes.isInvalid())
12443           return ExprError();
12444         Base = Input = InputRes.get();
12445       } else {
12446         // Convert the arguments.
12447         ExprResult InputInit
12448           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12449                                                       Context,
12450                                                       FnDecl->getParamDecl(0)),
12451                                       SourceLocation(),
12452                                       Input);
12453         if (InputInit.isInvalid())
12454           return ExprError();
12455         Input = InputInit.get();
12456       }
12457 
12458       // Build the actual expression node.
12459       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12460                                                 Base, HadMultipleCandidates,
12461                                                 OpLoc);
12462       if (FnExpr.isInvalid())
12463         return ExprError();
12464 
12465       // Determine the result type.
12466       QualType ResultTy = FnDecl->getReturnType();
12467       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12468       ResultTy = ResultTy.getNonLValueExprType(Context);
12469 
12470       Args[0] = Input;
12471       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12472           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12473           FPOptions(), Best->IsADLCandidate);
12474 
12475       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12476         return ExprError();
12477 
12478       if (CheckFunctionCall(FnDecl, TheCall,
12479                             FnDecl->getType()->castAs<FunctionProtoType>()))
12480         return ExprError();
12481 
12482       return MaybeBindToTemporary(TheCall);
12483     } else {
12484       // We matched a built-in operator. Convert the arguments, then
12485       // break out so that we will build the appropriate built-in
12486       // operator node.
12487       ExprResult InputRes = PerformImplicitConversion(
12488           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12489           CCK_ForBuiltinOverloadedOp);
12490       if (InputRes.isInvalid())
12491         return ExprError();
12492       Input = InputRes.get();
12493       break;
12494     }
12495   }
12496 
12497   case OR_No_Viable_Function:
12498     // This is an erroneous use of an operator which can be overloaded by
12499     // a non-member function. Check for non-member operators which were
12500     // defined too late to be candidates.
12501     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12502       // FIXME: Recover by calling the found function.
12503       return ExprError();
12504 
12505     // No viable function; fall through to handling this as a
12506     // built-in operator, which will produce an error message for us.
12507     break;
12508 
12509   case OR_Ambiguous:
12510     CandidateSet.NoteCandidates(
12511         PartialDiagnosticAt(OpLoc,
12512                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12513                                 << UnaryOperator::getOpcodeStr(Opc)
12514                                 << Input->getType() << Input->getSourceRange()),
12515         *this, OCD_ViableCandidates, ArgsArray,
12516         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12517     return ExprError();
12518 
12519   case OR_Deleted:
12520     CandidateSet.NoteCandidates(
12521         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12522                                        << UnaryOperator::getOpcodeStr(Opc)
12523                                        << Input->getSourceRange()),
12524         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12525         OpLoc);
12526     return ExprError();
12527   }
12528 
12529   // Either we found no viable overloaded operator or we matched a
12530   // built-in operator. In either case, fall through to trying to
12531   // build a built-in operation.
12532   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12533 }
12534 
12535 /// Create a binary operation that may resolve to an overloaded
12536 /// operator.
12537 ///
12538 /// \param OpLoc The location of the operator itself (e.g., '+').
12539 ///
12540 /// \param Opc The BinaryOperatorKind that describes this operator.
12541 ///
12542 /// \param Fns The set of non-member functions that will be
12543 /// considered by overload resolution. The caller needs to build this
12544 /// set based on the context using, e.g.,
12545 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12546 /// set should not contain any member functions; those will be added
12547 /// by CreateOverloadedBinOp().
12548 ///
12549 /// \param LHS Left-hand argument.
12550 /// \param RHS Right-hand argument.
12551 ExprResult
12552 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12553                             BinaryOperatorKind Opc,
12554                             const UnresolvedSetImpl &Fns,
12555                             Expr *LHS, Expr *RHS, bool PerformADL) {
12556   Expr *Args[2] = { LHS, RHS };
12557   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12558 
12559   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12560   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12561 
12562   // If either side is type-dependent, create an appropriate dependent
12563   // expression.
12564   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12565     if (Fns.empty()) {
12566       // If there are no functions to store, just build a dependent
12567       // BinaryOperator or CompoundAssignment.
12568       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12569         return new (Context) BinaryOperator(
12570             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12571             OpLoc, FPFeatures);
12572 
12573       return new (Context) CompoundAssignOperator(
12574           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12575           Context.DependentTy, Context.DependentTy, OpLoc,
12576           FPFeatures);
12577     }
12578 
12579     // FIXME: save results of ADL from here?
12580     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12581     // TODO: provide better source location info in DNLoc component.
12582     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12583     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12584         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12585         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12586     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12587                                        Context.DependentTy, VK_RValue, OpLoc,
12588                                        FPFeatures);
12589   }
12590 
12591   // Always do placeholder-like conversions on the RHS.
12592   if (checkPlaceholderForOverload(*this, Args[1]))
12593     return ExprError();
12594 
12595   // Do placeholder-like conversion on the LHS; note that we should
12596   // not get here with a PseudoObject LHS.
12597   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12598   if (checkPlaceholderForOverload(*this, Args[0]))
12599     return ExprError();
12600 
12601   // If this is the assignment operator, we only perform overload resolution
12602   // if the left-hand side is a class or enumeration type. This is actually
12603   // a hack. The standard requires that we do overload resolution between the
12604   // various built-in candidates, but as DR507 points out, this can lead to
12605   // problems. So we do it this way, which pretty much follows what GCC does.
12606   // Note that we go the traditional code path for compound assignment forms.
12607   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12608     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12609 
12610   // If this is the .* operator, which is not overloadable, just
12611   // create a built-in binary operator.
12612   if (Opc == BO_PtrMemD)
12613     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12614 
12615   // Build an empty overload set.
12616   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12617 
12618   // Add the candidates from the given function set.
12619   AddFunctionCandidates(Fns, Args, CandidateSet);
12620 
12621   // Add operator candidates that are member functions.
12622   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12623 
12624   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12625   // performed for an assignment operator (nor for operator[] nor operator->,
12626   // which don't get here).
12627   if (Opc != BO_Assign && PerformADL)
12628     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12629                                          /*ExplicitTemplateArgs*/ nullptr,
12630                                          CandidateSet);
12631 
12632   // Add builtin operator candidates.
12633   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12634 
12635   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12636 
12637   // Perform overload resolution.
12638   OverloadCandidateSet::iterator Best;
12639   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12640     case OR_Success: {
12641       // We found a built-in operator or an overloaded operator.
12642       FunctionDecl *FnDecl = Best->Function;
12643 
12644       if (FnDecl) {
12645         Expr *Base = nullptr;
12646         // We matched an overloaded operator. Build a call to that
12647         // operator.
12648 
12649         // Convert the arguments.
12650         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12651           // Best->Access is only meaningful for class members.
12652           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12653 
12654           ExprResult Arg1 =
12655             PerformCopyInitialization(
12656               InitializedEntity::InitializeParameter(Context,
12657                                                      FnDecl->getParamDecl(0)),
12658               SourceLocation(), Args[1]);
12659           if (Arg1.isInvalid())
12660             return ExprError();
12661 
12662           ExprResult Arg0 =
12663             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12664                                                 Best->FoundDecl, Method);
12665           if (Arg0.isInvalid())
12666             return ExprError();
12667           Base = Args[0] = Arg0.getAs<Expr>();
12668           Args[1] = RHS = Arg1.getAs<Expr>();
12669         } else {
12670           // Convert the arguments.
12671           ExprResult Arg0 = PerformCopyInitialization(
12672             InitializedEntity::InitializeParameter(Context,
12673                                                    FnDecl->getParamDecl(0)),
12674             SourceLocation(), Args[0]);
12675           if (Arg0.isInvalid())
12676             return ExprError();
12677 
12678           ExprResult Arg1 =
12679             PerformCopyInitialization(
12680               InitializedEntity::InitializeParameter(Context,
12681                                                      FnDecl->getParamDecl(1)),
12682               SourceLocation(), Args[1]);
12683           if (Arg1.isInvalid())
12684             return ExprError();
12685           Args[0] = LHS = Arg0.getAs<Expr>();
12686           Args[1] = RHS = Arg1.getAs<Expr>();
12687         }
12688 
12689         // Build the actual expression node.
12690         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12691                                                   Best->FoundDecl, Base,
12692                                                   HadMultipleCandidates, OpLoc);
12693         if (FnExpr.isInvalid())
12694           return ExprError();
12695 
12696         // Determine the result type.
12697         QualType ResultTy = FnDecl->getReturnType();
12698         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12699         ResultTy = ResultTy.getNonLValueExprType(Context);
12700 
12701         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12702             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12703             Best->IsADLCandidate);
12704 
12705         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12706                                 FnDecl))
12707           return ExprError();
12708 
12709         ArrayRef<const Expr *> ArgsArray(Args, 2);
12710         const Expr *ImplicitThis = nullptr;
12711         // Cut off the implicit 'this'.
12712         if (isa<CXXMethodDecl>(FnDecl)) {
12713           ImplicitThis = ArgsArray[0];
12714           ArgsArray = ArgsArray.slice(1);
12715         }
12716 
12717         // Check for a self move.
12718         if (Op == OO_Equal)
12719           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12720 
12721         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12722                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12723                   VariadicDoesNotApply);
12724 
12725         return MaybeBindToTemporary(TheCall);
12726       } else {
12727         // We matched a built-in operator. Convert the arguments, then
12728         // break out so that we will build the appropriate built-in
12729         // operator node.
12730         ExprResult ArgsRes0 = PerformImplicitConversion(
12731             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12732             AA_Passing, CCK_ForBuiltinOverloadedOp);
12733         if (ArgsRes0.isInvalid())
12734           return ExprError();
12735         Args[0] = ArgsRes0.get();
12736 
12737         ExprResult ArgsRes1 = PerformImplicitConversion(
12738             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12739             AA_Passing, CCK_ForBuiltinOverloadedOp);
12740         if (ArgsRes1.isInvalid())
12741           return ExprError();
12742         Args[1] = ArgsRes1.get();
12743         break;
12744       }
12745     }
12746 
12747     case OR_No_Viable_Function: {
12748       // C++ [over.match.oper]p9:
12749       //   If the operator is the operator , [...] and there are no
12750       //   viable functions, then the operator is assumed to be the
12751       //   built-in operator and interpreted according to clause 5.
12752       if (Opc == BO_Comma)
12753         break;
12754 
12755       // For class as left operand for assignment or compound assignment
12756       // operator do not fall through to handling in built-in, but report that
12757       // no overloaded assignment operator found
12758       ExprResult Result = ExprError();
12759       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
12760       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
12761                                                    Args, OpLoc);
12762       if (Args[0]->getType()->isRecordType() &&
12763           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12764         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12765              << BinaryOperator::getOpcodeStr(Opc)
12766              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12767         if (Args[0]->getType()->isIncompleteType()) {
12768           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12769             << Args[0]->getType()
12770             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12771         }
12772       } else {
12773         // This is an erroneous use of an operator which can be overloaded by
12774         // a non-member function. Check for non-member operators which were
12775         // defined too late to be candidates.
12776         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12777           // FIXME: Recover by calling the found function.
12778           return ExprError();
12779 
12780         // No viable function; try to create a built-in operation, which will
12781         // produce an error. Then, show the non-viable candidates.
12782         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12783       }
12784       assert(Result.isInvalid() &&
12785              "C++ binary operator overloading is missing candidates!");
12786       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
12787       return Result;
12788     }
12789 
12790     case OR_Ambiguous:
12791       CandidateSet.NoteCandidates(
12792           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12793                                          << BinaryOperator::getOpcodeStr(Opc)
12794                                          << Args[0]->getType()
12795                                          << Args[1]->getType()
12796                                          << Args[0]->getSourceRange()
12797                                          << Args[1]->getSourceRange()),
12798           *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12799           OpLoc);
12800       return ExprError();
12801 
12802     case OR_Deleted:
12803       if (isImplicitlyDeleted(Best->Function)) {
12804         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12805         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12806           << Context.getRecordType(Method->getParent())
12807           << getSpecialMember(Method);
12808 
12809         // The user probably meant to call this special member. Just
12810         // explain why it's deleted.
12811         NoteDeletedFunction(Method);
12812         return ExprError();
12813       }
12814       CandidateSet.NoteCandidates(
12815           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12816                                          << BinaryOperator::getOpcodeStr(Opc)
12817                                          << Args[0]->getSourceRange()
12818                                          << Args[1]->getSourceRange()),
12819           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12820           OpLoc);
12821       return ExprError();
12822   }
12823 
12824   // We matched a built-in operator; build it.
12825   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12826 }
12827 
12828 ExprResult
12829 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12830                                          SourceLocation RLoc,
12831                                          Expr *Base, Expr *Idx) {
12832   Expr *Args[2] = { Base, Idx };
12833   DeclarationName OpName =
12834       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12835 
12836   // If either side is type-dependent, create an appropriate dependent
12837   // expression.
12838   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12839 
12840     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12841     // CHECKME: no 'operator' keyword?
12842     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12843     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12844     UnresolvedLookupExpr *Fn
12845       = UnresolvedLookupExpr::Create(Context, NamingClass,
12846                                      NestedNameSpecifierLoc(), OpNameInfo,
12847                                      /*ADL*/ true, /*Overloaded*/ false,
12848                                      UnresolvedSetIterator(),
12849                                      UnresolvedSetIterator());
12850     // Can't add any actual overloads yet
12851 
12852     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12853                                        Context.DependentTy, VK_RValue, RLoc,
12854                                        FPOptions());
12855   }
12856 
12857   // Handle placeholders on both operands.
12858   if (checkPlaceholderForOverload(*this, Args[0]))
12859     return ExprError();
12860   if (checkPlaceholderForOverload(*this, Args[1]))
12861     return ExprError();
12862 
12863   // Build an empty overload set.
12864   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12865 
12866   // Subscript can only be overloaded as a member function.
12867 
12868   // Add operator candidates that are member functions.
12869   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12870 
12871   // Add builtin operator candidates.
12872   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12873 
12874   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12875 
12876   // Perform overload resolution.
12877   OverloadCandidateSet::iterator Best;
12878   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12879     case OR_Success: {
12880       // We found a built-in operator or an overloaded operator.
12881       FunctionDecl *FnDecl = Best->Function;
12882 
12883       if (FnDecl) {
12884         // We matched an overloaded operator. Build a call to that
12885         // operator.
12886 
12887         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12888 
12889         // Convert the arguments.
12890         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12891         ExprResult Arg0 =
12892           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12893                                               Best->FoundDecl, Method);
12894         if (Arg0.isInvalid())
12895           return ExprError();
12896         Args[0] = Arg0.get();
12897 
12898         // Convert the arguments.
12899         ExprResult InputInit
12900           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12901                                                       Context,
12902                                                       FnDecl->getParamDecl(0)),
12903                                       SourceLocation(),
12904                                       Args[1]);
12905         if (InputInit.isInvalid())
12906           return ExprError();
12907 
12908         Args[1] = InputInit.getAs<Expr>();
12909 
12910         // Build the actual expression node.
12911         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12912         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12913         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12914                                                   Best->FoundDecl,
12915                                                   Base,
12916                                                   HadMultipleCandidates,
12917                                                   OpLocInfo.getLoc(),
12918                                                   OpLocInfo.getInfo());
12919         if (FnExpr.isInvalid())
12920           return ExprError();
12921 
12922         // Determine the result type
12923         QualType ResultTy = FnDecl->getReturnType();
12924         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12925         ResultTy = ResultTy.getNonLValueExprType(Context);
12926 
12927         CXXOperatorCallExpr *TheCall =
12928             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12929                                         Args, ResultTy, VK, RLoc, FPOptions());
12930 
12931         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12932           return ExprError();
12933 
12934         if (CheckFunctionCall(Method, TheCall,
12935                               Method->getType()->castAs<FunctionProtoType>()))
12936           return ExprError();
12937 
12938         return MaybeBindToTemporary(TheCall);
12939       } else {
12940         // We matched a built-in operator. Convert the arguments, then
12941         // break out so that we will build the appropriate built-in
12942         // operator node.
12943         ExprResult ArgsRes0 = PerformImplicitConversion(
12944             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12945             AA_Passing, CCK_ForBuiltinOverloadedOp);
12946         if (ArgsRes0.isInvalid())
12947           return ExprError();
12948         Args[0] = ArgsRes0.get();
12949 
12950         ExprResult ArgsRes1 = PerformImplicitConversion(
12951             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12952             AA_Passing, CCK_ForBuiltinOverloadedOp);
12953         if (ArgsRes1.isInvalid())
12954           return ExprError();
12955         Args[1] = ArgsRes1.get();
12956 
12957         break;
12958       }
12959     }
12960 
12961     case OR_No_Viable_Function: {
12962       PartialDiagnostic PD = CandidateSet.empty()
12963           ? (PDiag(diag::err_ovl_no_oper)
12964              << Args[0]->getType() << /*subscript*/ 0
12965              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
12966           : (PDiag(diag::err_ovl_no_viable_subscript)
12967              << Args[0]->getType() << Args[0]->getSourceRange()
12968              << Args[1]->getSourceRange());
12969       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
12970                                   OCD_AllCandidates, Args, "[]", LLoc);
12971       return ExprError();
12972     }
12973 
12974     case OR_Ambiguous:
12975       CandidateSet.NoteCandidates(
12976           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12977                                         << "[]" << Args[0]->getType()
12978                                         << Args[1]->getType()
12979                                         << Args[0]->getSourceRange()
12980                                         << Args[1]->getSourceRange()),
12981           *this, OCD_ViableCandidates, Args, "[]", LLoc);
12982       return ExprError();
12983 
12984     case OR_Deleted:
12985       CandidateSet.NoteCandidates(
12986           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
12987                                         << "[]" << Args[0]->getSourceRange()
12988                                         << Args[1]->getSourceRange()),
12989           *this, OCD_AllCandidates, Args, "[]", LLoc);
12990       return ExprError();
12991     }
12992 
12993   // We matched a built-in operator; build it.
12994   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12995 }
12996 
12997 /// BuildCallToMemberFunction - Build a call to a member
12998 /// function. MemExpr is the expression that refers to the member
12999 /// function (and includes the object parameter), Args/NumArgs are the
13000 /// arguments to the function call (not including the object
13001 /// parameter). The caller needs to validate that the member
13002 /// expression refers to a non-static member function or an overloaded
13003 /// member function.
13004 ExprResult
13005 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13006                                 SourceLocation LParenLoc,
13007                                 MultiExprArg Args,
13008                                 SourceLocation RParenLoc) {
13009   assert(MemExprE->getType() == Context.BoundMemberTy ||
13010          MemExprE->getType() == Context.OverloadTy);
13011 
13012   // Dig out the member expression. This holds both the object
13013   // argument and the member function we're referring to.
13014   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13015 
13016   // Determine whether this is a call to a pointer-to-member function.
13017   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13018     assert(op->getType() == Context.BoundMemberTy);
13019     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13020 
13021     QualType fnType =
13022       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13023 
13024     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13025     QualType resultType = proto->getCallResultType(Context);
13026     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13027 
13028     // Check that the object type isn't more qualified than the
13029     // member function we're calling.
13030     Qualifiers funcQuals = proto->getMethodQuals();
13031 
13032     QualType objectType = op->getLHS()->getType();
13033     if (op->getOpcode() == BO_PtrMemI)
13034       objectType = objectType->castAs<PointerType>()->getPointeeType();
13035     Qualifiers objectQuals = objectType.getQualifiers();
13036 
13037     Qualifiers difference = objectQuals - funcQuals;
13038     difference.removeObjCGCAttr();
13039     difference.removeAddressSpace();
13040     if (difference) {
13041       std::string qualsString = difference.getAsString();
13042       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13043         << fnType.getUnqualifiedType()
13044         << qualsString
13045         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13046     }
13047 
13048     CXXMemberCallExpr *call =
13049         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13050                                   valueKind, RParenLoc, proto->getNumParams());
13051 
13052     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13053                             call, nullptr))
13054       return ExprError();
13055 
13056     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13057       return ExprError();
13058 
13059     if (CheckOtherCall(call, proto))
13060       return ExprError();
13061 
13062     return MaybeBindToTemporary(call);
13063   }
13064 
13065   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13066     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13067                             RParenLoc);
13068 
13069   UnbridgedCastsSet UnbridgedCasts;
13070   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13071     return ExprError();
13072 
13073   MemberExpr *MemExpr;
13074   CXXMethodDecl *Method = nullptr;
13075   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13076   NestedNameSpecifier *Qualifier = nullptr;
13077   if (isa<MemberExpr>(NakedMemExpr)) {
13078     MemExpr = cast<MemberExpr>(NakedMemExpr);
13079     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13080     FoundDecl = MemExpr->getFoundDecl();
13081     Qualifier = MemExpr->getQualifier();
13082     UnbridgedCasts.restore();
13083   } else {
13084     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13085     Qualifier = UnresExpr->getQualifier();
13086 
13087     QualType ObjectType = UnresExpr->getBaseType();
13088     Expr::Classification ObjectClassification
13089       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13090                             : UnresExpr->getBase()->Classify(Context);
13091 
13092     // Add overload candidates
13093     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13094                                       OverloadCandidateSet::CSK_Normal);
13095 
13096     // FIXME: avoid copy.
13097     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13098     if (UnresExpr->hasExplicitTemplateArgs()) {
13099       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13100       TemplateArgs = &TemplateArgsBuffer;
13101     }
13102 
13103     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13104            E = UnresExpr->decls_end(); I != E; ++I) {
13105 
13106       NamedDecl *Func = *I;
13107       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13108       if (isa<UsingShadowDecl>(Func))
13109         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13110 
13111 
13112       // Microsoft supports direct constructor calls.
13113       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13114         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13115                              CandidateSet,
13116                              /*SuppressUserConversions*/ false);
13117       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13118         // If explicit template arguments were provided, we can't call a
13119         // non-template member function.
13120         if (TemplateArgs)
13121           continue;
13122 
13123         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13124                            ObjectClassification, Args, CandidateSet,
13125                            /*SuppressUserConversions=*/false);
13126       } else {
13127         AddMethodTemplateCandidate(
13128             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13129             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13130             /*SuppressUserConversions=*/false);
13131       }
13132     }
13133 
13134     DeclarationName DeclName = UnresExpr->getMemberName();
13135 
13136     UnbridgedCasts.restore();
13137 
13138     OverloadCandidateSet::iterator Best;
13139     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13140                                             Best)) {
13141     case OR_Success:
13142       Method = cast<CXXMethodDecl>(Best->Function);
13143       FoundDecl = Best->FoundDecl;
13144       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13145       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13146         return ExprError();
13147       // If FoundDecl is different from Method (such as if one is a template
13148       // and the other a specialization), make sure DiagnoseUseOfDecl is
13149       // called on both.
13150       // FIXME: This would be more comprehensively addressed by modifying
13151       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13152       // being used.
13153       if (Method != FoundDecl.getDecl() &&
13154                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13155         return ExprError();
13156       break;
13157 
13158     case OR_No_Viable_Function:
13159       CandidateSet.NoteCandidates(
13160           PartialDiagnosticAt(
13161               UnresExpr->getMemberLoc(),
13162               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13163                   << DeclName << MemExprE->getSourceRange()),
13164           *this, OCD_AllCandidates, Args);
13165       // FIXME: Leaking incoming expressions!
13166       return ExprError();
13167 
13168     case OR_Ambiguous:
13169       CandidateSet.NoteCandidates(
13170           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13171                               PDiag(diag::err_ovl_ambiguous_member_call)
13172                                   << DeclName << MemExprE->getSourceRange()),
13173           *this, OCD_AllCandidates, Args);
13174       // FIXME: Leaking incoming expressions!
13175       return ExprError();
13176 
13177     case OR_Deleted:
13178       CandidateSet.NoteCandidates(
13179           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13180                               PDiag(diag::err_ovl_deleted_member_call)
13181                                   << DeclName << MemExprE->getSourceRange()),
13182           *this, OCD_AllCandidates, Args);
13183       // FIXME: Leaking incoming expressions!
13184       return ExprError();
13185     }
13186 
13187     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13188 
13189     // If overload resolution picked a static member, build a
13190     // non-member call based on that function.
13191     if (Method->isStatic()) {
13192       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13193                                    RParenLoc);
13194     }
13195 
13196     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13197   }
13198 
13199   QualType ResultType = Method->getReturnType();
13200   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13201   ResultType = ResultType.getNonLValueExprType(Context);
13202 
13203   assert(Method && "Member call to something that isn't a method?");
13204   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13205   CXXMemberCallExpr *TheCall =
13206       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13207                                 RParenLoc, Proto->getNumParams());
13208 
13209   // Check for a valid return type.
13210   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13211                           TheCall, Method))
13212     return ExprError();
13213 
13214   // Convert the object argument (for a non-static member function call).
13215   // We only need to do this if there was actually an overload; otherwise
13216   // it was done at lookup.
13217   if (!Method->isStatic()) {
13218     ExprResult ObjectArg =
13219       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13220                                           FoundDecl, Method);
13221     if (ObjectArg.isInvalid())
13222       return ExprError();
13223     MemExpr->setBase(ObjectArg.get());
13224   }
13225 
13226   // Convert the rest of the arguments
13227   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13228                               RParenLoc))
13229     return ExprError();
13230 
13231   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13232 
13233   if (CheckFunctionCall(Method, TheCall, Proto))
13234     return ExprError();
13235 
13236   // In the case the method to call was not selected by the overloading
13237   // resolution process, we still need to handle the enable_if attribute. Do
13238   // that here, so it will not hide previous -- and more relevant -- errors.
13239   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13240     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13241       Diag(MemE->getMemberLoc(),
13242            diag::err_ovl_no_viable_member_function_in_call)
13243           << Method << Method->getSourceRange();
13244       Diag(Method->getLocation(),
13245            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13246           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13247       return ExprError();
13248     }
13249   }
13250 
13251   if ((isa<CXXConstructorDecl>(CurContext) ||
13252        isa<CXXDestructorDecl>(CurContext)) &&
13253       TheCall->getMethodDecl()->isPure()) {
13254     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13255 
13256     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13257         MemExpr->performsVirtualDispatch(getLangOpts())) {
13258       Diag(MemExpr->getBeginLoc(),
13259            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13260           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13261           << MD->getParent()->getDeclName();
13262 
13263       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13264       if (getLangOpts().AppleKext)
13265         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13266             << MD->getParent()->getDeclName() << MD->getDeclName();
13267     }
13268   }
13269 
13270   if (CXXDestructorDecl *DD =
13271           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13272     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13273     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13274     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13275                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13276                          MemExpr->getMemberLoc());
13277   }
13278 
13279   return MaybeBindToTemporary(TheCall);
13280 }
13281 
13282 /// BuildCallToObjectOfClassType - Build a call to an object of class
13283 /// type (C++ [over.call.object]), which can end up invoking an
13284 /// overloaded function call operator (@c operator()) or performing a
13285 /// user-defined conversion on the object argument.
13286 ExprResult
13287 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13288                                    SourceLocation LParenLoc,
13289                                    MultiExprArg Args,
13290                                    SourceLocation RParenLoc) {
13291   if (checkPlaceholderForOverload(*this, Obj))
13292     return ExprError();
13293   ExprResult Object = Obj;
13294 
13295   UnbridgedCastsSet UnbridgedCasts;
13296   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13297     return ExprError();
13298 
13299   assert(Object.get()->getType()->isRecordType() &&
13300          "Requires object type argument");
13301   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13302 
13303   // C++ [over.call.object]p1:
13304   //  If the primary-expression E in the function call syntax
13305   //  evaluates to a class object of type "cv T", then the set of
13306   //  candidate functions includes at least the function call
13307   //  operators of T. The function call operators of T are obtained by
13308   //  ordinary lookup of the name operator() in the context of
13309   //  (E).operator().
13310   OverloadCandidateSet CandidateSet(LParenLoc,
13311                                     OverloadCandidateSet::CSK_Operator);
13312   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13313 
13314   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13315                           diag::err_incomplete_object_call, Object.get()))
13316     return true;
13317 
13318   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13319   LookupQualifiedName(R, Record->getDecl());
13320   R.suppressDiagnostics();
13321 
13322   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13323        Oper != OperEnd; ++Oper) {
13324     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13325                        Object.get()->Classify(Context), Args, CandidateSet,
13326                        /*SuppressUserConversion=*/false);
13327   }
13328 
13329   // C++ [over.call.object]p2:
13330   //   In addition, for each (non-explicit in C++0x) conversion function
13331   //   declared in T of the form
13332   //
13333   //        operator conversion-type-id () cv-qualifier;
13334   //
13335   //   where cv-qualifier is the same cv-qualification as, or a
13336   //   greater cv-qualification than, cv, and where conversion-type-id
13337   //   denotes the type "pointer to function of (P1,...,Pn) returning
13338   //   R", or the type "reference to pointer to function of
13339   //   (P1,...,Pn) returning R", or the type "reference to function
13340   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13341   //   is also considered as a candidate function. Similarly,
13342   //   surrogate call functions are added to the set of candidate
13343   //   functions for each conversion function declared in an
13344   //   accessible base class provided the function is not hidden
13345   //   within T by another intervening declaration.
13346   const auto &Conversions =
13347       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13348   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13349     NamedDecl *D = *I;
13350     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13351     if (isa<UsingShadowDecl>(D))
13352       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13353 
13354     // Skip over templated conversion functions; they aren't
13355     // surrogates.
13356     if (isa<FunctionTemplateDecl>(D))
13357       continue;
13358 
13359     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13360     if (!Conv->isExplicit()) {
13361       // Strip the reference type (if any) and then the pointer type (if
13362       // any) to get down to what might be a function type.
13363       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13364       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13365         ConvType = ConvPtrType->getPointeeType();
13366 
13367       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13368       {
13369         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13370                               Object.get(), Args, CandidateSet);
13371       }
13372     }
13373   }
13374 
13375   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13376 
13377   // Perform overload resolution.
13378   OverloadCandidateSet::iterator Best;
13379   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13380                                           Best)) {
13381   case OR_Success:
13382     // Overload resolution succeeded; we'll build the appropriate call
13383     // below.
13384     break;
13385 
13386   case OR_No_Viable_Function: {
13387     PartialDiagnostic PD =
13388         CandidateSet.empty()
13389             ? (PDiag(diag::err_ovl_no_oper)
13390                << Object.get()->getType() << /*call*/ 1
13391                << Object.get()->getSourceRange())
13392             : (PDiag(diag::err_ovl_no_viable_object_call)
13393                << Object.get()->getType() << Object.get()->getSourceRange());
13394     CandidateSet.NoteCandidates(
13395         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13396         OCD_AllCandidates, Args);
13397     break;
13398   }
13399   case OR_Ambiguous:
13400     CandidateSet.NoteCandidates(
13401         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13402                             PDiag(diag::err_ovl_ambiguous_object_call)
13403                                 << Object.get()->getType()
13404                                 << Object.get()->getSourceRange()),
13405         *this, OCD_ViableCandidates, Args);
13406     break;
13407 
13408   case OR_Deleted:
13409     CandidateSet.NoteCandidates(
13410         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13411                             PDiag(diag::err_ovl_deleted_object_call)
13412                                 << Object.get()->getType()
13413                                 << Object.get()->getSourceRange()),
13414         *this, OCD_AllCandidates, Args);
13415     break;
13416   }
13417 
13418   if (Best == CandidateSet.end())
13419     return true;
13420 
13421   UnbridgedCasts.restore();
13422 
13423   if (Best->Function == nullptr) {
13424     // Since there is no function declaration, this is one of the
13425     // surrogate candidates. Dig out the conversion function.
13426     CXXConversionDecl *Conv
13427       = cast<CXXConversionDecl>(
13428                          Best->Conversions[0].UserDefined.ConversionFunction);
13429 
13430     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13431                               Best->FoundDecl);
13432     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13433       return ExprError();
13434     assert(Conv == Best->FoundDecl.getDecl() &&
13435              "Found Decl & conversion-to-functionptr should be same, right?!");
13436     // We selected one of the surrogate functions that converts the
13437     // object parameter to a function pointer. Perform the conversion
13438     // on the object argument, then let BuildCallExpr finish the job.
13439 
13440     // Create an implicit member expr to refer to the conversion operator.
13441     // and then call it.
13442     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13443                                              Conv, HadMultipleCandidates);
13444     if (Call.isInvalid())
13445       return ExprError();
13446     // Record usage of conversion in an implicit cast.
13447     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13448                                     CK_UserDefinedConversion, Call.get(),
13449                                     nullptr, VK_RValue);
13450 
13451     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13452   }
13453 
13454   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13455 
13456   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13457   // that calls this method, using Object for the implicit object
13458   // parameter and passing along the remaining arguments.
13459   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13460 
13461   // An error diagnostic has already been printed when parsing the declaration.
13462   if (Method->isInvalidDecl())
13463     return ExprError();
13464 
13465   const FunctionProtoType *Proto =
13466     Method->getType()->getAs<FunctionProtoType>();
13467 
13468   unsigned NumParams = Proto->getNumParams();
13469 
13470   DeclarationNameInfo OpLocInfo(
13471                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13472   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13473   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13474                                            Obj, HadMultipleCandidates,
13475                                            OpLocInfo.getLoc(),
13476                                            OpLocInfo.getInfo());
13477   if (NewFn.isInvalid())
13478     return true;
13479 
13480   // The number of argument slots to allocate in the call. If we have default
13481   // arguments we need to allocate space for them as well. We additionally
13482   // need one more slot for the object parameter.
13483   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13484 
13485   // Build the full argument list for the method call (the implicit object
13486   // parameter is placed at the beginning of the list).
13487   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13488 
13489   bool IsError = false;
13490 
13491   // Initialize the implicit object parameter.
13492   ExprResult ObjRes =
13493     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13494                                         Best->FoundDecl, Method);
13495   if (ObjRes.isInvalid())
13496     IsError = true;
13497   else
13498     Object = ObjRes;
13499   MethodArgs[0] = Object.get();
13500 
13501   // Check the argument types.
13502   for (unsigned i = 0; i != NumParams; i++) {
13503     Expr *Arg;
13504     if (i < Args.size()) {
13505       Arg = Args[i];
13506 
13507       // Pass the argument.
13508 
13509       ExprResult InputInit
13510         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13511                                                     Context,
13512                                                     Method->getParamDecl(i)),
13513                                     SourceLocation(), Arg);
13514 
13515       IsError |= InputInit.isInvalid();
13516       Arg = InputInit.getAs<Expr>();
13517     } else {
13518       ExprResult DefArg
13519         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13520       if (DefArg.isInvalid()) {
13521         IsError = true;
13522         break;
13523       }
13524 
13525       Arg = DefArg.getAs<Expr>();
13526     }
13527 
13528     MethodArgs[i + 1] = Arg;
13529   }
13530 
13531   // If this is a variadic call, handle args passed through "...".
13532   if (Proto->isVariadic()) {
13533     // Promote the arguments (C99 6.5.2.2p7).
13534     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13535       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13536                                                         nullptr);
13537       IsError |= Arg.isInvalid();
13538       MethodArgs[i + 1] = Arg.get();
13539     }
13540   }
13541 
13542   if (IsError)
13543     return true;
13544 
13545   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13546 
13547   // Once we've built TheCall, all of the expressions are properly owned.
13548   QualType ResultTy = Method->getReturnType();
13549   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13550   ResultTy = ResultTy.getNonLValueExprType(Context);
13551 
13552   CXXOperatorCallExpr *TheCall =
13553       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13554                                   ResultTy, VK, RParenLoc, FPOptions());
13555 
13556   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13557     return true;
13558 
13559   if (CheckFunctionCall(Method, TheCall, Proto))
13560     return true;
13561 
13562   return MaybeBindToTemporary(TheCall);
13563 }
13564 
13565 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13566 ///  (if one exists), where @c Base is an expression of class type and
13567 /// @c Member is the name of the member we're trying to find.
13568 ExprResult
13569 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13570                                bool *NoArrowOperatorFound) {
13571   assert(Base->getType()->isRecordType() &&
13572          "left-hand side must have class type");
13573 
13574   if (checkPlaceholderForOverload(*this, Base))
13575     return ExprError();
13576 
13577   SourceLocation Loc = Base->getExprLoc();
13578 
13579   // C++ [over.ref]p1:
13580   //
13581   //   [...] An expression x->m is interpreted as (x.operator->())->m
13582   //   for a class object x of type T if T::operator->() exists and if
13583   //   the operator is selected as the best match function by the
13584   //   overload resolution mechanism (13.3).
13585   DeclarationName OpName =
13586     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13587   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13588   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13589 
13590   if (RequireCompleteType(Loc, Base->getType(),
13591                           diag::err_typecheck_incomplete_tag, Base))
13592     return ExprError();
13593 
13594   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13595   LookupQualifiedName(R, BaseRecord->getDecl());
13596   R.suppressDiagnostics();
13597 
13598   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13599        Oper != OperEnd; ++Oper) {
13600     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13601                        None, CandidateSet, /*SuppressUserConversion=*/false);
13602   }
13603 
13604   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13605 
13606   // Perform overload resolution.
13607   OverloadCandidateSet::iterator Best;
13608   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13609   case OR_Success:
13610     // Overload resolution succeeded; we'll build the call below.
13611     break;
13612 
13613   case OR_No_Viable_Function: {
13614     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
13615     if (CandidateSet.empty()) {
13616       QualType BaseType = Base->getType();
13617       if (NoArrowOperatorFound) {
13618         // Report this specific error to the caller instead of emitting a
13619         // diagnostic, as requested.
13620         *NoArrowOperatorFound = true;
13621         return ExprError();
13622       }
13623       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13624         << BaseType << Base->getSourceRange();
13625       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13626         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13627           << FixItHint::CreateReplacement(OpLoc, ".");
13628       }
13629     } else
13630       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13631         << "operator->" << Base->getSourceRange();
13632     CandidateSet.NoteCandidates(*this, Base, Cands);
13633     return ExprError();
13634   }
13635   case OR_Ambiguous:
13636     CandidateSet.NoteCandidates(
13637         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
13638                                        << "->" << Base->getType()
13639                                        << Base->getSourceRange()),
13640         *this, OCD_ViableCandidates, Base);
13641     return ExprError();
13642 
13643   case OR_Deleted:
13644     CandidateSet.NoteCandidates(
13645         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13646                                        << "->" << Base->getSourceRange()),
13647         *this, OCD_AllCandidates, Base);
13648     return ExprError();
13649   }
13650 
13651   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13652 
13653   // Convert the object parameter.
13654   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13655   ExprResult BaseResult =
13656     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13657                                         Best->FoundDecl, Method);
13658   if (BaseResult.isInvalid())
13659     return ExprError();
13660   Base = BaseResult.get();
13661 
13662   // Build the operator call.
13663   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13664                                             Base, HadMultipleCandidates, OpLoc);
13665   if (FnExpr.isInvalid())
13666     return ExprError();
13667 
13668   QualType ResultTy = Method->getReturnType();
13669   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13670   ResultTy = ResultTy.getNonLValueExprType(Context);
13671   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13672       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13673 
13674   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13675     return ExprError();
13676 
13677   if (CheckFunctionCall(Method, TheCall,
13678                         Method->getType()->castAs<FunctionProtoType>()))
13679     return ExprError();
13680 
13681   return MaybeBindToTemporary(TheCall);
13682 }
13683 
13684 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13685 /// a literal operator described by the provided lookup results.
13686 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13687                                           DeclarationNameInfo &SuffixInfo,
13688                                           ArrayRef<Expr*> Args,
13689                                           SourceLocation LitEndLoc,
13690                                        TemplateArgumentListInfo *TemplateArgs) {
13691   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13692 
13693   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13694                                     OverloadCandidateSet::CSK_Normal);
13695   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13696                         /*SuppressUserConversions=*/true);
13697 
13698   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13699 
13700   // Perform overload resolution. This will usually be trivial, but might need
13701   // to perform substitutions for a literal operator template.
13702   OverloadCandidateSet::iterator Best;
13703   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13704   case OR_Success:
13705   case OR_Deleted:
13706     break;
13707 
13708   case OR_No_Viable_Function:
13709     CandidateSet.NoteCandidates(
13710         PartialDiagnosticAt(UDSuffixLoc,
13711                             PDiag(diag::err_ovl_no_viable_function_in_call)
13712                                 << R.getLookupName()),
13713         *this, OCD_AllCandidates, Args);
13714     return ExprError();
13715 
13716   case OR_Ambiguous:
13717     CandidateSet.NoteCandidates(
13718         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
13719                                                 << R.getLookupName()),
13720         *this, OCD_ViableCandidates, Args);
13721     return ExprError();
13722   }
13723 
13724   FunctionDecl *FD = Best->Function;
13725   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13726                                         nullptr, HadMultipleCandidates,
13727                                         SuffixInfo.getLoc(),
13728                                         SuffixInfo.getInfo());
13729   if (Fn.isInvalid())
13730     return true;
13731 
13732   // Check the argument types. This should almost always be a no-op, except
13733   // that array-to-pointer decay is applied to string literals.
13734   Expr *ConvArgs[2];
13735   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13736     ExprResult InputInit = PerformCopyInitialization(
13737       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13738       SourceLocation(), Args[ArgIdx]);
13739     if (InputInit.isInvalid())
13740       return true;
13741     ConvArgs[ArgIdx] = InputInit.get();
13742   }
13743 
13744   QualType ResultTy = FD->getReturnType();
13745   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13746   ResultTy = ResultTy.getNonLValueExprType(Context);
13747 
13748   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13749       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13750       VK, LitEndLoc, UDSuffixLoc);
13751 
13752   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13753     return ExprError();
13754 
13755   if (CheckFunctionCall(FD, UDL, nullptr))
13756     return ExprError();
13757 
13758   return MaybeBindToTemporary(UDL);
13759 }
13760 
13761 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13762 /// given LookupResult is non-empty, it is assumed to describe a member which
13763 /// will be invoked. Otherwise, the function will be found via argument
13764 /// dependent lookup.
13765 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13766 /// otherwise CallExpr is set to ExprError() and some non-success value
13767 /// is returned.
13768 Sema::ForRangeStatus
13769 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13770                                 SourceLocation RangeLoc,
13771                                 const DeclarationNameInfo &NameInfo,
13772                                 LookupResult &MemberLookup,
13773                                 OverloadCandidateSet *CandidateSet,
13774                                 Expr *Range, ExprResult *CallExpr) {
13775   Scope *S = nullptr;
13776 
13777   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13778   if (!MemberLookup.empty()) {
13779     ExprResult MemberRef =
13780         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13781                                  /*IsPtr=*/false, CXXScopeSpec(),
13782                                  /*TemplateKWLoc=*/SourceLocation(),
13783                                  /*FirstQualifierInScope=*/nullptr,
13784                                  MemberLookup,
13785                                  /*TemplateArgs=*/nullptr, S);
13786     if (MemberRef.isInvalid()) {
13787       *CallExpr = ExprError();
13788       return FRS_DiagnosticIssued;
13789     }
13790     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13791     if (CallExpr->isInvalid()) {
13792       *CallExpr = ExprError();
13793       return FRS_DiagnosticIssued;
13794     }
13795   } else {
13796     UnresolvedSet<0> FoundNames;
13797     UnresolvedLookupExpr *Fn =
13798       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13799                                    NestedNameSpecifierLoc(), NameInfo,
13800                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13801                                    FoundNames.begin(), FoundNames.end());
13802 
13803     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13804                                                     CandidateSet, CallExpr);
13805     if (CandidateSet->empty() || CandidateSetError) {
13806       *CallExpr = ExprError();
13807       return FRS_NoViableFunction;
13808     }
13809     OverloadCandidateSet::iterator Best;
13810     OverloadingResult OverloadResult =
13811         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13812 
13813     if (OverloadResult == OR_No_Viable_Function) {
13814       *CallExpr = ExprError();
13815       return FRS_NoViableFunction;
13816     }
13817     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13818                                          Loc, nullptr, CandidateSet, &Best,
13819                                          OverloadResult,
13820                                          /*AllowTypoCorrection=*/false);
13821     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13822       *CallExpr = ExprError();
13823       return FRS_DiagnosticIssued;
13824     }
13825   }
13826   return FRS_Success;
13827 }
13828 
13829 
13830 /// FixOverloadedFunctionReference - E is an expression that refers to
13831 /// a C++ overloaded function (possibly with some parentheses and
13832 /// perhaps a '&' around it). We have resolved the overloaded function
13833 /// to the function declaration Fn, so patch up the expression E to
13834 /// refer (possibly indirectly) to Fn. Returns the new expr.
13835 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13836                                            FunctionDecl *Fn) {
13837   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13838     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13839                                                    Found, Fn);
13840     if (SubExpr == PE->getSubExpr())
13841       return PE;
13842 
13843     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13844   }
13845 
13846   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13847     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13848                                                    Found, Fn);
13849     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13850                                SubExpr->getType()) &&
13851            "Implicit cast type cannot be determined from overload");
13852     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13853     if (SubExpr == ICE->getSubExpr())
13854       return ICE;
13855 
13856     return ImplicitCastExpr::Create(Context, ICE->getType(),
13857                                     ICE->getCastKind(),
13858                                     SubExpr, nullptr,
13859                                     ICE->getValueKind());
13860   }
13861 
13862   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13863     if (!GSE->isResultDependent()) {
13864       Expr *SubExpr =
13865           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13866       if (SubExpr == GSE->getResultExpr())
13867         return GSE;
13868 
13869       // Replace the resulting type information before rebuilding the generic
13870       // selection expression.
13871       ArrayRef<Expr *> A = GSE->getAssocExprs();
13872       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13873       unsigned ResultIdx = GSE->getResultIndex();
13874       AssocExprs[ResultIdx] = SubExpr;
13875 
13876       return GenericSelectionExpr::Create(
13877           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13878           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13879           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13880           ResultIdx);
13881     }
13882     // Rather than fall through to the unreachable, return the original generic
13883     // selection expression.
13884     return GSE;
13885   }
13886 
13887   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13888     assert(UnOp->getOpcode() == UO_AddrOf &&
13889            "Can only take the address of an overloaded function");
13890     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13891       if (Method->isStatic()) {
13892         // Do nothing: static member functions aren't any different
13893         // from non-member functions.
13894       } else {
13895         // Fix the subexpression, which really has to be an
13896         // UnresolvedLookupExpr holding an overloaded member function
13897         // or template.
13898         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13899                                                        Found, Fn);
13900         if (SubExpr == UnOp->getSubExpr())
13901           return UnOp;
13902 
13903         assert(isa<DeclRefExpr>(SubExpr)
13904                && "fixed to something other than a decl ref");
13905         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13906                && "fixed to a member ref with no nested name qualifier");
13907 
13908         // We have taken the address of a pointer to member
13909         // function. Perform the computation here so that we get the
13910         // appropriate pointer to member type.
13911         QualType ClassType
13912           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13913         QualType MemPtrType
13914           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13915         // Under the MS ABI, lock down the inheritance model now.
13916         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13917           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13918 
13919         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13920                                            VK_RValue, OK_Ordinary,
13921                                            UnOp->getOperatorLoc(), false);
13922       }
13923     }
13924     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13925                                                    Found, Fn);
13926     if (SubExpr == UnOp->getSubExpr())
13927       return UnOp;
13928 
13929     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13930                                      Context.getPointerType(SubExpr->getType()),
13931                                        VK_RValue, OK_Ordinary,
13932                                        UnOp->getOperatorLoc(), false);
13933   }
13934 
13935   // C++ [except.spec]p17:
13936   //   An exception-specification is considered to be needed when:
13937   //   - in an expression the function is the unique lookup result or the
13938   //     selected member of a set of overloaded functions
13939   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13940     ResolveExceptionSpec(E->getExprLoc(), FPT);
13941 
13942   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13943     // FIXME: avoid copy.
13944     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13945     if (ULE->hasExplicitTemplateArgs()) {
13946       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13947       TemplateArgs = &TemplateArgsBuffer;
13948     }
13949 
13950     DeclRefExpr *DRE =
13951         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
13952                          ULE->getQualifierLoc(), Found.getDecl(),
13953                          ULE->getTemplateKeywordLoc(), TemplateArgs);
13954     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13955     return DRE;
13956   }
13957 
13958   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13959     // FIXME: avoid copy.
13960     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13961     if (MemExpr->hasExplicitTemplateArgs()) {
13962       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13963       TemplateArgs = &TemplateArgsBuffer;
13964     }
13965 
13966     Expr *Base;
13967 
13968     // If we're filling in a static method where we used to have an
13969     // implicit member access, rewrite to a simple decl ref.
13970     if (MemExpr->isImplicitAccess()) {
13971       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13972         DeclRefExpr *DRE = BuildDeclRefExpr(
13973             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
13974             MemExpr->getQualifierLoc(), Found.getDecl(),
13975             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
13976         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13977         return DRE;
13978       } else {
13979         SourceLocation Loc = MemExpr->getMemberLoc();
13980         if (MemExpr->getQualifier())
13981           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13982         Base =
13983             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
13984       }
13985     } else
13986       Base = MemExpr->getBase();
13987 
13988     ExprValueKind valueKind;
13989     QualType type;
13990     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13991       valueKind = VK_LValue;
13992       type = Fn->getType();
13993     } else {
13994       valueKind = VK_RValue;
13995       type = Context.BoundMemberTy;
13996     }
13997 
13998     return BuildMemberExpr(
13999         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14000         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14001         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14002         type, valueKind, OK_Ordinary, TemplateArgs);
14003   }
14004 
14005   llvm_unreachable("Invalid reference to overloaded function");
14006 }
14007 
14008 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14009                                                 DeclAccessPair Found,
14010                                                 FunctionDecl *Fn) {
14011   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14012 }
14013