1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_OCL_Scalar_Widening,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isMemberPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_IncompletePack:
632     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633   case Sema::TDK_Inconsistent:
634   case Sema::TDK_Underqualified: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637     Saved->Param = Info.Param;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Result.Data = Saved;
641     break;
642   }
643 
644   case Sema::TDK_SubstitutionFailure:
645     Result.Data = Info.take();
646     if (Info.hasSFINAEDiagnostic()) {
647       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
648           SourceLocation(), PartialDiagnostic::NullDiagnostic());
649       Info.takeSFINAEDiagnostic(*Diag);
650       Result.HasDiagnostic = true;
651     }
652     break;
653 
654   case Sema::TDK_Success:
655   case Sema::TDK_NonDependentConversionFailure:
656     llvm_unreachable("not a deduction failure");
657   }
658 
659   return Result;
660 }
661 
662 void DeductionFailureInfo::Destroy() {
663   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664   case Sema::TDK_Success:
665   case Sema::TDK_Invalid:
666   case Sema::TDK_InstantiationDepth:
667   case Sema::TDK_Incomplete:
668   case Sema::TDK_TooManyArguments:
669   case Sema::TDK_TooFewArguments:
670   case Sema::TDK_InvalidExplicitArguments:
671   case Sema::TDK_CUDATargetMismatch:
672   case Sema::TDK_NonDependentConversionFailure:
673     break;
674 
675   case Sema::TDK_IncompletePack:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_DeducedMismatch:
679   case Sema::TDK_DeducedMismatchNested:
680   case Sema::TDK_NonDeducedMismatch:
681     // FIXME: Destroy the data?
682     Data = nullptr;
683     break;
684 
685   case Sema::TDK_SubstitutionFailure:
686     // FIXME: Destroy the template argument list?
687     Data = nullptr;
688     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689       Diag->~PartialDiagnosticAt();
690       HasDiagnostic = false;
691     }
692     break;
693 
694   // Unhandled
695   case Sema::TDK_MiscellaneousDeductionFailure:
696     break;
697   }
698 }
699 
700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701   if (HasDiagnostic)
702     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703   return nullptr;
704 }
705 
706 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708   case Sema::TDK_Success:
709   case Sema::TDK_Invalid:
710   case Sema::TDK_InstantiationDepth:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_SubstitutionFailure:
714   case Sema::TDK_DeducedMismatch:
715   case Sema::TDK_DeducedMismatchNested:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     return TemplateParameter();
720 
721   case Sema::TDK_Incomplete:
722   case Sema::TDK_InvalidExplicitArguments:
723     return TemplateParameter::getFromOpaqueValue(Data);
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728     return static_cast<DFIParamWithArguments*>(Data)->Param;
729 
730   // Unhandled
731   case Sema::TDK_MiscellaneousDeductionFailure:
732     break;
733   }
734 
735   return TemplateParameter();
736 }
737 
738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740   case Sema::TDK_Success:
741   case Sema::TDK_Invalid:
742   case Sema::TDK_InstantiationDepth:
743   case Sema::TDK_TooManyArguments:
744   case Sema::TDK_TooFewArguments:
745   case Sema::TDK_Incomplete:
746   case Sema::TDK_IncompletePack:
747   case Sema::TDK_InvalidExplicitArguments:
748   case Sema::TDK_Inconsistent:
749   case Sema::TDK_Underqualified:
750   case Sema::TDK_NonDeducedMismatch:
751   case Sema::TDK_CUDATargetMismatch:
752   case Sema::TDK_NonDependentConversionFailure:
753     return nullptr;
754 
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758 
759   case Sema::TDK_SubstitutionFailure:
760     return static_cast<TemplateArgumentList*>(Data);
761 
762   // Unhandled
763   case Sema::TDK_MiscellaneousDeductionFailure:
764     break;
765   }
766 
767   return nullptr;
768 }
769 
770 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772   case Sema::TDK_Success:
773   case Sema::TDK_Invalid:
774   case Sema::TDK_InstantiationDepth:
775   case Sema::TDK_Incomplete:
776   case Sema::TDK_TooManyArguments:
777   case Sema::TDK_TooFewArguments:
778   case Sema::TDK_InvalidExplicitArguments:
779   case Sema::TDK_SubstitutionFailure:
780   case Sema::TDK_CUDATargetMismatch:
781   case Sema::TDK_NonDependentConversionFailure:
782     return nullptr;
783 
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_Inconsistent:
786   case Sema::TDK_Underqualified:
787   case Sema::TDK_DeducedMismatch:
788   case Sema::TDK_DeducedMismatchNested:
789   case Sema::TDK_NonDeducedMismatch:
790     return &static_cast<DFIArguments*>(Data)->FirstArg;
791 
792   // Unhandled
793   case Sema::TDK_MiscellaneousDeductionFailure:
794     break;
795   }
796 
797   return nullptr;
798 }
799 
800 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_Incomplete:
806   case Sema::TDK_IncompletePack:
807   case Sema::TDK_TooManyArguments:
808   case Sema::TDK_TooFewArguments:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_SubstitutionFailure:
811   case Sema::TDK_CUDATargetMismatch:
812   case Sema::TDK_NonDependentConversionFailure:
813     return nullptr;
814 
815   case Sema::TDK_Inconsistent:
816   case Sema::TDK_Underqualified:
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819   case Sema::TDK_NonDeducedMismatch:
820     return &static_cast<DFIArguments*>(Data)->SecondArg;
821 
822   // Unhandled
823   case Sema::TDK_MiscellaneousDeductionFailure:
824     break;
825   }
826 
827   return nullptr;
828 }
829 
830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
831   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835 
836   default:
837     return llvm::None;
838   }
839 }
840 
841 void OverloadCandidateSet::destroyCandidates() {
842   for (iterator i = begin(), e = end(); i != e; ++i) {
843     for (auto &C : i->Conversions)
844       C.~ImplicitConversionSequence();
845     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
846       i->DeductionFailure.Destroy();
847   }
848 }
849 
850 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851   destroyCandidates();
852   SlabAllocator.Reset();
853   NumInlineBytesUsed = 0;
854   Candidates.clear();
855   Functions.clear();
856   Kind = CSK;
857 }
858 
859 namespace {
860   class UnbridgedCastsSet {
861     struct Entry {
862       Expr **Addr;
863       Expr *Saved;
864     };
865     SmallVector<Entry, 2> Entries;
866 
867   public:
868     void save(Sema &S, Expr *&E) {
869       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870       Entry entry = { &E, E };
871       Entries.push_back(entry);
872       E = S.stripARCUnbridgedCast(E);
873     }
874 
875     void restore() {
876       for (SmallVectorImpl<Entry>::iterator
877              i = Entries.begin(), e = Entries.end(); i != e; ++i)
878         *i->Addr = i->Saved;
879     }
880   };
881 }
882 
883 /// checkPlaceholderForOverload - Do any interesting placeholder-like
884 /// preprocessing on the given expression.
885 ///
886 /// \param unbridgedCasts a collection to which to add unbridged casts;
887 ///   without this, they will be immediately diagnosed as errors
888 ///
889 /// Return true on unrecoverable error.
890 static bool
891 checkPlaceholderForOverload(Sema &S, Expr *&E,
892                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
893   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894     // We can't handle overloaded expressions here because overload
895     // resolution might reasonably tweak them.
896     if (placeholder->getKind() == BuiltinType::Overload) return false;
897 
898     // If the context potentially accepts unbridged ARC casts, strip
899     // the unbridged cast and add it to the collection for later restoration.
900     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901         unbridgedCasts) {
902       unbridgedCasts->save(S, E);
903       return false;
904     }
905 
906     // Go ahead and check everything else.
907     ExprResult result = S.CheckPlaceholderExpr(E);
908     if (result.isInvalid())
909       return true;
910 
911     E = result.get();
912     return false;
913   }
914 
915   // Nothing to do.
916   return false;
917 }
918 
919 /// checkArgPlaceholdersForOverload - Check a set of call operands for
920 /// placeholders.
921 static bool checkArgPlaceholdersForOverload(Sema &S,
922                                             MultiExprArg Args,
923                                             UnbridgedCastsSet &unbridged) {
924   for (unsigned i = 0, e = Args.size(); i != e; ++i)
925     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926       return true;
927 
928   return false;
929 }
930 
931 /// Determine whether the given New declaration is an overload of the
932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933 /// New and Old cannot be overloaded, e.g., if New has the same signature as
934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935 /// functions (or function templates) at all. When it does return Ovl_Match or
936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938 /// declaration.
939 ///
940 /// Example: Given the following input:
941 ///
942 ///   void f(int, float); // #1
943 ///   void f(int, int); // #2
944 ///   int f(int, int); // #3
945 ///
946 /// When we process #1, there is no previous declaration of "f", so IsOverload
947 /// will not be used.
948 ///
949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950 /// the parameter types, we see that #1 and #2 are overloaded (since they have
951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952 /// unchanged.
953 ///
954 /// When we process #3, Old is an overload set containing #1 and #2. We compare
955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957 /// functions are not part of the signature), IsOverload returns Ovl_Match and
958 /// MatchedDecl will be set to point to the FunctionDecl for #2.
959 ///
960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961 /// by a using declaration. The rules for whether to hide shadow declarations
962 /// ignore some properties which otherwise figure into a function template's
963 /// signature.
964 Sema::OverloadKind
965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
966                     NamedDecl *&Match, bool NewIsUsingDecl) {
967   for (LookupResult::iterator I = Old.begin(), E = Old.end();
968          I != E; ++I) {
969     NamedDecl *OldD = *I;
970 
971     bool OldIsUsingDecl = false;
972     if (isa<UsingShadowDecl>(OldD)) {
973       OldIsUsingDecl = true;
974 
975       // We can always introduce two using declarations into the same
976       // context, even if they have identical signatures.
977       if (NewIsUsingDecl) continue;
978 
979       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980     }
981 
982     // A using-declaration does not conflict with another declaration
983     // if one of them is hidden.
984     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985       continue;
986 
987     // If either declaration was introduced by a using declaration,
988     // we'll need to use slightly different rules for matching.
989     // Essentially, these rules are the normal rules, except that
990     // function templates hide function templates with different
991     // return types or template parameter lists.
992     bool UseMemberUsingDeclRules =
993       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
994       !New->getFriendObjectKind();
995 
996     if (FunctionDecl *OldF = OldD->getAsFunction()) {
997       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
998         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
999           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000           continue;
1001         }
1002 
1003         if (!isa<FunctionTemplateDecl>(OldD) &&
1004             !shouldLinkPossiblyHiddenDecl(*I, New))
1005           continue;
1006 
1007         Match = *I;
1008         return Ovl_Match;
1009       }
1010 
1011       // Builtins that have custom typechecking or have a reference should
1012       // not be overloadable or redeclarable.
1013       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1018       // We can overload with these, which can show up when doing
1019       // redeclaration checks for UsingDecls.
1020       assert(Old.getLookupKind() == LookupUsingDeclName);
1021     } else if (isa<TagDecl>(OldD)) {
1022       // We can always overload with tags by hiding them.
1023     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024       // Optimistically assume that an unresolved using decl will
1025       // overload; if it doesn't, we'll have to diagnose during
1026       // template instantiation.
1027       //
1028       // Exception: if the scope is dependent and this is not a class
1029       // member, the using declaration can only introduce an enumerator.
1030       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031         Match = *I;
1032         return Ovl_NonFunction;
1033       }
1034     } else {
1035       // (C++ 13p1):
1036       //   Only function declarations can be overloaded; object and type
1037       //   declarations cannot be overloaded.
1038       Match = *I;
1039       return Ovl_NonFunction;
1040     }
1041   }
1042 
1043   // C++ [temp.friend]p1:
1044   //   For a friend function declaration that is not a template declaration:
1045   //    -- if the name of the friend is a qualified or unqualified template-id,
1046   //       [...], otherwise
1047   //    -- if the name of the friend is a qualified-id and a matching
1048   //       non-template function is found in the specified class or namespace,
1049   //       the friend declaration refers to that function, otherwise,
1050   //    -- if the name of the friend is a qualified-id and a matching function
1051   //       template is found in the specified class or namespace, the friend
1052   //       declaration refers to the deduced specialization of that function
1053   //       template, otherwise
1054   //    -- the name shall be an unqualified-id [...]
1055   // If we get here for a qualified friend declaration, we've just reached the
1056   // third bullet. If the type of the friend is dependent, skip this lookup
1057   // until instantiation.
1058   if (New->getFriendObjectKind() && New->getQualifier() &&
1059       !New->getDependentSpecializationInfo() &&
1060       !New->getType()->isDependentType()) {
1061     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1062     TemplateSpecResult.addAllDecls(Old);
1063     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1064                                             /*QualifiedFriend*/true)) {
1065       New->setInvalidDecl();
1066       return Ovl_Overload;
1067     }
1068 
1069     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1070     return Ovl_Match;
1071   }
1072 
1073   return Ovl_Overload;
1074 }
1075 
1076 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1077                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1078   // C++ [basic.start.main]p2: This function shall not be overloaded.
1079   if (New->isMain())
1080     return false;
1081 
1082   // MSVCRT user defined entry points cannot be overloaded.
1083   if (New->isMSVCRTEntryPoint())
1084     return false;
1085 
1086   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1087   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1088 
1089   // C++ [temp.fct]p2:
1090   //   A function template can be overloaded with other function templates
1091   //   and with normal (non-template) functions.
1092   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1093     return true;
1094 
1095   // Is the function New an overload of the function Old?
1096   QualType OldQType = Context.getCanonicalType(Old->getType());
1097   QualType NewQType = Context.getCanonicalType(New->getType());
1098 
1099   // Compare the signatures (C++ 1.3.10) of the two functions to
1100   // determine whether they are overloads. If we find any mismatch
1101   // in the signature, they are overloads.
1102 
1103   // If either of these functions is a K&R-style function (no
1104   // prototype), then we consider them to have matching signatures.
1105   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1106       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1107     return false;
1108 
1109   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1110   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1111 
1112   // The signature of a function includes the types of its
1113   // parameters (C++ 1.3.10), which includes the presence or absence
1114   // of the ellipsis; see C++ DR 357).
1115   if (OldQType != NewQType &&
1116       (OldType->getNumParams() != NewType->getNumParams() ||
1117        OldType->isVariadic() != NewType->isVariadic() ||
1118        !FunctionParamTypesAreEqual(OldType, NewType)))
1119     return true;
1120 
1121   // C++ [temp.over.link]p4:
1122   //   The signature of a function template consists of its function
1123   //   signature, its return type and its template parameter list. The names
1124   //   of the template parameters are significant only for establishing the
1125   //   relationship between the template parameters and the rest of the
1126   //   signature.
1127   //
1128   // We check the return type and template parameter lists for function
1129   // templates first; the remaining checks follow.
1130   //
1131   // However, we don't consider either of these when deciding whether
1132   // a member introduced by a shadow declaration is hidden.
1133   if (!UseMemberUsingDeclRules && NewTemplate &&
1134       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1135                                        OldTemplate->getTemplateParameters(),
1136                                        false, TPL_TemplateMatch) ||
1137        !Context.hasSameType(Old->getDeclaredReturnType(),
1138                             New->getDeclaredReturnType())))
1139     return true;
1140 
1141   // If the function is a class member, its signature includes the
1142   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1143   //
1144   // As part of this, also check whether one of the member functions
1145   // is static, in which case they are not overloads (C++
1146   // 13.1p2). While not part of the definition of the signature,
1147   // this check is important to determine whether these functions
1148   // can be overloaded.
1149   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1150   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1151   if (OldMethod && NewMethod &&
1152       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1153     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1154       if (!UseMemberUsingDeclRules &&
1155           (OldMethod->getRefQualifier() == RQ_None ||
1156            NewMethod->getRefQualifier() == RQ_None)) {
1157         // C++0x [over.load]p2:
1158         //   - Member function declarations with the same name and the same
1159         //     parameter-type-list as well as member function template
1160         //     declarations with the same name, the same parameter-type-list, and
1161         //     the same template parameter lists cannot be overloaded if any of
1162         //     them, but not all, have a ref-qualifier (8.3.5).
1163         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1164           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1165         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1166       }
1167       return true;
1168     }
1169 
1170     // We may not have applied the implicit const for a constexpr member
1171     // function yet (because we haven't yet resolved whether this is a static
1172     // or non-static member function). Add it now, on the assumption that this
1173     // is a redeclaration of OldMethod.
1174     auto OldQuals = OldMethod->getMethodQualifiers();
1175     auto NewQuals = NewMethod->getMethodQualifiers();
1176     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1177         !isa<CXXConstructorDecl>(NewMethod))
1178       NewQuals.addConst();
1179     // We do not allow overloading based off of '__restrict'.
1180     OldQuals.removeRestrict();
1181     NewQuals.removeRestrict();
1182     if (OldQuals != NewQuals)
1183       return true;
1184   }
1185 
1186   // Though pass_object_size is placed on parameters and takes an argument, we
1187   // consider it to be a function-level modifier for the sake of function
1188   // identity. Either the function has one or more parameters with
1189   // pass_object_size or it doesn't.
1190   if (functionHasPassObjectSizeParams(New) !=
1191       functionHasPassObjectSizeParams(Old))
1192     return true;
1193 
1194   // enable_if attributes are an order-sensitive part of the signature.
1195   for (specific_attr_iterator<EnableIfAttr>
1196          NewI = New->specific_attr_begin<EnableIfAttr>(),
1197          NewE = New->specific_attr_end<EnableIfAttr>(),
1198          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1199          OldE = Old->specific_attr_end<EnableIfAttr>();
1200        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1201     if (NewI == NewE || OldI == OldE)
1202       return true;
1203     llvm::FoldingSetNodeID NewID, OldID;
1204     NewI->getCond()->Profile(NewID, Context, true);
1205     OldI->getCond()->Profile(OldID, Context, true);
1206     if (NewID != OldID)
1207       return true;
1208   }
1209 
1210   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1211     // Don't allow overloading of destructors.  (In theory we could, but it
1212     // would be a giant change to clang.)
1213     if (isa<CXXDestructorDecl>(New))
1214       return false;
1215 
1216     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1217                        OldTarget = IdentifyCUDATarget(Old);
1218     if (NewTarget == CFT_InvalidTarget)
1219       return false;
1220 
1221     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1222 
1223     // Allow overloading of functions with same signature and different CUDA
1224     // target attributes.
1225     return NewTarget != OldTarget;
1226   }
1227 
1228   // The signatures match; this is not an overload.
1229   return false;
1230 }
1231 
1232 /// Tries a user-defined conversion from From to ToType.
1233 ///
1234 /// Produces an implicit conversion sequence for when a standard conversion
1235 /// is not an option. See TryImplicitConversion for more information.
1236 static ImplicitConversionSequence
1237 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1238                          bool SuppressUserConversions,
1239                          bool AllowExplicit,
1240                          bool InOverloadResolution,
1241                          bool CStyle,
1242                          bool AllowObjCWritebackConversion,
1243                          bool AllowObjCConversionOnExplicit) {
1244   ImplicitConversionSequence ICS;
1245 
1246   if (SuppressUserConversions) {
1247     // We're not in the case above, so there is no conversion that
1248     // we can perform.
1249     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1250     return ICS;
1251   }
1252 
1253   // Attempt user-defined conversion.
1254   OverloadCandidateSet Conversions(From->getExprLoc(),
1255                                    OverloadCandidateSet::CSK_Normal);
1256   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1257                                   Conversions, AllowExplicit,
1258                                   AllowObjCConversionOnExplicit)) {
1259   case OR_Success:
1260   case OR_Deleted:
1261     ICS.setUserDefined();
1262     // C++ [over.ics.user]p4:
1263     //   A conversion of an expression of class type to the same class
1264     //   type is given Exact Match rank, and a conversion of an
1265     //   expression of class type to a base class of that type is
1266     //   given Conversion rank, in spite of the fact that a copy
1267     //   constructor (i.e., a user-defined conversion function) is
1268     //   called for those cases.
1269     if (CXXConstructorDecl *Constructor
1270           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1271       QualType FromCanon
1272         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1273       QualType ToCanon
1274         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1275       if (Constructor->isCopyConstructor() &&
1276           (FromCanon == ToCanon ||
1277            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1278         // Turn this into a "standard" conversion sequence, so that it
1279         // gets ranked with standard conversion sequences.
1280         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1281         ICS.setStandard();
1282         ICS.Standard.setAsIdentityConversion();
1283         ICS.Standard.setFromType(From->getType());
1284         ICS.Standard.setAllToTypes(ToType);
1285         ICS.Standard.CopyConstructor = Constructor;
1286         ICS.Standard.FoundCopyConstructor = Found;
1287         if (ToCanon != FromCanon)
1288           ICS.Standard.Second = ICK_Derived_To_Base;
1289       }
1290     }
1291     break;
1292 
1293   case OR_Ambiguous:
1294     ICS.setAmbiguous();
1295     ICS.Ambiguous.setFromType(From->getType());
1296     ICS.Ambiguous.setToType(ToType);
1297     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1298          Cand != Conversions.end(); ++Cand)
1299       if (Cand->Viable)
1300         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1301     break;
1302 
1303     // Fall through.
1304   case OR_No_Viable_Function:
1305     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1306     break;
1307   }
1308 
1309   return ICS;
1310 }
1311 
1312 /// TryImplicitConversion - Attempt to perform an implicit conversion
1313 /// from the given expression (Expr) to the given type (ToType). This
1314 /// function returns an implicit conversion sequence that can be used
1315 /// to perform the initialization. Given
1316 ///
1317 ///   void f(float f);
1318 ///   void g(int i) { f(i); }
1319 ///
1320 /// this routine would produce an implicit conversion sequence to
1321 /// describe the initialization of f from i, which will be a standard
1322 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1323 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1324 //
1325 /// Note that this routine only determines how the conversion can be
1326 /// performed; it does not actually perform the conversion. As such,
1327 /// it will not produce any diagnostics if no conversion is available,
1328 /// but will instead return an implicit conversion sequence of kind
1329 /// "BadConversion".
1330 ///
1331 /// If @p SuppressUserConversions, then user-defined conversions are
1332 /// not permitted.
1333 /// If @p AllowExplicit, then explicit user-defined conversions are
1334 /// permitted.
1335 ///
1336 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1337 /// writeback conversion, which allows __autoreleasing id* parameters to
1338 /// be initialized with __strong id* or __weak id* arguments.
1339 static ImplicitConversionSequence
1340 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1341                       bool SuppressUserConversions,
1342                       bool AllowExplicit,
1343                       bool InOverloadResolution,
1344                       bool CStyle,
1345                       bool AllowObjCWritebackConversion,
1346                       bool AllowObjCConversionOnExplicit) {
1347   ImplicitConversionSequence ICS;
1348   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1349                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1350     ICS.setStandard();
1351     return ICS;
1352   }
1353 
1354   if (!S.getLangOpts().CPlusPlus) {
1355     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1356     return ICS;
1357   }
1358 
1359   // C++ [over.ics.user]p4:
1360   //   A conversion of an expression of class type to the same class
1361   //   type is given Exact Match rank, and a conversion of an
1362   //   expression of class type to a base class of that type is
1363   //   given Conversion rank, in spite of the fact that a copy/move
1364   //   constructor (i.e., a user-defined conversion function) is
1365   //   called for those cases.
1366   QualType FromType = From->getType();
1367   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1368       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1369        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1370     ICS.setStandard();
1371     ICS.Standard.setAsIdentityConversion();
1372     ICS.Standard.setFromType(FromType);
1373     ICS.Standard.setAllToTypes(ToType);
1374 
1375     // We don't actually check at this point whether there is a valid
1376     // copy/move constructor, since overloading just assumes that it
1377     // exists. When we actually perform initialization, we'll find the
1378     // appropriate constructor to copy the returned object, if needed.
1379     ICS.Standard.CopyConstructor = nullptr;
1380 
1381     // Determine whether this is considered a derived-to-base conversion.
1382     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1383       ICS.Standard.Second = ICK_Derived_To_Base;
1384 
1385     return ICS;
1386   }
1387 
1388   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1389                                   AllowExplicit, InOverloadResolution, CStyle,
1390                                   AllowObjCWritebackConversion,
1391                                   AllowObjCConversionOnExplicit);
1392 }
1393 
1394 ImplicitConversionSequence
1395 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1396                             bool SuppressUserConversions,
1397                             bool AllowExplicit,
1398                             bool InOverloadResolution,
1399                             bool CStyle,
1400                             bool AllowObjCWritebackConversion) {
1401   return ::TryImplicitConversion(*this, From, ToType,
1402                                  SuppressUserConversions, AllowExplicit,
1403                                  InOverloadResolution, CStyle,
1404                                  AllowObjCWritebackConversion,
1405                                  /*AllowObjCConversionOnExplicit=*/false);
1406 }
1407 
1408 /// PerformImplicitConversion - Perform an implicit conversion of the
1409 /// expression From to the type ToType. Returns the
1410 /// converted expression. Flavor is the kind of conversion we're
1411 /// performing, used in the error message. If @p AllowExplicit,
1412 /// explicit user-defined conversions are permitted.
1413 ExprResult
1414 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1415                                 AssignmentAction Action, bool AllowExplicit) {
1416   ImplicitConversionSequence ICS;
1417   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1418 }
1419 
1420 ExprResult
1421 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1422                                 AssignmentAction Action, bool AllowExplicit,
1423                                 ImplicitConversionSequence& ICS) {
1424   if (checkPlaceholderForOverload(*this, From))
1425     return ExprError();
1426 
1427   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1428   bool AllowObjCWritebackConversion
1429     = getLangOpts().ObjCAutoRefCount &&
1430       (Action == AA_Passing || Action == AA_Sending);
1431   if (getLangOpts().ObjC)
1432     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1433                                       From->getType(), From);
1434   ICS = ::TryImplicitConversion(*this, From, ToType,
1435                                 /*SuppressUserConversions=*/false,
1436                                 AllowExplicit,
1437                                 /*InOverloadResolution=*/false,
1438                                 /*CStyle=*/false,
1439                                 AllowObjCWritebackConversion,
1440                                 /*AllowObjCConversionOnExplicit=*/false);
1441   return PerformImplicitConversion(From, ToType, ICS, Action);
1442 }
1443 
1444 /// Determine whether the conversion from FromType to ToType is a valid
1445 /// conversion that strips "noexcept" or "noreturn" off the nested function
1446 /// type.
1447 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1448                                 QualType &ResultTy) {
1449   if (Context.hasSameUnqualifiedType(FromType, ToType))
1450     return false;
1451 
1452   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1453   //                    or F(t noexcept) -> F(t)
1454   // where F adds one of the following at most once:
1455   //   - a pointer
1456   //   - a member pointer
1457   //   - a block pointer
1458   // Changes here need matching changes in FindCompositePointerType.
1459   CanQualType CanTo = Context.getCanonicalType(ToType);
1460   CanQualType CanFrom = Context.getCanonicalType(FromType);
1461   Type::TypeClass TyClass = CanTo->getTypeClass();
1462   if (TyClass != CanFrom->getTypeClass()) return false;
1463   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1464     if (TyClass == Type::Pointer) {
1465       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1466       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1467     } else if (TyClass == Type::BlockPointer) {
1468       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1469       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1470     } else if (TyClass == Type::MemberPointer) {
1471       auto ToMPT = CanTo.getAs<MemberPointerType>();
1472       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1473       // A function pointer conversion cannot change the class of the function.
1474       if (ToMPT->getClass() != FromMPT->getClass())
1475         return false;
1476       CanTo = ToMPT->getPointeeType();
1477       CanFrom = FromMPT->getPointeeType();
1478     } else {
1479       return false;
1480     }
1481 
1482     TyClass = CanTo->getTypeClass();
1483     if (TyClass != CanFrom->getTypeClass()) return false;
1484     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1485       return false;
1486   }
1487 
1488   const auto *FromFn = cast<FunctionType>(CanFrom);
1489   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1490 
1491   const auto *ToFn = cast<FunctionType>(CanTo);
1492   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1493 
1494   bool Changed = false;
1495 
1496   // Drop 'noreturn' if not present in target type.
1497   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1498     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1499     Changed = true;
1500   }
1501 
1502   // Drop 'noexcept' if not present in target type.
1503   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1504     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1505     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1506       FromFn = cast<FunctionType>(
1507           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1508                                                    EST_None)
1509                  .getTypePtr());
1510       Changed = true;
1511     }
1512 
1513     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1514     // only if the ExtParameterInfo lists of the two function prototypes can be
1515     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1516     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1517     bool CanUseToFPT, CanUseFromFPT;
1518     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1519                                       CanUseFromFPT, NewParamInfos) &&
1520         CanUseToFPT && !CanUseFromFPT) {
1521       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1522       ExtInfo.ExtParameterInfos =
1523           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1524       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1525                                             FromFPT->getParamTypes(), ExtInfo);
1526       FromFn = QT->getAs<FunctionType>();
1527       Changed = true;
1528     }
1529   }
1530 
1531   if (!Changed)
1532     return false;
1533 
1534   assert(QualType(FromFn, 0).isCanonical());
1535   if (QualType(FromFn, 0) != CanTo) return false;
1536 
1537   ResultTy = ToType;
1538   return true;
1539 }
1540 
1541 /// Determine whether the conversion from FromType to ToType is a valid
1542 /// vector conversion.
1543 ///
1544 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1545 /// conversion.
1546 static bool IsVectorConversion(Sema &S, QualType FromType,
1547                                QualType ToType, ImplicitConversionKind &ICK) {
1548   // We need at least one of these types to be a vector type to have a vector
1549   // conversion.
1550   if (!ToType->isVectorType() && !FromType->isVectorType())
1551     return false;
1552 
1553   // Identical types require no conversions.
1554   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1555     return false;
1556 
1557   // There are no conversions between extended vector types, only identity.
1558   if (ToType->isExtVectorType()) {
1559     // There are no conversions between extended vector types other than the
1560     // identity conversion.
1561     if (FromType->isExtVectorType())
1562       return false;
1563 
1564     // Vector splat from any arithmetic type to a vector.
1565     if (FromType->isArithmeticType()) {
1566       ICK = ICK_Vector_Splat;
1567       return true;
1568     }
1569   }
1570 
1571   // We can perform the conversion between vector types in the following cases:
1572   // 1)vector types are equivalent AltiVec and GCC vector types
1573   // 2)lax vector conversions are permitted and the vector types are of the
1574   //   same size
1575   if (ToType->isVectorType() && FromType->isVectorType()) {
1576     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1577         S.isLaxVectorConversion(FromType, ToType)) {
1578       ICK = ICK_Vector_Conversion;
1579       return true;
1580     }
1581   }
1582 
1583   return false;
1584 }
1585 
1586 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1587                                 bool InOverloadResolution,
1588                                 StandardConversionSequence &SCS,
1589                                 bool CStyle);
1590 
1591 /// IsStandardConversion - Determines whether there is a standard
1592 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1593 /// expression From to the type ToType. Standard conversion sequences
1594 /// only consider non-class types; for conversions that involve class
1595 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1596 /// contain the standard conversion sequence required to perform this
1597 /// conversion and this routine will return true. Otherwise, this
1598 /// routine will return false and the value of SCS is unspecified.
1599 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1600                                  bool InOverloadResolution,
1601                                  StandardConversionSequence &SCS,
1602                                  bool CStyle,
1603                                  bool AllowObjCWritebackConversion) {
1604   QualType FromType = From->getType();
1605 
1606   // Standard conversions (C++ [conv])
1607   SCS.setAsIdentityConversion();
1608   SCS.IncompatibleObjC = false;
1609   SCS.setFromType(FromType);
1610   SCS.CopyConstructor = nullptr;
1611 
1612   // There are no standard conversions for class types in C++, so
1613   // abort early. When overloading in C, however, we do permit them.
1614   if (S.getLangOpts().CPlusPlus &&
1615       (FromType->isRecordType() || ToType->isRecordType()))
1616     return false;
1617 
1618   // The first conversion can be an lvalue-to-rvalue conversion,
1619   // array-to-pointer conversion, or function-to-pointer conversion
1620   // (C++ 4p1).
1621 
1622   if (FromType == S.Context.OverloadTy) {
1623     DeclAccessPair AccessPair;
1624     if (FunctionDecl *Fn
1625           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1626                                                  AccessPair)) {
1627       // We were able to resolve the address of the overloaded function,
1628       // so we can convert to the type of that function.
1629       FromType = Fn->getType();
1630       SCS.setFromType(FromType);
1631 
1632       // we can sometimes resolve &foo<int> regardless of ToType, so check
1633       // if the type matches (identity) or we are converting to bool
1634       if (!S.Context.hasSameUnqualifiedType(
1635                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1636         QualType resultTy;
1637         // if the function type matches except for [[noreturn]], it's ok
1638         if (!S.IsFunctionConversion(FromType,
1639               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1640           // otherwise, only a boolean conversion is standard
1641           if (!ToType->isBooleanType())
1642             return false;
1643       }
1644 
1645       // Check if the "from" expression is taking the address of an overloaded
1646       // function and recompute the FromType accordingly. Take advantage of the
1647       // fact that non-static member functions *must* have such an address-of
1648       // expression.
1649       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1650       if (Method && !Method->isStatic()) {
1651         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1652                "Non-unary operator on non-static member address");
1653         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1654                == UO_AddrOf &&
1655                "Non-address-of operator on non-static member address");
1656         const Type *ClassType
1657           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1658         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1659       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1660         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1661                UO_AddrOf &&
1662                "Non-address-of operator for overloaded function expression");
1663         FromType = S.Context.getPointerType(FromType);
1664       }
1665 
1666       // Check that we've computed the proper type after overload resolution.
1667       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1668       // be calling it from within an NDEBUG block.
1669       assert(S.Context.hasSameType(
1670         FromType,
1671         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1672     } else {
1673       return false;
1674     }
1675   }
1676   // Lvalue-to-rvalue conversion (C++11 4.1):
1677   //   A glvalue (3.10) of a non-function, non-array type T can
1678   //   be converted to a prvalue.
1679   bool argIsLValue = From->isGLValue();
1680   if (argIsLValue &&
1681       !FromType->isFunctionType() && !FromType->isArrayType() &&
1682       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1683     SCS.First = ICK_Lvalue_To_Rvalue;
1684 
1685     // C11 6.3.2.1p2:
1686     //   ... if the lvalue has atomic type, the value has the non-atomic version
1687     //   of the type of the lvalue ...
1688     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1689       FromType = Atomic->getValueType();
1690 
1691     // If T is a non-class type, the type of the rvalue is the
1692     // cv-unqualified version of T. Otherwise, the type of the rvalue
1693     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1694     // just strip the qualifiers because they don't matter.
1695     FromType = FromType.getUnqualifiedType();
1696   } else if (FromType->isArrayType()) {
1697     // Array-to-pointer conversion (C++ 4.2)
1698     SCS.First = ICK_Array_To_Pointer;
1699 
1700     // An lvalue or rvalue of type "array of N T" or "array of unknown
1701     // bound of T" can be converted to an rvalue of type "pointer to
1702     // T" (C++ 4.2p1).
1703     FromType = S.Context.getArrayDecayedType(FromType);
1704 
1705     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1706       // This conversion is deprecated in C++03 (D.4)
1707       SCS.DeprecatedStringLiteralToCharPtr = true;
1708 
1709       // For the purpose of ranking in overload resolution
1710       // (13.3.3.1.1), this conversion is considered an
1711       // array-to-pointer conversion followed by a qualification
1712       // conversion (4.4). (C++ 4.2p2)
1713       SCS.Second = ICK_Identity;
1714       SCS.Third = ICK_Qualification;
1715       SCS.QualificationIncludesObjCLifetime = false;
1716       SCS.setAllToTypes(FromType);
1717       return true;
1718     }
1719   } else if (FromType->isFunctionType() && argIsLValue) {
1720     // Function-to-pointer conversion (C++ 4.3).
1721     SCS.First = ICK_Function_To_Pointer;
1722 
1723     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1724       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1725         if (!S.checkAddressOfFunctionIsAvailable(FD))
1726           return false;
1727 
1728     // An lvalue of function type T can be converted to an rvalue of
1729     // type "pointer to T." The result is a pointer to the
1730     // function. (C++ 4.3p1).
1731     FromType = S.Context.getPointerType(FromType);
1732   } else {
1733     // We don't require any conversions for the first step.
1734     SCS.First = ICK_Identity;
1735   }
1736   SCS.setToType(0, FromType);
1737 
1738   // The second conversion can be an integral promotion, floating
1739   // point promotion, integral conversion, floating point conversion,
1740   // floating-integral conversion, pointer conversion,
1741   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1742   // For overloading in C, this can also be a "compatible-type"
1743   // conversion.
1744   bool IncompatibleObjC = false;
1745   ImplicitConversionKind SecondICK = ICK_Identity;
1746   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1747     // The unqualified versions of the types are the same: there's no
1748     // conversion to do.
1749     SCS.Second = ICK_Identity;
1750   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1751     // Integral promotion (C++ 4.5).
1752     SCS.Second = ICK_Integral_Promotion;
1753     FromType = ToType.getUnqualifiedType();
1754   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1755     // Floating point promotion (C++ 4.6).
1756     SCS.Second = ICK_Floating_Promotion;
1757     FromType = ToType.getUnqualifiedType();
1758   } else if (S.IsComplexPromotion(FromType, ToType)) {
1759     // Complex promotion (Clang extension)
1760     SCS.Second = ICK_Complex_Promotion;
1761     FromType = ToType.getUnqualifiedType();
1762   } else if (ToType->isBooleanType() &&
1763              (FromType->isArithmeticType() ||
1764               FromType->isAnyPointerType() ||
1765               FromType->isBlockPointerType() ||
1766               FromType->isMemberPointerType() ||
1767               FromType->isNullPtrType())) {
1768     // Boolean conversions (C++ 4.12).
1769     SCS.Second = ICK_Boolean_Conversion;
1770     FromType = S.Context.BoolTy;
1771   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1772              ToType->isIntegralType(S.Context)) {
1773     // Integral conversions (C++ 4.7).
1774     SCS.Second = ICK_Integral_Conversion;
1775     FromType = ToType.getUnqualifiedType();
1776   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1777     // Complex conversions (C99 6.3.1.6)
1778     SCS.Second = ICK_Complex_Conversion;
1779     FromType = ToType.getUnqualifiedType();
1780   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1781              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1782     // Complex-real conversions (C99 6.3.1.7)
1783     SCS.Second = ICK_Complex_Real;
1784     FromType = ToType.getUnqualifiedType();
1785   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1786     // FIXME: disable conversions between long double and __float128 if
1787     // their representation is different until there is back end support
1788     // We of course allow this conversion if long double is really double.
1789     if (&S.Context.getFloatTypeSemantics(FromType) !=
1790         &S.Context.getFloatTypeSemantics(ToType)) {
1791       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1792                                     ToType == S.Context.LongDoubleTy) ||
1793                                    (FromType == S.Context.LongDoubleTy &&
1794                                     ToType == S.Context.Float128Ty));
1795       if (Float128AndLongDouble &&
1796           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1797            &llvm::APFloat::PPCDoubleDouble()))
1798         return false;
1799     }
1800     // Floating point conversions (C++ 4.8).
1801     SCS.Second = ICK_Floating_Conversion;
1802     FromType = ToType.getUnqualifiedType();
1803   } else if ((FromType->isRealFloatingType() &&
1804               ToType->isIntegralType(S.Context)) ||
1805              (FromType->isIntegralOrUnscopedEnumerationType() &&
1806               ToType->isRealFloatingType())) {
1807     // Floating-integral conversions (C++ 4.9).
1808     SCS.Second = ICK_Floating_Integral;
1809     FromType = ToType.getUnqualifiedType();
1810   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1811     SCS.Second = ICK_Block_Pointer_Conversion;
1812   } else if (AllowObjCWritebackConversion &&
1813              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1814     SCS.Second = ICK_Writeback_Conversion;
1815   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1816                                    FromType, IncompatibleObjC)) {
1817     // Pointer conversions (C++ 4.10).
1818     SCS.Second = ICK_Pointer_Conversion;
1819     SCS.IncompatibleObjC = IncompatibleObjC;
1820     FromType = FromType.getUnqualifiedType();
1821   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1822                                          InOverloadResolution, FromType)) {
1823     // Pointer to member conversions (4.11).
1824     SCS.Second = ICK_Pointer_Member;
1825   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1826     SCS.Second = SecondICK;
1827     FromType = ToType.getUnqualifiedType();
1828   } else if (!S.getLangOpts().CPlusPlus &&
1829              S.Context.typesAreCompatible(ToType, FromType)) {
1830     // Compatible conversions (Clang extension for C function overloading)
1831     SCS.Second = ICK_Compatible_Conversion;
1832     FromType = ToType.getUnqualifiedType();
1833   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1834                                              InOverloadResolution,
1835                                              SCS, CStyle)) {
1836     SCS.Second = ICK_TransparentUnionConversion;
1837     FromType = ToType;
1838   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1839                                  CStyle)) {
1840     // tryAtomicConversion has updated the standard conversion sequence
1841     // appropriately.
1842     return true;
1843   } else if (ToType->isEventT() &&
1844              From->isIntegerConstantExpr(S.getASTContext()) &&
1845              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1846     SCS.Second = ICK_Zero_Event_Conversion;
1847     FromType = ToType;
1848   } else if (ToType->isQueueT() &&
1849              From->isIntegerConstantExpr(S.getASTContext()) &&
1850              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1851     SCS.Second = ICK_Zero_Queue_Conversion;
1852     FromType = ToType;
1853   } else {
1854     // No second conversion required.
1855     SCS.Second = ICK_Identity;
1856   }
1857   SCS.setToType(1, FromType);
1858 
1859   // The third conversion can be a function pointer conversion or a
1860   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1861   bool ObjCLifetimeConversion;
1862   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1863     // Function pointer conversions (removing 'noexcept') including removal of
1864     // 'noreturn' (Clang extension).
1865     SCS.Third = ICK_Function_Conversion;
1866   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1867                                          ObjCLifetimeConversion)) {
1868     SCS.Third = ICK_Qualification;
1869     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1870     FromType = ToType;
1871   } else {
1872     // No conversion required
1873     SCS.Third = ICK_Identity;
1874   }
1875 
1876   // C++ [over.best.ics]p6:
1877   //   [...] Any difference in top-level cv-qualification is
1878   //   subsumed by the initialization itself and does not constitute
1879   //   a conversion. [...]
1880   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1881   QualType CanonTo = S.Context.getCanonicalType(ToType);
1882   if (CanonFrom.getLocalUnqualifiedType()
1883                                      == CanonTo.getLocalUnqualifiedType() &&
1884       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1885     FromType = ToType;
1886     CanonFrom = CanonTo;
1887   }
1888 
1889   SCS.setToType(2, FromType);
1890 
1891   if (CanonFrom == CanonTo)
1892     return true;
1893 
1894   // If we have not converted the argument type to the parameter type,
1895   // this is a bad conversion sequence, unless we're resolving an overload in C.
1896   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1897     return false;
1898 
1899   ExprResult ER = ExprResult{From};
1900   Sema::AssignConvertType Conv =
1901       S.CheckSingleAssignmentConstraints(ToType, ER,
1902                                          /*Diagnose=*/false,
1903                                          /*DiagnoseCFAudited=*/false,
1904                                          /*ConvertRHS=*/false);
1905   ImplicitConversionKind SecondConv;
1906   switch (Conv) {
1907   case Sema::Compatible:
1908     SecondConv = ICK_C_Only_Conversion;
1909     break;
1910   // For our purposes, discarding qualifiers is just as bad as using an
1911   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1912   // qualifiers, as well.
1913   case Sema::CompatiblePointerDiscardsQualifiers:
1914   case Sema::IncompatiblePointer:
1915   case Sema::IncompatiblePointerSign:
1916     SecondConv = ICK_Incompatible_Pointer_Conversion;
1917     break;
1918   default:
1919     return false;
1920   }
1921 
1922   // First can only be an lvalue conversion, so we pretend that this was the
1923   // second conversion. First should already be valid from earlier in the
1924   // function.
1925   SCS.Second = SecondConv;
1926   SCS.setToType(1, ToType);
1927 
1928   // Third is Identity, because Second should rank us worse than any other
1929   // conversion. This could also be ICK_Qualification, but it's simpler to just
1930   // lump everything in with the second conversion, and we don't gain anything
1931   // from making this ICK_Qualification.
1932   SCS.Third = ICK_Identity;
1933   SCS.setToType(2, ToType);
1934   return true;
1935 }
1936 
1937 static bool
1938 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1939                                      QualType &ToType,
1940                                      bool InOverloadResolution,
1941                                      StandardConversionSequence &SCS,
1942                                      bool CStyle) {
1943 
1944   const RecordType *UT = ToType->getAsUnionType();
1945   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1946     return false;
1947   // The field to initialize within the transparent union.
1948   RecordDecl *UD = UT->getDecl();
1949   // It's compatible if the expression matches any of the fields.
1950   for (const auto *it : UD->fields()) {
1951     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1952                              CStyle, /*ObjCWritebackConversion=*/false)) {
1953       ToType = it->getType();
1954       return true;
1955     }
1956   }
1957   return false;
1958 }
1959 
1960 /// IsIntegralPromotion - Determines whether the conversion from the
1961 /// expression From (whose potentially-adjusted type is FromType) to
1962 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1963 /// sets PromotedType to the promoted type.
1964 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1965   const BuiltinType *To = ToType->getAs<BuiltinType>();
1966   // All integers are built-in.
1967   if (!To) {
1968     return false;
1969   }
1970 
1971   // An rvalue of type char, signed char, unsigned char, short int, or
1972   // unsigned short int can be converted to an rvalue of type int if
1973   // int can represent all the values of the source type; otherwise,
1974   // the source rvalue can be converted to an rvalue of type unsigned
1975   // int (C++ 4.5p1).
1976   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1977       !FromType->isEnumeralType()) {
1978     if (// We can promote any signed, promotable integer type to an int
1979         (FromType->isSignedIntegerType() ||
1980          // We can promote any unsigned integer type whose size is
1981          // less than int to an int.
1982          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1983       return To->getKind() == BuiltinType::Int;
1984     }
1985 
1986     return To->getKind() == BuiltinType::UInt;
1987   }
1988 
1989   // C++11 [conv.prom]p3:
1990   //   A prvalue of an unscoped enumeration type whose underlying type is not
1991   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1992   //   following types that can represent all the values of the enumeration
1993   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1994   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1995   //   long long int. If none of the types in that list can represent all the
1996   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1997   //   type can be converted to an rvalue a prvalue of the extended integer type
1998   //   with lowest integer conversion rank (4.13) greater than the rank of long
1999   //   long in which all the values of the enumeration can be represented. If
2000   //   there are two such extended types, the signed one is chosen.
2001   // C++11 [conv.prom]p4:
2002   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2003   //   can be converted to a prvalue of its underlying type. Moreover, if
2004   //   integral promotion can be applied to its underlying type, a prvalue of an
2005   //   unscoped enumeration type whose underlying type is fixed can also be
2006   //   converted to a prvalue of the promoted underlying type.
2007   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2008     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2009     // provided for a scoped enumeration.
2010     if (FromEnumType->getDecl()->isScoped())
2011       return false;
2012 
2013     // We can perform an integral promotion to the underlying type of the enum,
2014     // even if that's not the promoted type. Note that the check for promoting
2015     // the underlying type is based on the type alone, and does not consider
2016     // the bitfield-ness of the actual source expression.
2017     if (FromEnumType->getDecl()->isFixed()) {
2018       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2019       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2020              IsIntegralPromotion(nullptr, Underlying, ToType);
2021     }
2022 
2023     // We have already pre-calculated the promotion type, so this is trivial.
2024     if (ToType->isIntegerType() &&
2025         isCompleteType(From->getBeginLoc(), FromType))
2026       return Context.hasSameUnqualifiedType(
2027           ToType, FromEnumType->getDecl()->getPromotionType());
2028 
2029     // C++ [conv.prom]p5:
2030     //   If the bit-field has an enumerated type, it is treated as any other
2031     //   value of that type for promotion purposes.
2032     //
2033     // ... so do not fall through into the bit-field checks below in C++.
2034     if (getLangOpts().CPlusPlus)
2035       return false;
2036   }
2037 
2038   // C++0x [conv.prom]p2:
2039   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2040   //   to an rvalue a prvalue of the first of the following types that can
2041   //   represent all the values of its underlying type: int, unsigned int,
2042   //   long int, unsigned long int, long long int, or unsigned long long int.
2043   //   If none of the types in that list can represent all the values of its
2044   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2045   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2046   //   type.
2047   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2048       ToType->isIntegerType()) {
2049     // Determine whether the type we're converting from is signed or
2050     // unsigned.
2051     bool FromIsSigned = FromType->isSignedIntegerType();
2052     uint64_t FromSize = Context.getTypeSize(FromType);
2053 
2054     // The types we'll try to promote to, in the appropriate
2055     // order. Try each of these types.
2056     QualType PromoteTypes[6] = {
2057       Context.IntTy, Context.UnsignedIntTy,
2058       Context.LongTy, Context.UnsignedLongTy ,
2059       Context.LongLongTy, Context.UnsignedLongLongTy
2060     };
2061     for (int Idx = 0; Idx < 6; ++Idx) {
2062       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2063       if (FromSize < ToSize ||
2064           (FromSize == ToSize &&
2065            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2066         // We found the type that we can promote to. If this is the
2067         // type we wanted, we have a promotion. Otherwise, no
2068         // promotion.
2069         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2070       }
2071     }
2072   }
2073 
2074   // An rvalue for an integral bit-field (9.6) can be converted to an
2075   // rvalue of type int if int can represent all the values of the
2076   // bit-field; otherwise, it can be converted to unsigned int if
2077   // unsigned int can represent all the values of the bit-field. If
2078   // the bit-field is larger yet, no integral promotion applies to
2079   // it. If the bit-field has an enumerated type, it is treated as any
2080   // other value of that type for promotion purposes (C++ 4.5p3).
2081   // FIXME: We should delay checking of bit-fields until we actually perform the
2082   // conversion.
2083   //
2084   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2085   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2086   // bit-fields and those whose underlying type is larger than int) for GCC
2087   // compatibility.
2088   if (From) {
2089     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2090       llvm::APSInt BitWidth;
2091       if (FromType->isIntegralType(Context) &&
2092           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2093         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2094         ToSize = Context.getTypeSize(ToType);
2095 
2096         // Are we promoting to an int from a bitfield that fits in an int?
2097         if (BitWidth < ToSize ||
2098             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2099           return To->getKind() == BuiltinType::Int;
2100         }
2101 
2102         // Are we promoting to an unsigned int from an unsigned bitfield
2103         // that fits into an unsigned int?
2104         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2105           return To->getKind() == BuiltinType::UInt;
2106         }
2107 
2108         return false;
2109       }
2110     }
2111   }
2112 
2113   // An rvalue of type bool can be converted to an rvalue of type int,
2114   // with false becoming zero and true becoming one (C++ 4.5p4).
2115   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2116     return true;
2117   }
2118 
2119   return false;
2120 }
2121 
2122 /// IsFloatingPointPromotion - Determines whether the conversion from
2123 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2124 /// returns true and sets PromotedType to the promoted type.
2125 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2126   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2127     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2128       /// An rvalue of type float can be converted to an rvalue of type
2129       /// double. (C++ 4.6p1).
2130       if (FromBuiltin->getKind() == BuiltinType::Float &&
2131           ToBuiltin->getKind() == BuiltinType::Double)
2132         return true;
2133 
2134       // C99 6.3.1.5p1:
2135       //   When a float is promoted to double or long double, or a
2136       //   double is promoted to long double [...].
2137       if (!getLangOpts().CPlusPlus &&
2138           (FromBuiltin->getKind() == BuiltinType::Float ||
2139            FromBuiltin->getKind() == BuiltinType::Double) &&
2140           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2141            ToBuiltin->getKind() == BuiltinType::Float128))
2142         return true;
2143 
2144       // Half can be promoted to float.
2145       if (!getLangOpts().NativeHalfType &&
2146            FromBuiltin->getKind() == BuiltinType::Half &&
2147           ToBuiltin->getKind() == BuiltinType::Float)
2148         return true;
2149     }
2150 
2151   return false;
2152 }
2153 
2154 /// Determine if a conversion is a complex promotion.
2155 ///
2156 /// A complex promotion is defined as a complex -> complex conversion
2157 /// where the conversion between the underlying real types is a
2158 /// floating-point or integral promotion.
2159 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2160   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2161   if (!FromComplex)
2162     return false;
2163 
2164   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2165   if (!ToComplex)
2166     return false;
2167 
2168   return IsFloatingPointPromotion(FromComplex->getElementType(),
2169                                   ToComplex->getElementType()) ||
2170     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2171                         ToComplex->getElementType());
2172 }
2173 
2174 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2175 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2176 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2177 /// if non-empty, will be a pointer to ToType that may or may not have
2178 /// the right set of qualifiers on its pointee.
2179 ///
2180 static QualType
2181 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2182                                    QualType ToPointee, QualType ToType,
2183                                    ASTContext &Context,
2184                                    bool StripObjCLifetime = false) {
2185   assert((FromPtr->getTypeClass() == Type::Pointer ||
2186           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2187          "Invalid similarly-qualified pointer type");
2188 
2189   /// Conversions to 'id' subsume cv-qualifier conversions.
2190   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2191     return ToType.getUnqualifiedType();
2192 
2193   QualType CanonFromPointee
2194     = Context.getCanonicalType(FromPtr->getPointeeType());
2195   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2196   Qualifiers Quals = CanonFromPointee.getQualifiers();
2197 
2198   if (StripObjCLifetime)
2199     Quals.removeObjCLifetime();
2200 
2201   // Exact qualifier match -> return the pointer type we're converting to.
2202   if (CanonToPointee.getLocalQualifiers() == Quals) {
2203     // ToType is exactly what we need. Return it.
2204     if (!ToType.isNull())
2205       return ToType.getUnqualifiedType();
2206 
2207     // Build a pointer to ToPointee. It has the right qualifiers
2208     // already.
2209     if (isa<ObjCObjectPointerType>(ToType))
2210       return Context.getObjCObjectPointerType(ToPointee);
2211     return Context.getPointerType(ToPointee);
2212   }
2213 
2214   // Just build a canonical type that has the right qualifiers.
2215   QualType QualifiedCanonToPointee
2216     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2217 
2218   if (isa<ObjCObjectPointerType>(ToType))
2219     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2220   return Context.getPointerType(QualifiedCanonToPointee);
2221 }
2222 
2223 static bool isNullPointerConstantForConversion(Expr *Expr,
2224                                                bool InOverloadResolution,
2225                                                ASTContext &Context) {
2226   // Handle value-dependent integral null pointer constants correctly.
2227   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2228   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2229       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2230     return !InOverloadResolution;
2231 
2232   return Expr->isNullPointerConstant(Context,
2233                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2234                                         : Expr::NPC_ValueDependentIsNull);
2235 }
2236 
2237 /// IsPointerConversion - Determines whether the conversion of the
2238 /// expression From, which has the (possibly adjusted) type FromType,
2239 /// can be converted to the type ToType via a pointer conversion (C++
2240 /// 4.10). If so, returns true and places the converted type (that
2241 /// might differ from ToType in its cv-qualifiers at some level) into
2242 /// ConvertedType.
2243 ///
2244 /// This routine also supports conversions to and from block pointers
2245 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2246 /// pointers to interfaces. FIXME: Once we've determined the
2247 /// appropriate overloading rules for Objective-C, we may want to
2248 /// split the Objective-C checks into a different routine; however,
2249 /// GCC seems to consider all of these conversions to be pointer
2250 /// conversions, so for now they live here. IncompatibleObjC will be
2251 /// set if the conversion is an allowed Objective-C conversion that
2252 /// should result in a warning.
2253 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2254                                bool InOverloadResolution,
2255                                QualType& ConvertedType,
2256                                bool &IncompatibleObjC) {
2257   IncompatibleObjC = false;
2258   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2259                               IncompatibleObjC))
2260     return true;
2261 
2262   // Conversion from a null pointer constant to any Objective-C pointer type.
2263   if (ToType->isObjCObjectPointerType() &&
2264       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2265     ConvertedType = ToType;
2266     return true;
2267   }
2268 
2269   // Blocks: Block pointers can be converted to void*.
2270   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2271       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2272     ConvertedType = ToType;
2273     return true;
2274   }
2275   // Blocks: A null pointer constant can be converted to a block
2276   // pointer type.
2277   if (ToType->isBlockPointerType() &&
2278       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2279     ConvertedType = ToType;
2280     return true;
2281   }
2282 
2283   // If the left-hand-side is nullptr_t, the right side can be a null
2284   // pointer constant.
2285   if (ToType->isNullPtrType() &&
2286       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2287     ConvertedType = ToType;
2288     return true;
2289   }
2290 
2291   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2292   if (!ToTypePtr)
2293     return false;
2294 
2295   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2296   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2297     ConvertedType = ToType;
2298     return true;
2299   }
2300 
2301   // Beyond this point, both types need to be pointers
2302   // , including objective-c pointers.
2303   QualType ToPointeeType = ToTypePtr->getPointeeType();
2304   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2305       !getLangOpts().ObjCAutoRefCount) {
2306     ConvertedType = BuildSimilarlyQualifiedPointerType(
2307                                       FromType->getAs<ObjCObjectPointerType>(),
2308                                                        ToPointeeType,
2309                                                        ToType, Context);
2310     return true;
2311   }
2312   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2313   if (!FromTypePtr)
2314     return false;
2315 
2316   QualType FromPointeeType = FromTypePtr->getPointeeType();
2317 
2318   // If the unqualified pointee types are the same, this can't be a
2319   // pointer conversion, so don't do all of the work below.
2320   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2321     return false;
2322 
2323   // An rvalue of type "pointer to cv T," where T is an object type,
2324   // can be converted to an rvalue of type "pointer to cv void" (C++
2325   // 4.10p2).
2326   if (FromPointeeType->isIncompleteOrObjectType() &&
2327       ToPointeeType->isVoidType()) {
2328     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329                                                        ToPointeeType,
2330                                                        ToType, Context,
2331                                                    /*StripObjCLifetime=*/true);
2332     return true;
2333   }
2334 
2335   // MSVC allows implicit function to void* type conversion.
2336   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2337       ToPointeeType->isVoidType()) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343 
2344   // When we're overloading in C, we allow a special kind of pointer
2345   // conversion for compatible-but-not-identical pointee types.
2346   if (!getLangOpts().CPlusPlus &&
2347       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2348     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2349                                                        ToPointeeType,
2350                                                        ToType, Context);
2351     return true;
2352   }
2353 
2354   // C++ [conv.ptr]p3:
2355   //
2356   //   An rvalue of type "pointer to cv D," where D is a class type,
2357   //   can be converted to an rvalue of type "pointer to cv B," where
2358   //   B is a base class (clause 10) of D. If B is an inaccessible
2359   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2360   //   necessitates this conversion is ill-formed. The result of the
2361   //   conversion is a pointer to the base class sub-object of the
2362   //   derived class object. The null pointer value is converted to
2363   //   the null pointer value of the destination type.
2364   //
2365   // Note that we do not check for ambiguity or inaccessibility
2366   // here. That is handled by CheckPointerConversion.
2367   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2368       ToPointeeType->isRecordType() &&
2369       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2370       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2371     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2372                                                        ToPointeeType,
2373                                                        ToType, Context);
2374     return true;
2375   }
2376 
2377   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2378       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2379     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2380                                                        ToPointeeType,
2381                                                        ToType, Context);
2382     return true;
2383   }
2384 
2385   return false;
2386 }
2387 
2388 /// Adopt the given qualifiers for the given type.
2389 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2390   Qualifiers TQs = T.getQualifiers();
2391 
2392   // Check whether qualifiers already match.
2393   if (TQs == Qs)
2394     return T;
2395 
2396   if (Qs.compatiblyIncludes(TQs))
2397     return Context.getQualifiedType(T, Qs);
2398 
2399   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2400 }
2401 
2402 /// isObjCPointerConversion - Determines whether this is an
2403 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2404 /// with the same arguments and return values.
2405 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2406                                    QualType& ConvertedType,
2407                                    bool &IncompatibleObjC) {
2408   if (!getLangOpts().ObjC)
2409     return false;
2410 
2411   // The set of qualifiers on the type we're converting from.
2412   Qualifiers FromQualifiers = FromType.getQualifiers();
2413 
2414   // First, we handle all conversions on ObjC object pointer types.
2415   const ObjCObjectPointerType* ToObjCPtr =
2416     ToType->getAs<ObjCObjectPointerType>();
2417   const ObjCObjectPointerType *FromObjCPtr =
2418     FromType->getAs<ObjCObjectPointerType>();
2419 
2420   if (ToObjCPtr && FromObjCPtr) {
2421     // If the pointee types are the same (ignoring qualifications),
2422     // then this is not a pointer conversion.
2423     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2424                                        FromObjCPtr->getPointeeType()))
2425       return false;
2426 
2427     // Conversion between Objective-C pointers.
2428     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2429       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2430       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2431       if (getLangOpts().CPlusPlus && LHS && RHS &&
2432           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2433                                                 FromObjCPtr->getPointeeType()))
2434         return false;
2435       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2436                                                    ToObjCPtr->getPointeeType(),
2437                                                          ToType, Context);
2438       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2439       return true;
2440     }
2441 
2442     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2443       // Okay: this is some kind of implicit downcast of Objective-C
2444       // interfaces, which is permitted. However, we're going to
2445       // complain about it.
2446       IncompatibleObjC = true;
2447       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2448                                                    ToObjCPtr->getPointeeType(),
2449                                                          ToType, Context);
2450       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2451       return true;
2452     }
2453   }
2454   // Beyond this point, both types need to be C pointers or block pointers.
2455   QualType ToPointeeType;
2456   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2457     ToPointeeType = ToCPtr->getPointeeType();
2458   else if (const BlockPointerType *ToBlockPtr =
2459             ToType->getAs<BlockPointerType>()) {
2460     // Objective C++: We're able to convert from a pointer to any object
2461     // to a block pointer type.
2462     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2463       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2464       return true;
2465     }
2466     ToPointeeType = ToBlockPtr->getPointeeType();
2467   }
2468   else if (FromType->getAs<BlockPointerType>() &&
2469            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2470     // Objective C++: We're able to convert from a block pointer type to a
2471     // pointer to any object.
2472     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2473     return true;
2474   }
2475   else
2476     return false;
2477 
2478   QualType FromPointeeType;
2479   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2480     FromPointeeType = FromCPtr->getPointeeType();
2481   else if (const BlockPointerType *FromBlockPtr =
2482            FromType->getAs<BlockPointerType>())
2483     FromPointeeType = FromBlockPtr->getPointeeType();
2484   else
2485     return false;
2486 
2487   // If we have pointers to pointers, recursively check whether this
2488   // is an Objective-C conversion.
2489   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2490       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2491                               IncompatibleObjC)) {
2492     // We always complain about this conversion.
2493     IncompatibleObjC = true;
2494     ConvertedType = Context.getPointerType(ConvertedType);
2495     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2496     return true;
2497   }
2498   // Allow conversion of pointee being objective-c pointer to another one;
2499   // as in I* to id.
2500   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2501       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2502       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2503                               IncompatibleObjC)) {
2504 
2505     ConvertedType = Context.getPointerType(ConvertedType);
2506     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2507     return true;
2508   }
2509 
2510   // If we have pointers to functions or blocks, check whether the only
2511   // differences in the argument and result types are in Objective-C
2512   // pointer conversions. If so, we permit the conversion (but
2513   // complain about it).
2514   const FunctionProtoType *FromFunctionType
2515     = FromPointeeType->getAs<FunctionProtoType>();
2516   const FunctionProtoType *ToFunctionType
2517     = ToPointeeType->getAs<FunctionProtoType>();
2518   if (FromFunctionType && ToFunctionType) {
2519     // If the function types are exactly the same, this isn't an
2520     // Objective-C pointer conversion.
2521     if (Context.getCanonicalType(FromPointeeType)
2522           == Context.getCanonicalType(ToPointeeType))
2523       return false;
2524 
2525     // Perform the quick checks that will tell us whether these
2526     // function types are obviously different.
2527     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2528         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2529         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2530       return false;
2531 
2532     bool HasObjCConversion = false;
2533     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2534         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2535       // Okay, the types match exactly. Nothing to do.
2536     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2537                                        ToFunctionType->getReturnType(),
2538                                        ConvertedType, IncompatibleObjC)) {
2539       // Okay, we have an Objective-C pointer conversion.
2540       HasObjCConversion = true;
2541     } else {
2542       // Function types are too different. Abort.
2543       return false;
2544     }
2545 
2546     // Check argument types.
2547     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2548          ArgIdx != NumArgs; ++ArgIdx) {
2549       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2550       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2551       if (Context.getCanonicalType(FromArgType)
2552             == Context.getCanonicalType(ToArgType)) {
2553         // Okay, the types match exactly. Nothing to do.
2554       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2555                                          ConvertedType, IncompatibleObjC)) {
2556         // Okay, we have an Objective-C pointer conversion.
2557         HasObjCConversion = true;
2558       } else {
2559         // Argument types are too different. Abort.
2560         return false;
2561       }
2562     }
2563 
2564     if (HasObjCConversion) {
2565       // We had an Objective-C conversion. Allow this pointer
2566       // conversion, but complain about it.
2567       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2568       IncompatibleObjC = true;
2569       return true;
2570     }
2571   }
2572 
2573   return false;
2574 }
2575 
2576 /// Determine whether this is an Objective-C writeback conversion,
2577 /// used for parameter passing when performing automatic reference counting.
2578 ///
2579 /// \param FromType The type we're converting form.
2580 ///
2581 /// \param ToType The type we're converting to.
2582 ///
2583 /// \param ConvertedType The type that will be produced after applying
2584 /// this conversion.
2585 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2586                                      QualType &ConvertedType) {
2587   if (!getLangOpts().ObjCAutoRefCount ||
2588       Context.hasSameUnqualifiedType(FromType, ToType))
2589     return false;
2590 
2591   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2592   QualType ToPointee;
2593   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2594     ToPointee = ToPointer->getPointeeType();
2595   else
2596     return false;
2597 
2598   Qualifiers ToQuals = ToPointee.getQualifiers();
2599   if (!ToPointee->isObjCLifetimeType() ||
2600       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2601       !ToQuals.withoutObjCLifetime().empty())
2602     return false;
2603 
2604   // Argument must be a pointer to __strong to __weak.
2605   QualType FromPointee;
2606   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2607     FromPointee = FromPointer->getPointeeType();
2608   else
2609     return false;
2610 
2611   Qualifiers FromQuals = FromPointee.getQualifiers();
2612   if (!FromPointee->isObjCLifetimeType() ||
2613       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2614        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2615     return false;
2616 
2617   // Make sure that we have compatible qualifiers.
2618   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2619   if (!ToQuals.compatiblyIncludes(FromQuals))
2620     return false;
2621 
2622   // Remove qualifiers from the pointee type we're converting from; they
2623   // aren't used in the compatibility check belong, and we'll be adding back
2624   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2625   FromPointee = FromPointee.getUnqualifiedType();
2626 
2627   // The unqualified form of the pointee types must be compatible.
2628   ToPointee = ToPointee.getUnqualifiedType();
2629   bool IncompatibleObjC;
2630   if (Context.typesAreCompatible(FromPointee, ToPointee))
2631     FromPointee = ToPointee;
2632   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2633                                     IncompatibleObjC))
2634     return false;
2635 
2636   /// Construct the type we're converting to, which is a pointer to
2637   /// __autoreleasing pointee.
2638   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2639   ConvertedType = Context.getPointerType(FromPointee);
2640   return true;
2641 }
2642 
2643 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2644                                     QualType& ConvertedType) {
2645   QualType ToPointeeType;
2646   if (const BlockPointerType *ToBlockPtr =
2647         ToType->getAs<BlockPointerType>())
2648     ToPointeeType = ToBlockPtr->getPointeeType();
2649   else
2650     return false;
2651 
2652   QualType FromPointeeType;
2653   if (const BlockPointerType *FromBlockPtr =
2654       FromType->getAs<BlockPointerType>())
2655     FromPointeeType = FromBlockPtr->getPointeeType();
2656   else
2657     return false;
2658   // We have pointer to blocks, check whether the only
2659   // differences in the argument and result types are in Objective-C
2660   // pointer conversions. If so, we permit the conversion.
2661 
2662   const FunctionProtoType *FromFunctionType
2663     = FromPointeeType->getAs<FunctionProtoType>();
2664   const FunctionProtoType *ToFunctionType
2665     = ToPointeeType->getAs<FunctionProtoType>();
2666 
2667   if (!FromFunctionType || !ToFunctionType)
2668     return false;
2669 
2670   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2671     return true;
2672 
2673   // Perform the quick checks that will tell us whether these
2674   // function types are obviously different.
2675   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2676       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2677     return false;
2678 
2679   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2680   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2681   if (FromEInfo != ToEInfo)
2682     return false;
2683 
2684   bool IncompatibleObjC = false;
2685   if (Context.hasSameType(FromFunctionType->getReturnType(),
2686                           ToFunctionType->getReturnType())) {
2687     // Okay, the types match exactly. Nothing to do.
2688   } else {
2689     QualType RHS = FromFunctionType->getReturnType();
2690     QualType LHS = ToFunctionType->getReturnType();
2691     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2692         !RHS.hasQualifiers() && LHS.hasQualifiers())
2693        LHS = LHS.getUnqualifiedType();
2694 
2695      if (Context.hasSameType(RHS,LHS)) {
2696        // OK exact match.
2697      } else if (isObjCPointerConversion(RHS, LHS,
2698                                         ConvertedType, IncompatibleObjC)) {
2699      if (IncompatibleObjC)
2700        return false;
2701      // Okay, we have an Objective-C pointer conversion.
2702      }
2703      else
2704        return false;
2705    }
2706 
2707    // Check argument types.
2708    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2709         ArgIdx != NumArgs; ++ArgIdx) {
2710      IncompatibleObjC = false;
2711      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2712      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2713      if (Context.hasSameType(FromArgType, ToArgType)) {
2714        // Okay, the types match exactly. Nothing to do.
2715      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2716                                         ConvertedType, IncompatibleObjC)) {
2717        if (IncompatibleObjC)
2718          return false;
2719        // Okay, we have an Objective-C pointer conversion.
2720      } else
2721        // Argument types are too different. Abort.
2722        return false;
2723    }
2724 
2725    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2726    bool CanUseToFPT, CanUseFromFPT;
2727    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2728                                       CanUseToFPT, CanUseFromFPT,
2729                                       NewParamInfos))
2730      return false;
2731 
2732    ConvertedType = ToType;
2733    return true;
2734 }
2735 
2736 enum {
2737   ft_default,
2738   ft_different_class,
2739   ft_parameter_arity,
2740   ft_parameter_mismatch,
2741   ft_return_type,
2742   ft_qualifer_mismatch,
2743   ft_noexcept
2744 };
2745 
2746 /// Attempts to get the FunctionProtoType from a Type. Handles
2747 /// MemberFunctionPointers properly.
2748 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2749   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2750     return FPT;
2751 
2752   if (auto *MPT = FromType->getAs<MemberPointerType>())
2753     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2754 
2755   return nullptr;
2756 }
2757 
2758 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2759 /// function types.  Catches different number of parameter, mismatch in
2760 /// parameter types, and different return types.
2761 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2762                                       QualType FromType, QualType ToType) {
2763   // If either type is not valid, include no extra info.
2764   if (FromType.isNull() || ToType.isNull()) {
2765     PDiag << ft_default;
2766     return;
2767   }
2768 
2769   // Get the function type from the pointers.
2770   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2771     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2772                             *ToMember = ToType->getAs<MemberPointerType>();
2773     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2774       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2775             << QualType(FromMember->getClass(), 0);
2776       return;
2777     }
2778     FromType = FromMember->getPointeeType();
2779     ToType = ToMember->getPointeeType();
2780   }
2781 
2782   if (FromType->isPointerType())
2783     FromType = FromType->getPointeeType();
2784   if (ToType->isPointerType())
2785     ToType = ToType->getPointeeType();
2786 
2787   // Remove references.
2788   FromType = FromType.getNonReferenceType();
2789   ToType = ToType.getNonReferenceType();
2790 
2791   // Don't print extra info for non-specialized template functions.
2792   if (FromType->isInstantiationDependentType() &&
2793       !FromType->getAs<TemplateSpecializationType>()) {
2794     PDiag << ft_default;
2795     return;
2796   }
2797 
2798   // No extra info for same types.
2799   if (Context.hasSameType(FromType, ToType)) {
2800     PDiag << ft_default;
2801     return;
2802   }
2803 
2804   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2805                           *ToFunction = tryGetFunctionProtoType(ToType);
2806 
2807   // Both types need to be function types.
2808   if (!FromFunction || !ToFunction) {
2809     PDiag << ft_default;
2810     return;
2811   }
2812 
2813   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2814     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2815           << FromFunction->getNumParams();
2816     return;
2817   }
2818 
2819   // Handle different parameter types.
2820   unsigned ArgPos;
2821   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2822     PDiag << ft_parameter_mismatch << ArgPos + 1
2823           << ToFunction->getParamType(ArgPos)
2824           << FromFunction->getParamType(ArgPos);
2825     return;
2826   }
2827 
2828   // Handle different return type.
2829   if (!Context.hasSameType(FromFunction->getReturnType(),
2830                            ToFunction->getReturnType())) {
2831     PDiag << ft_return_type << ToFunction->getReturnType()
2832           << FromFunction->getReturnType();
2833     return;
2834   }
2835 
2836   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2837     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2838           << FromFunction->getMethodQuals();
2839     return;
2840   }
2841 
2842   // Handle exception specification differences on canonical type (in C++17
2843   // onwards).
2844   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2845           ->isNothrow() !=
2846       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2847           ->isNothrow()) {
2848     PDiag << ft_noexcept;
2849     return;
2850   }
2851 
2852   // Unable to find a difference, so add no extra info.
2853   PDiag << ft_default;
2854 }
2855 
2856 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2857 /// for equality of their argument types. Caller has already checked that
2858 /// they have same number of arguments.  If the parameters are different,
2859 /// ArgPos will have the parameter index of the first different parameter.
2860 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2861                                       const FunctionProtoType *NewType,
2862                                       unsigned *ArgPos) {
2863   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2864                                               N = NewType->param_type_begin(),
2865                                               E = OldType->param_type_end();
2866        O && (O != E); ++O, ++N) {
2867     if (!Context.hasSameType(O->getUnqualifiedType(),
2868                              N->getUnqualifiedType())) {
2869       if (ArgPos)
2870         *ArgPos = O - OldType->param_type_begin();
2871       return false;
2872     }
2873   }
2874   return true;
2875 }
2876 
2877 /// CheckPointerConversion - Check the pointer conversion from the
2878 /// expression From to the type ToType. This routine checks for
2879 /// ambiguous or inaccessible derived-to-base pointer
2880 /// conversions for which IsPointerConversion has already returned
2881 /// true. It returns true and produces a diagnostic if there was an
2882 /// error, or returns false otherwise.
2883 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2884                                   CastKind &Kind,
2885                                   CXXCastPath& BasePath,
2886                                   bool IgnoreBaseAccess,
2887                                   bool Diagnose) {
2888   QualType FromType = From->getType();
2889   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2890 
2891   Kind = CK_BitCast;
2892 
2893   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2894       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2895           Expr::NPCK_ZeroExpression) {
2896     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2897       DiagRuntimeBehavior(From->getExprLoc(), From,
2898                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2899                             << ToType << From->getSourceRange());
2900     else if (!isUnevaluatedContext())
2901       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2902         << ToType << From->getSourceRange();
2903   }
2904   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2905     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2906       QualType FromPointeeType = FromPtrType->getPointeeType(),
2907                ToPointeeType   = ToPtrType->getPointeeType();
2908 
2909       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2910           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2911         // We must have a derived-to-base conversion. Check an
2912         // ambiguous or inaccessible conversion.
2913         unsigned InaccessibleID = 0;
2914         unsigned AmbigiousID = 0;
2915         if (Diagnose) {
2916           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2917           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2918         }
2919         if (CheckDerivedToBaseConversion(
2920                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2921                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2922                 &BasePath, IgnoreBaseAccess))
2923           return true;
2924 
2925         // The conversion was successful.
2926         Kind = CK_DerivedToBase;
2927       }
2928 
2929       if (Diagnose && !IsCStyleOrFunctionalCast &&
2930           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2931         assert(getLangOpts().MSVCCompat &&
2932                "this should only be possible with MSVCCompat!");
2933         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2934             << From->getSourceRange();
2935       }
2936     }
2937   } else if (const ObjCObjectPointerType *ToPtrType =
2938                ToType->getAs<ObjCObjectPointerType>()) {
2939     if (const ObjCObjectPointerType *FromPtrType =
2940           FromType->getAs<ObjCObjectPointerType>()) {
2941       // Objective-C++ conversions are always okay.
2942       // FIXME: We should have a different class of conversions for the
2943       // Objective-C++ implicit conversions.
2944       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2945         return false;
2946     } else if (FromType->isBlockPointerType()) {
2947       Kind = CK_BlockPointerToObjCPointerCast;
2948     } else {
2949       Kind = CK_CPointerToObjCPointerCast;
2950     }
2951   } else if (ToType->isBlockPointerType()) {
2952     if (!FromType->isBlockPointerType())
2953       Kind = CK_AnyPointerToBlockPointerCast;
2954   }
2955 
2956   // We shouldn't fall into this case unless it's valid for other
2957   // reasons.
2958   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2959     Kind = CK_NullToPointer;
2960 
2961   return false;
2962 }
2963 
2964 /// IsMemberPointerConversion - Determines whether the conversion of the
2965 /// expression From, which has the (possibly adjusted) type FromType, can be
2966 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2967 /// If so, returns true and places the converted type (that might differ from
2968 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2969 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2970                                      QualType ToType,
2971                                      bool InOverloadResolution,
2972                                      QualType &ConvertedType) {
2973   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2974   if (!ToTypePtr)
2975     return false;
2976 
2977   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2978   if (From->isNullPointerConstant(Context,
2979                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2980                                         : Expr::NPC_ValueDependentIsNull)) {
2981     ConvertedType = ToType;
2982     return true;
2983   }
2984 
2985   // Otherwise, both types have to be member pointers.
2986   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2987   if (!FromTypePtr)
2988     return false;
2989 
2990   // A pointer to member of B can be converted to a pointer to member of D,
2991   // where D is derived from B (C++ 4.11p2).
2992   QualType FromClass(FromTypePtr->getClass(), 0);
2993   QualType ToClass(ToTypePtr->getClass(), 0);
2994 
2995   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2996       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
2997     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2998                                                  ToClass.getTypePtr());
2999     return true;
3000   }
3001 
3002   return false;
3003 }
3004 
3005 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3006 /// expression From to the type ToType. This routine checks for ambiguous or
3007 /// virtual or inaccessible base-to-derived member pointer conversions
3008 /// for which IsMemberPointerConversion has already returned true. It returns
3009 /// true and produces a diagnostic if there was an error, or returns false
3010 /// otherwise.
3011 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3012                                         CastKind &Kind,
3013                                         CXXCastPath &BasePath,
3014                                         bool IgnoreBaseAccess) {
3015   QualType FromType = From->getType();
3016   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3017   if (!FromPtrType) {
3018     // This must be a null pointer to member pointer conversion
3019     assert(From->isNullPointerConstant(Context,
3020                                        Expr::NPC_ValueDependentIsNull) &&
3021            "Expr must be null pointer constant!");
3022     Kind = CK_NullToMemberPointer;
3023     return false;
3024   }
3025 
3026   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3027   assert(ToPtrType && "No member pointer cast has a target type "
3028                       "that is not a member pointer.");
3029 
3030   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3031   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3032 
3033   // FIXME: What about dependent types?
3034   assert(FromClass->isRecordType() && "Pointer into non-class.");
3035   assert(ToClass->isRecordType() && "Pointer into non-class.");
3036 
3037   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3038                      /*DetectVirtual=*/true);
3039   bool DerivationOkay =
3040       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3041   assert(DerivationOkay &&
3042          "Should not have been called if derivation isn't OK.");
3043   (void)DerivationOkay;
3044 
3045   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3046                                   getUnqualifiedType())) {
3047     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3048     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3049       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3050     return true;
3051   }
3052 
3053   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3054     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3055       << FromClass << ToClass << QualType(VBase, 0)
3056       << From->getSourceRange();
3057     return true;
3058   }
3059 
3060   if (!IgnoreBaseAccess)
3061     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3062                          Paths.front(),
3063                          diag::err_downcast_from_inaccessible_base);
3064 
3065   // Must be a base to derived member conversion.
3066   BuildBasePathArray(Paths, BasePath);
3067   Kind = CK_BaseToDerivedMemberPointer;
3068   return false;
3069 }
3070 
3071 /// Determine whether the lifetime conversion between the two given
3072 /// qualifiers sets is nontrivial.
3073 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3074                                                Qualifiers ToQuals) {
3075   // Converting anything to const __unsafe_unretained is trivial.
3076   if (ToQuals.hasConst() &&
3077       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3078     return false;
3079 
3080   return true;
3081 }
3082 
3083 /// IsQualificationConversion - Determines whether the conversion from
3084 /// an rvalue of type FromType to ToType is a qualification conversion
3085 /// (C++ 4.4).
3086 ///
3087 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3088 /// when the qualification conversion involves a change in the Objective-C
3089 /// object lifetime.
3090 bool
3091 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3092                                 bool CStyle, bool &ObjCLifetimeConversion) {
3093   FromType = Context.getCanonicalType(FromType);
3094   ToType = Context.getCanonicalType(ToType);
3095   ObjCLifetimeConversion = false;
3096 
3097   // If FromType and ToType are the same type, this is not a
3098   // qualification conversion.
3099   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3100     return false;
3101 
3102   // (C++ 4.4p4):
3103   //   A conversion can add cv-qualifiers at levels other than the first
3104   //   in multi-level pointers, subject to the following rules: [...]
3105   bool PreviousToQualsIncludeConst = true;
3106   bool UnwrappedAnyPointer = false;
3107   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3108     // Within each iteration of the loop, we check the qualifiers to
3109     // determine if this still looks like a qualification
3110     // conversion. Then, if all is well, we unwrap one more level of
3111     // pointers or pointers-to-members and do it all again
3112     // until there are no more pointers or pointers-to-members left to
3113     // unwrap.
3114     UnwrappedAnyPointer = true;
3115 
3116     Qualifiers FromQuals = FromType.getQualifiers();
3117     Qualifiers ToQuals = ToType.getQualifiers();
3118 
3119     // Ignore __unaligned qualifier if this type is void.
3120     if (ToType.getUnqualifiedType()->isVoidType())
3121       FromQuals.removeUnaligned();
3122 
3123     // Objective-C ARC:
3124     //   Check Objective-C lifetime conversions.
3125     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3126         UnwrappedAnyPointer) {
3127       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3128         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3129           ObjCLifetimeConversion = true;
3130         FromQuals.removeObjCLifetime();
3131         ToQuals.removeObjCLifetime();
3132       } else {
3133         // Qualification conversions cannot cast between different
3134         // Objective-C lifetime qualifiers.
3135         return false;
3136       }
3137     }
3138 
3139     // Allow addition/removal of GC attributes but not changing GC attributes.
3140     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3141         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3142       FromQuals.removeObjCGCAttr();
3143       ToQuals.removeObjCGCAttr();
3144     }
3145 
3146     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3147     //      2,j, and similarly for volatile.
3148     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3149       return false;
3150 
3151     //   -- if the cv 1,j and cv 2,j are different, then const is in
3152     //      every cv for 0 < k < j.
3153     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3154         && !PreviousToQualsIncludeConst)
3155       return false;
3156 
3157     // Keep track of whether all prior cv-qualifiers in the "to" type
3158     // include const.
3159     PreviousToQualsIncludeConst
3160       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3161   }
3162 
3163   // Allows address space promotion by language rules implemented in
3164   // Type::Qualifiers::isAddressSpaceSupersetOf.
3165   Qualifiers FromQuals = FromType.getQualifiers();
3166   Qualifiers ToQuals = ToType.getQualifiers();
3167   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3168       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3169     return false;
3170   }
3171 
3172   // We are left with FromType and ToType being the pointee types
3173   // after unwrapping the original FromType and ToType the same number
3174   // of types. If we unwrapped any pointers, and if FromType and
3175   // ToType have the same unqualified type (since we checked
3176   // qualifiers above), then this is a qualification conversion.
3177   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3178 }
3179 
3180 /// - Determine whether this is a conversion from a scalar type to an
3181 /// atomic type.
3182 ///
3183 /// If successful, updates \c SCS's second and third steps in the conversion
3184 /// sequence to finish the conversion.
3185 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3186                                 bool InOverloadResolution,
3187                                 StandardConversionSequence &SCS,
3188                                 bool CStyle) {
3189   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3190   if (!ToAtomic)
3191     return false;
3192 
3193   StandardConversionSequence InnerSCS;
3194   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3195                             InOverloadResolution, InnerSCS,
3196                             CStyle, /*AllowObjCWritebackConversion=*/false))
3197     return false;
3198 
3199   SCS.Second = InnerSCS.Second;
3200   SCS.setToType(1, InnerSCS.getToType(1));
3201   SCS.Third = InnerSCS.Third;
3202   SCS.QualificationIncludesObjCLifetime
3203     = InnerSCS.QualificationIncludesObjCLifetime;
3204   SCS.setToType(2, InnerSCS.getToType(2));
3205   return true;
3206 }
3207 
3208 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3209                                               CXXConstructorDecl *Constructor,
3210                                               QualType Type) {
3211   const FunctionProtoType *CtorType =
3212       Constructor->getType()->getAs<FunctionProtoType>();
3213   if (CtorType->getNumParams() > 0) {
3214     QualType FirstArg = CtorType->getParamType(0);
3215     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3216       return true;
3217   }
3218   return false;
3219 }
3220 
3221 static OverloadingResult
3222 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3223                                        CXXRecordDecl *To,
3224                                        UserDefinedConversionSequence &User,
3225                                        OverloadCandidateSet &CandidateSet,
3226                                        bool AllowExplicit) {
3227   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3228   for (auto *D : S.LookupConstructors(To)) {
3229     auto Info = getConstructorInfo(D);
3230     if (!Info)
3231       continue;
3232 
3233     bool Usable = !Info.Constructor->isInvalidDecl() &&
3234                   S.isInitListConstructor(Info.Constructor) &&
3235                   (AllowExplicit || !Info.Constructor->isExplicit());
3236     if (Usable) {
3237       // If the first argument is (a reference to) the target type,
3238       // suppress conversions.
3239       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3240           S.Context, Info.Constructor, ToType);
3241       if (Info.ConstructorTmpl)
3242         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3243                                        /*ExplicitArgs*/ nullptr, From,
3244                                        CandidateSet, SuppressUserConversions);
3245       else
3246         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3247                                CandidateSet, SuppressUserConversions);
3248     }
3249   }
3250 
3251   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3252 
3253   OverloadCandidateSet::iterator Best;
3254   switch (auto Result =
3255               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3256   case OR_Deleted:
3257   case OR_Success: {
3258     // Record the standard conversion we used and the conversion function.
3259     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3260     QualType ThisType = Constructor->getThisType();
3261     // Initializer lists don't have conversions as such.
3262     User.Before.setAsIdentityConversion();
3263     User.HadMultipleCandidates = HadMultipleCandidates;
3264     User.ConversionFunction = Constructor;
3265     User.FoundConversionFunction = Best->FoundDecl;
3266     User.After.setAsIdentityConversion();
3267     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3268     User.After.setAllToTypes(ToType);
3269     return Result;
3270   }
3271 
3272   case OR_No_Viable_Function:
3273     return OR_No_Viable_Function;
3274   case OR_Ambiguous:
3275     return OR_Ambiguous;
3276   }
3277 
3278   llvm_unreachable("Invalid OverloadResult!");
3279 }
3280 
3281 /// Determines whether there is a user-defined conversion sequence
3282 /// (C++ [over.ics.user]) that converts expression From to the type
3283 /// ToType. If such a conversion exists, User will contain the
3284 /// user-defined conversion sequence that performs such a conversion
3285 /// and this routine will return true. Otherwise, this routine returns
3286 /// false and User is unspecified.
3287 ///
3288 /// \param AllowExplicit  true if the conversion should consider C++0x
3289 /// "explicit" conversion functions as well as non-explicit conversion
3290 /// functions (C++0x [class.conv.fct]p2).
3291 ///
3292 /// \param AllowObjCConversionOnExplicit true if the conversion should
3293 /// allow an extra Objective-C pointer conversion on uses of explicit
3294 /// constructors. Requires \c AllowExplicit to also be set.
3295 static OverloadingResult
3296 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3297                         UserDefinedConversionSequence &User,
3298                         OverloadCandidateSet &CandidateSet,
3299                         bool AllowExplicit,
3300                         bool AllowObjCConversionOnExplicit) {
3301   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3302   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3303 
3304   // Whether we will only visit constructors.
3305   bool ConstructorsOnly = false;
3306 
3307   // If the type we are conversion to is a class type, enumerate its
3308   // constructors.
3309   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3310     // C++ [over.match.ctor]p1:
3311     //   When objects of class type are direct-initialized (8.5), or
3312     //   copy-initialized from an expression of the same or a
3313     //   derived class type (8.5), overload resolution selects the
3314     //   constructor. [...] For copy-initialization, the candidate
3315     //   functions are all the converting constructors (12.3.1) of
3316     //   that class. The argument list is the expression-list within
3317     //   the parentheses of the initializer.
3318     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3319         (From->getType()->getAs<RecordType>() &&
3320          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3321       ConstructorsOnly = true;
3322 
3323     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3324       // We're not going to find any constructors.
3325     } else if (CXXRecordDecl *ToRecordDecl
3326                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3327 
3328       Expr **Args = &From;
3329       unsigned NumArgs = 1;
3330       bool ListInitializing = false;
3331       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3332         // But first, see if there is an init-list-constructor that will work.
3333         OverloadingResult Result = IsInitializerListConstructorConversion(
3334             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3335         if (Result != OR_No_Viable_Function)
3336           return Result;
3337         // Never mind.
3338         CandidateSet.clear(
3339             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340 
3341         // If we're list-initializing, we pass the individual elements as
3342         // arguments, not the entire list.
3343         Args = InitList->getInits();
3344         NumArgs = InitList->getNumInits();
3345         ListInitializing = true;
3346       }
3347 
3348       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3349         auto Info = getConstructorInfo(D);
3350         if (!Info)
3351           continue;
3352 
3353         bool Usable = !Info.Constructor->isInvalidDecl();
3354         if (ListInitializing)
3355           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3356         else
3357           Usable = Usable &&
3358                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3359         if (Usable) {
3360           bool SuppressUserConversions = !ConstructorsOnly;
3361           if (SuppressUserConversions && ListInitializing) {
3362             SuppressUserConversions = false;
3363             if (NumArgs == 1) {
3364               // If the first argument is (a reference to) the target type,
3365               // suppress conversions.
3366               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3367                   S.Context, Info.Constructor, ToType);
3368             }
3369           }
3370           if (Info.ConstructorTmpl)
3371             S.AddTemplateOverloadCandidate(
3372                 Info.ConstructorTmpl, Info.FoundDecl,
3373                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3374                 CandidateSet, SuppressUserConversions);
3375           else
3376             // Allow one user-defined conversion when user specifies a
3377             // From->ToType conversion via an static cast (c-style, etc).
3378             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3379                                    llvm::makeArrayRef(Args, NumArgs),
3380                                    CandidateSet, SuppressUserConversions);
3381         }
3382       }
3383     }
3384   }
3385 
3386   // Enumerate conversion functions, if we're allowed to.
3387   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3388   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3389     // No conversion functions from incomplete types.
3390   } else if (const RecordType *FromRecordType =
3391                  From->getType()->getAs<RecordType>()) {
3392     if (CXXRecordDecl *FromRecordDecl
3393          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3394       // Add all of the conversion functions as candidates.
3395       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3396       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3397         DeclAccessPair FoundDecl = I.getPair();
3398         NamedDecl *D = FoundDecl.getDecl();
3399         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3400         if (isa<UsingShadowDecl>(D))
3401           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3402 
3403         CXXConversionDecl *Conv;
3404         FunctionTemplateDecl *ConvTemplate;
3405         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3406           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3407         else
3408           Conv = cast<CXXConversionDecl>(D);
3409 
3410         if (AllowExplicit || !Conv->isExplicit()) {
3411           if (ConvTemplate)
3412             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3413                                              ActingContext, From, ToType,
3414                                              CandidateSet,
3415                                              AllowObjCConversionOnExplicit);
3416           else
3417             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3418                                      From, ToType, CandidateSet,
3419                                      AllowObjCConversionOnExplicit);
3420         }
3421       }
3422     }
3423   }
3424 
3425   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3426 
3427   OverloadCandidateSet::iterator Best;
3428   switch (auto Result =
3429               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3430   case OR_Success:
3431   case OR_Deleted:
3432     // Record the standard conversion we used and the conversion function.
3433     if (CXXConstructorDecl *Constructor
3434           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3435       // C++ [over.ics.user]p1:
3436       //   If the user-defined conversion is specified by a
3437       //   constructor (12.3.1), the initial standard conversion
3438       //   sequence converts the source type to the type required by
3439       //   the argument of the constructor.
3440       //
3441       QualType ThisType = Constructor->getThisType();
3442       if (isa<InitListExpr>(From)) {
3443         // Initializer lists don't have conversions as such.
3444         User.Before.setAsIdentityConversion();
3445       } else {
3446         if (Best->Conversions[0].isEllipsis())
3447           User.EllipsisConversion = true;
3448         else {
3449           User.Before = Best->Conversions[0].Standard;
3450           User.EllipsisConversion = false;
3451         }
3452       }
3453       User.HadMultipleCandidates = HadMultipleCandidates;
3454       User.ConversionFunction = Constructor;
3455       User.FoundConversionFunction = Best->FoundDecl;
3456       User.After.setAsIdentityConversion();
3457       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3458       User.After.setAllToTypes(ToType);
3459       return Result;
3460     }
3461     if (CXXConversionDecl *Conversion
3462                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3463       // C++ [over.ics.user]p1:
3464       //
3465       //   [...] If the user-defined conversion is specified by a
3466       //   conversion function (12.3.2), the initial standard
3467       //   conversion sequence converts the source type to the
3468       //   implicit object parameter of the conversion function.
3469       User.Before = Best->Conversions[0].Standard;
3470       User.HadMultipleCandidates = HadMultipleCandidates;
3471       User.ConversionFunction = Conversion;
3472       User.FoundConversionFunction = Best->FoundDecl;
3473       User.EllipsisConversion = false;
3474 
3475       // C++ [over.ics.user]p2:
3476       //   The second standard conversion sequence converts the
3477       //   result of the user-defined conversion to the target type
3478       //   for the sequence. Since an implicit conversion sequence
3479       //   is an initialization, the special rules for
3480       //   initialization by user-defined conversion apply when
3481       //   selecting the best user-defined conversion for a
3482       //   user-defined conversion sequence (see 13.3.3 and
3483       //   13.3.3.1).
3484       User.After = Best->FinalConversion;
3485       return Result;
3486     }
3487     llvm_unreachable("Not a constructor or conversion function?");
3488 
3489   case OR_No_Viable_Function:
3490     return OR_No_Viable_Function;
3491 
3492   case OR_Ambiguous:
3493     return OR_Ambiguous;
3494   }
3495 
3496   llvm_unreachable("Invalid OverloadResult!");
3497 }
3498 
3499 bool
3500 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3501   ImplicitConversionSequence ICS;
3502   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3503                                     OverloadCandidateSet::CSK_Normal);
3504   OverloadingResult OvResult =
3505     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3506                             CandidateSet, false, false);
3507   if (OvResult == OR_Ambiguous)
3508     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3509         << From->getType() << ToType << From->getSourceRange();
3510   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3511     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3512                              diag::err_typecheck_nonviable_condition_incomplete,
3513                              From->getType(), From->getSourceRange()))
3514       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3515           << false << From->getType() << From->getSourceRange() << ToType;
3516   } else
3517     return false;
3518   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3519   return true;
3520 }
3521 
3522 /// Compare the user-defined conversion functions or constructors
3523 /// of two user-defined conversion sequences to determine whether any ordering
3524 /// is possible.
3525 static ImplicitConversionSequence::CompareKind
3526 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3527                            FunctionDecl *Function2) {
3528   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3529     return ImplicitConversionSequence::Indistinguishable;
3530 
3531   // Objective-C++:
3532   //   If both conversion functions are implicitly-declared conversions from
3533   //   a lambda closure type to a function pointer and a block pointer,
3534   //   respectively, always prefer the conversion to a function pointer,
3535   //   because the function pointer is more lightweight and is more likely
3536   //   to keep code working.
3537   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3538   if (!Conv1)
3539     return ImplicitConversionSequence::Indistinguishable;
3540 
3541   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3542   if (!Conv2)
3543     return ImplicitConversionSequence::Indistinguishable;
3544 
3545   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3546     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3547     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3548     if (Block1 != Block2)
3549       return Block1 ? ImplicitConversionSequence::Worse
3550                     : ImplicitConversionSequence::Better;
3551   }
3552 
3553   return ImplicitConversionSequence::Indistinguishable;
3554 }
3555 
3556 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3557     const ImplicitConversionSequence &ICS) {
3558   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3559          (ICS.isUserDefined() &&
3560           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3561 }
3562 
3563 /// CompareImplicitConversionSequences - Compare two implicit
3564 /// conversion sequences to determine whether one is better than the
3565 /// other or if they are indistinguishable (C++ 13.3.3.2).
3566 static ImplicitConversionSequence::CompareKind
3567 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3568                                    const ImplicitConversionSequence& ICS1,
3569                                    const ImplicitConversionSequence& ICS2)
3570 {
3571   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3572   // conversion sequences (as defined in 13.3.3.1)
3573   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3574   //      conversion sequence than a user-defined conversion sequence or
3575   //      an ellipsis conversion sequence, and
3576   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3577   //      conversion sequence than an ellipsis conversion sequence
3578   //      (13.3.3.1.3).
3579   //
3580   // C++0x [over.best.ics]p10:
3581   //   For the purpose of ranking implicit conversion sequences as
3582   //   described in 13.3.3.2, the ambiguous conversion sequence is
3583   //   treated as a user-defined sequence that is indistinguishable
3584   //   from any other user-defined conversion sequence.
3585 
3586   // String literal to 'char *' conversion has been deprecated in C++03. It has
3587   // been removed from C++11. We still accept this conversion, if it happens at
3588   // the best viable function. Otherwise, this conversion is considered worse
3589   // than ellipsis conversion. Consider this as an extension; this is not in the
3590   // standard. For example:
3591   //
3592   // int &f(...);    // #1
3593   // void f(char*);  // #2
3594   // void g() { int &r = f("foo"); }
3595   //
3596   // In C++03, we pick #2 as the best viable function.
3597   // In C++11, we pick #1 as the best viable function, because ellipsis
3598   // conversion is better than string-literal to char* conversion (since there
3599   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3600   // convert arguments, #2 would be the best viable function in C++11.
3601   // If the best viable function has this conversion, a warning will be issued
3602   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3603 
3604   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3605       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3606       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3607     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3608                ? ImplicitConversionSequence::Worse
3609                : ImplicitConversionSequence::Better;
3610 
3611   if (ICS1.getKindRank() < ICS2.getKindRank())
3612     return ImplicitConversionSequence::Better;
3613   if (ICS2.getKindRank() < ICS1.getKindRank())
3614     return ImplicitConversionSequence::Worse;
3615 
3616   // The following checks require both conversion sequences to be of
3617   // the same kind.
3618   if (ICS1.getKind() != ICS2.getKind())
3619     return ImplicitConversionSequence::Indistinguishable;
3620 
3621   ImplicitConversionSequence::CompareKind Result =
3622       ImplicitConversionSequence::Indistinguishable;
3623 
3624   // Two implicit conversion sequences of the same form are
3625   // indistinguishable conversion sequences unless one of the
3626   // following rules apply: (C++ 13.3.3.2p3):
3627 
3628   // List-initialization sequence L1 is a better conversion sequence than
3629   // list-initialization sequence L2 if:
3630   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3631   //   if not that,
3632   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3633   //   and N1 is smaller than N2.,
3634   // even if one of the other rules in this paragraph would otherwise apply.
3635   if (!ICS1.isBad()) {
3636     if (ICS1.isStdInitializerListElement() &&
3637         !ICS2.isStdInitializerListElement())
3638       return ImplicitConversionSequence::Better;
3639     if (!ICS1.isStdInitializerListElement() &&
3640         ICS2.isStdInitializerListElement())
3641       return ImplicitConversionSequence::Worse;
3642   }
3643 
3644   if (ICS1.isStandard())
3645     // Standard conversion sequence S1 is a better conversion sequence than
3646     // standard conversion sequence S2 if [...]
3647     Result = CompareStandardConversionSequences(S, Loc,
3648                                                 ICS1.Standard, ICS2.Standard);
3649   else if (ICS1.isUserDefined()) {
3650     // User-defined conversion sequence U1 is a better conversion
3651     // sequence than another user-defined conversion sequence U2 if
3652     // they contain the same user-defined conversion function or
3653     // constructor and if the second standard conversion sequence of
3654     // U1 is better than the second standard conversion sequence of
3655     // U2 (C++ 13.3.3.2p3).
3656     if (ICS1.UserDefined.ConversionFunction ==
3657           ICS2.UserDefined.ConversionFunction)
3658       Result = CompareStandardConversionSequences(S, Loc,
3659                                                   ICS1.UserDefined.After,
3660                                                   ICS2.UserDefined.After);
3661     else
3662       Result = compareConversionFunctions(S,
3663                                           ICS1.UserDefined.ConversionFunction,
3664                                           ICS2.UserDefined.ConversionFunction);
3665   }
3666 
3667   return Result;
3668 }
3669 
3670 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3671 // determine if one is a proper subset of the other.
3672 static ImplicitConversionSequence::CompareKind
3673 compareStandardConversionSubsets(ASTContext &Context,
3674                                  const StandardConversionSequence& SCS1,
3675                                  const StandardConversionSequence& SCS2) {
3676   ImplicitConversionSequence::CompareKind Result
3677     = ImplicitConversionSequence::Indistinguishable;
3678 
3679   // the identity conversion sequence is considered to be a subsequence of
3680   // any non-identity conversion sequence
3681   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3682     return ImplicitConversionSequence::Better;
3683   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3684     return ImplicitConversionSequence::Worse;
3685 
3686   if (SCS1.Second != SCS2.Second) {
3687     if (SCS1.Second == ICK_Identity)
3688       Result = ImplicitConversionSequence::Better;
3689     else if (SCS2.Second == ICK_Identity)
3690       Result = ImplicitConversionSequence::Worse;
3691     else
3692       return ImplicitConversionSequence::Indistinguishable;
3693   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3694     return ImplicitConversionSequence::Indistinguishable;
3695 
3696   if (SCS1.Third == SCS2.Third) {
3697     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3698                              : ImplicitConversionSequence::Indistinguishable;
3699   }
3700 
3701   if (SCS1.Third == ICK_Identity)
3702     return Result == ImplicitConversionSequence::Worse
3703              ? ImplicitConversionSequence::Indistinguishable
3704              : ImplicitConversionSequence::Better;
3705 
3706   if (SCS2.Third == ICK_Identity)
3707     return Result == ImplicitConversionSequence::Better
3708              ? ImplicitConversionSequence::Indistinguishable
3709              : ImplicitConversionSequence::Worse;
3710 
3711   return ImplicitConversionSequence::Indistinguishable;
3712 }
3713 
3714 /// Determine whether one of the given reference bindings is better
3715 /// than the other based on what kind of bindings they are.
3716 static bool
3717 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3718                              const StandardConversionSequence &SCS2) {
3719   // C++0x [over.ics.rank]p3b4:
3720   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3721   //      implicit object parameter of a non-static member function declared
3722   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3723   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3724   //      lvalue reference to a function lvalue and S2 binds an rvalue
3725   //      reference*.
3726   //
3727   // FIXME: Rvalue references. We're going rogue with the above edits,
3728   // because the semantics in the current C++0x working paper (N3225 at the
3729   // time of this writing) break the standard definition of std::forward
3730   // and std::reference_wrapper when dealing with references to functions.
3731   // Proposed wording changes submitted to CWG for consideration.
3732   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3733       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3734     return false;
3735 
3736   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3737           SCS2.IsLvalueReference) ||
3738          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3739           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3740 }
3741 
3742 /// CompareStandardConversionSequences - Compare two standard
3743 /// conversion sequences to determine whether one is better than the
3744 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3745 static ImplicitConversionSequence::CompareKind
3746 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3747                                    const StandardConversionSequence& SCS1,
3748                                    const StandardConversionSequence& SCS2)
3749 {
3750   // Standard conversion sequence S1 is a better conversion sequence
3751   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3752 
3753   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3754   //     sequences in the canonical form defined by 13.3.3.1.1,
3755   //     excluding any Lvalue Transformation; the identity conversion
3756   //     sequence is considered to be a subsequence of any
3757   //     non-identity conversion sequence) or, if not that,
3758   if (ImplicitConversionSequence::CompareKind CK
3759         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3760     return CK;
3761 
3762   //  -- the rank of S1 is better than the rank of S2 (by the rules
3763   //     defined below), or, if not that,
3764   ImplicitConversionRank Rank1 = SCS1.getRank();
3765   ImplicitConversionRank Rank2 = SCS2.getRank();
3766   if (Rank1 < Rank2)
3767     return ImplicitConversionSequence::Better;
3768   else if (Rank2 < Rank1)
3769     return ImplicitConversionSequence::Worse;
3770 
3771   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3772   // are indistinguishable unless one of the following rules
3773   // applies:
3774 
3775   //   A conversion that is not a conversion of a pointer, or
3776   //   pointer to member, to bool is better than another conversion
3777   //   that is such a conversion.
3778   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3779     return SCS2.isPointerConversionToBool()
3780              ? ImplicitConversionSequence::Better
3781              : ImplicitConversionSequence::Worse;
3782 
3783   // C++ [over.ics.rank]p4b2:
3784   //
3785   //   If class B is derived directly or indirectly from class A,
3786   //   conversion of B* to A* is better than conversion of B* to
3787   //   void*, and conversion of A* to void* is better than conversion
3788   //   of B* to void*.
3789   bool SCS1ConvertsToVoid
3790     = SCS1.isPointerConversionToVoidPointer(S.Context);
3791   bool SCS2ConvertsToVoid
3792     = SCS2.isPointerConversionToVoidPointer(S.Context);
3793   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3794     // Exactly one of the conversion sequences is a conversion to
3795     // a void pointer; it's the worse conversion.
3796     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3797                               : ImplicitConversionSequence::Worse;
3798   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3799     // Neither conversion sequence converts to a void pointer; compare
3800     // their derived-to-base conversions.
3801     if (ImplicitConversionSequence::CompareKind DerivedCK
3802           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3803       return DerivedCK;
3804   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3805              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3806     // Both conversion sequences are conversions to void
3807     // pointers. Compare the source types to determine if there's an
3808     // inheritance relationship in their sources.
3809     QualType FromType1 = SCS1.getFromType();
3810     QualType FromType2 = SCS2.getFromType();
3811 
3812     // Adjust the types we're converting from via the array-to-pointer
3813     // conversion, if we need to.
3814     if (SCS1.First == ICK_Array_To_Pointer)
3815       FromType1 = S.Context.getArrayDecayedType(FromType1);
3816     if (SCS2.First == ICK_Array_To_Pointer)
3817       FromType2 = S.Context.getArrayDecayedType(FromType2);
3818 
3819     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3820     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3821 
3822     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3823       return ImplicitConversionSequence::Better;
3824     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3825       return ImplicitConversionSequence::Worse;
3826 
3827     // Objective-C++: If one interface is more specific than the
3828     // other, it is the better one.
3829     const ObjCObjectPointerType* FromObjCPtr1
3830       = FromType1->getAs<ObjCObjectPointerType>();
3831     const ObjCObjectPointerType* FromObjCPtr2
3832       = FromType2->getAs<ObjCObjectPointerType>();
3833     if (FromObjCPtr1 && FromObjCPtr2) {
3834       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3835                                                           FromObjCPtr2);
3836       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3837                                                            FromObjCPtr1);
3838       if (AssignLeft != AssignRight) {
3839         return AssignLeft? ImplicitConversionSequence::Better
3840                          : ImplicitConversionSequence::Worse;
3841       }
3842     }
3843   }
3844 
3845   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3846   // bullet 3).
3847   if (ImplicitConversionSequence::CompareKind QualCK
3848         = CompareQualificationConversions(S, SCS1, SCS2))
3849     return QualCK;
3850 
3851   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3852     // Check for a better reference binding based on the kind of bindings.
3853     if (isBetterReferenceBindingKind(SCS1, SCS2))
3854       return ImplicitConversionSequence::Better;
3855     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3856       return ImplicitConversionSequence::Worse;
3857 
3858     // C++ [over.ics.rank]p3b4:
3859     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3860     //      which the references refer are the same type except for
3861     //      top-level cv-qualifiers, and the type to which the reference
3862     //      initialized by S2 refers is more cv-qualified than the type
3863     //      to which the reference initialized by S1 refers.
3864     QualType T1 = SCS1.getToType(2);
3865     QualType T2 = SCS2.getToType(2);
3866     T1 = S.Context.getCanonicalType(T1);
3867     T2 = S.Context.getCanonicalType(T2);
3868     Qualifiers T1Quals, T2Quals;
3869     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3870     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3871     if (UnqualT1 == UnqualT2) {
3872       // Objective-C++ ARC: If the references refer to objects with different
3873       // lifetimes, prefer bindings that don't change lifetime.
3874       if (SCS1.ObjCLifetimeConversionBinding !=
3875                                           SCS2.ObjCLifetimeConversionBinding) {
3876         return SCS1.ObjCLifetimeConversionBinding
3877                                            ? ImplicitConversionSequence::Worse
3878                                            : ImplicitConversionSequence::Better;
3879       }
3880 
3881       // If the type is an array type, promote the element qualifiers to the
3882       // type for comparison.
3883       if (isa<ArrayType>(T1) && T1Quals)
3884         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3885       if (isa<ArrayType>(T2) && T2Quals)
3886         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3887       if (T2.isMoreQualifiedThan(T1))
3888         return ImplicitConversionSequence::Better;
3889       else if (T1.isMoreQualifiedThan(T2))
3890         return ImplicitConversionSequence::Worse;
3891     }
3892   }
3893 
3894   // In Microsoft mode, prefer an integral conversion to a
3895   // floating-to-integral conversion if the integral conversion
3896   // is between types of the same size.
3897   // For example:
3898   // void f(float);
3899   // void f(int);
3900   // int main {
3901   //    long a;
3902   //    f(a);
3903   // }
3904   // Here, MSVC will call f(int) instead of generating a compile error
3905   // as clang will do in standard mode.
3906   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3907       SCS2.Second == ICK_Floating_Integral &&
3908       S.Context.getTypeSize(SCS1.getFromType()) ==
3909           S.Context.getTypeSize(SCS1.getToType(2)))
3910     return ImplicitConversionSequence::Better;
3911 
3912   // Prefer a compatible vector conversion over a lax vector conversion
3913   // For example:
3914   //
3915   // typedef float __v4sf __attribute__((__vector_size__(16)));
3916   // void f(vector float);
3917   // void f(vector signed int);
3918   // int main() {
3919   //   __v4sf a;
3920   //   f(a);
3921   // }
3922   // Here, we'd like to choose f(vector float) and not
3923   // report an ambiguous call error
3924   if (SCS1.Second == ICK_Vector_Conversion &&
3925       SCS2.Second == ICK_Vector_Conversion) {
3926     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3927         SCS1.getFromType(), SCS1.getToType(2));
3928     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3929         SCS2.getFromType(), SCS2.getToType(2));
3930 
3931     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3932       return SCS1IsCompatibleVectorConversion
3933                  ? ImplicitConversionSequence::Better
3934                  : ImplicitConversionSequence::Worse;
3935   }
3936 
3937   return ImplicitConversionSequence::Indistinguishable;
3938 }
3939 
3940 /// CompareQualificationConversions - Compares two standard conversion
3941 /// sequences to determine whether they can be ranked based on their
3942 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3943 static ImplicitConversionSequence::CompareKind
3944 CompareQualificationConversions(Sema &S,
3945                                 const StandardConversionSequence& SCS1,
3946                                 const StandardConversionSequence& SCS2) {
3947   // C++ 13.3.3.2p3:
3948   //  -- S1 and S2 differ only in their qualification conversion and
3949   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3950   //     cv-qualification signature of type T1 is a proper subset of
3951   //     the cv-qualification signature of type T2, and S1 is not the
3952   //     deprecated string literal array-to-pointer conversion (4.2).
3953   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3954       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3955     return ImplicitConversionSequence::Indistinguishable;
3956 
3957   // FIXME: the example in the standard doesn't use a qualification
3958   // conversion (!)
3959   QualType T1 = SCS1.getToType(2);
3960   QualType T2 = SCS2.getToType(2);
3961   T1 = S.Context.getCanonicalType(T1);
3962   T2 = S.Context.getCanonicalType(T2);
3963   Qualifiers T1Quals, T2Quals;
3964   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3965   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3966 
3967   // If the types are the same, we won't learn anything by unwrapped
3968   // them.
3969   if (UnqualT1 == UnqualT2)
3970     return ImplicitConversionSequence::Indistinguishable;
3971 
3972   // If the type is an array type, promote the element qualifiers to the type
3973   // for comparison.
3974   if (isa<ArrayType>(T1) && T1Quals)
3975     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3976   if (isa<ArrayType>(T2) && T2Quals)
3977     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3978 
3979   ImplicitConversionSequence::CompareKind Result
3980     = ImplicitConversionSequence::Indistinguishable;
3981 
3982   // Objective-C++ ARC:
3983   //   Prefer qualification conversions not involving a change in lifetime
3984   //   to qualification conversions that do not change lifetime.
3985   if (SCS1.QualificationIncludesObjCLifetime !=
3986                                       SCS2.QualificationIncludesObjCLifetime) {
3987     Result = SCS1.QualificationIncludesObjCLifetime
3988                ? ImplicitConversionSequence::Worse
3989                : ImplicitConversionSequence::Better;
3990   }
3991 
3992   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3993     // Within each iteration of the loop, we check the qualifiers to
3994     // determine if this still looks like a qualification
3995     // conversion. Then, if all is well, we unwrap one more level of
3996     // pointers or pointers-to-members and do it all again
3997     // until there are no more pointers or pointers-to-members left
3998     // to unwrap. This essentially mimics what
3999     // IsQualificationConversion does, but here we're checking for a
4000     // strict subset of qualifiers.
4001     if (T1.getQualifiers().withoutObjCLifetime() ==
4002         T2.getQualifiers().withoutObjCLifetime())
4003       // The qualifiers are the same, so this doesn't tell us anything
4004       // about how the sequences rank.
4005       // ObjC ownership quals are omitted above as they interfere with
4006       // the ARC overload rule.
4007       ;
4008     else if (T2.isMoreQualifiedThan(T1)) {
4009       // T1 has fewer qualifiers, so it could be the better sequence.
4010       if (Result == ImplicitConversionSequence::Worse)
4011         // Neither has qualifiers that are a subset of the other's
4012         // qualifiers.
4013         return ImplicitConversionSequence::Indistinguishable;
4014 
4015       Result = ImplicitConversionSequence::Better;
4016     } else if (T1.isMoreQualifiedThan(T2)) {
4017       // T2 has fewer qualifiers, so it could be the better sequence.
4018       if (Result == ImplicitConversionSequence::Better)
4019         // Neither has qualifiers that are a subset of the other's
4020         // qualifiers.
4021         return ImplicitConversionSequence::Indistinguishable;
4022 
4023       Result = ImplicitConversionSequence::Worse;
4024     } else {
4025       // Qualifiers are disjoint.
4026       return ImplicitConversionSequence::Indistinguishable;
4027     }
4028 
4029     // If the types after this point are equivalent, we're done.
4030     if (S.Context.hasSameUnqualifiedType(T1, T2))
4031       break;
4032   }
4033 
4034   // Check that the winning standard conversion sequence isn't using
4035   // the deprecated string literal array to pointer conversion.
4036   switch (Result) {
4037   case ImplicitConversionSequence::Better:
4038     if (SCS1.DeprecatedStringLiteralToCharPtr)
4039       Result = ImplicitConversionSequence::Indistinguishable;
4040     break;
4041 
4042   case ImplicitConversionSequence::Indistinguishable:
4043     break;
4044 
4045   case ImplicitConversionSequence::Worse:
4046     if (SCS2.DeprecatedStringLiteralToCharPtr)
4047       Result = ImplicitConversionSequence::Indistinguishable;
4048     break;
4049   }
4050 
4051   return Result;
4052 }
4053 
4054 /// CompareDerivedToBaseConversions - Compares two standard conversion
4055 /// sequences to determine whether they can be ranked based on their
4056 /// various kinds of derived-to-base conversions (C++
4057 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4058 /// conversions between Objective-C interface types.
4059 static ImplicitConversionSequence::CompareKind
4060 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4061                                 const StandardConversionSequence& SCS1,
4062                                 const StandardConversionSequence& SCS2) {
4063   QualType FromType1 = SCS1.getFromType();
4064   QualType ToType1 = SCS1.getToType(1);
4065   QualType FromType2 = SCS2.getFromType();
4066   QualType ToType2 = SCS2.getToType(1);
4067 
4068   // Adjust the types we're converting from via the array-to-pointer
4069   // conversion, if we need to.
4070   if (SCS1.First == ICK_Array_To_Pointer)
4071     FromType1 = S.Context.getArrayDecayedType(FromType1);
4072   if (SCS2.First == ICK_Array_To_Pointer)
4073     FromType2 = S.Context.getArrayDecayedType(FromType2);
4074 
4075   // Canonicalize all of the types.
4076   FromType1 = S.Context.getCanonicalType(FromType1);
4077   ToType1 = S.Context.getCanonicalType(ToType1);
4078   FromType2 = S.Context.getCanonicalType(FromType2);
4079   ToType2 = S.Context.getCanonicalType(ToType2);
4080 
4081   // C++ [over.ics.rank]p4b3:
4082   //
4083   //   If class B is derived directly or indirectly from class A and
4084   //   class C is derived directly or indirectly from B,
4085   //
4086   // Compare based on pointer conversions.
4087   if (SCS1.Second == ICK_Pointer_Conversion &&
4088       SCS2.Second == ICK_Pointer_Conversion &&
4089       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4090       FromType1->isPointerType() && FromType2->isPointerType() &&
4091       ToType1->isPointerType() && ToType2->isPointerType()) {
4092     QualType FromPointee1
4093       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4094     QualType ToPointee1
4095       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4096     QualType FromPointee2
4097       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4098     QualType ToPointee2
4099       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4100 
4101     //   -- conversion of C* to B* is better than conversion of C* to A*,
4102     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4103       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4104         return ImplicitConversionSequence::Better;
4105       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4106         return ImplicitConversionSequence::Worse;
4107     }
4108 
4109     //   -- conversion of B* to A* is better than conversion of C* to A*,
4110     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4111       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4112         return ImplicitConversionSequence::Better;
4113       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4114         return ImplicitConversionSequence::Worse;
4115     }
4116   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4117              SCS2.Second == ICK_Pointer_Conversion) {
4118     const ObjCObjectPointerType *FromPtr1
4119       = FromType1->getAs<ObjCObjectPointerType>();
4120     const ObjCObjectPointerType *FromPtr2
4121       = FromType2->getAs<ObjCObjectPointerType>();
4122     const ObjCObjectPointerType *ToPtr1
4123       = ToType1->getAs<ObjCObjectPointerType>();
4124     const ObjCObjectPointerType *ToPtr2
4125       = ToType2->getAs<ObjCObjectPointerType>();
4126 
4127     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4128       // Apply the same conversion ranking rules for Objective-C pointer types
4129       // that we do for C++ pointers to class types. However, we employ the
4130       // Objective-C pseudo-subtyping relationship used for assignment of
4131       // Objective-C pointer types.
4132       bool FromAssignLeft
4133         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4134       bool FromAssignRight
4135         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4136       bool ToAssignLeft
4137         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4138       bool ToAssignRight
4139         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4140 
4141       // A conversion to an a non-id object pointer type or qualified 'id'
4142       // type is better than a conversion to 'id'.
4143       if (ToPtr1->isObjCIdType() &&
4144           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4145         return ImplicitConversionSequence::Worse;
4146       if (ToPtr2->isObjCIdType() &&
4147           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4148         return ImplicitConversionSequence::Better;
4149 
4150       // A conversion to a non-id object pointer type is better than a
4151       // conversion to a qualified 'id' type
4152       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4153         return ImplicitConversionSequence::Worse;
4154       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4155         return ImplicitConversionSequence::Better;
4156 
4157       // A conversion to an a non-Class object pointer type or qualified 'Class'
4158       // type is better than a conversion to 'Class'.
4159       if (ToPtr1->isObjCClassType() &&
4160           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4161         return ImplicitConversionSequence::Worse;
4162       if (ToPtr2->isObjCClassType() &&
4163           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4164         return ImplicitConversionSequence::Better;
4165 
4166       // A conversion to a non-Class object pointer type is better than a
4167       // conversion to a qualified 'Class' type.
4168       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4169         return ImplicitConversionSequence::Worse;
4170       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4171         return ImplicitConversionSequence::Better;
4172 
4173       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4174       if (S.Context.hasSameType(FromType1, FromType2) &&
4175           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4176           (ToAssignLeft != ToAssignRight)) {
4177         if (FromPtr1->isSpecialized()) {
4178           // "conversion of B<A> * to B * is better than conversion of B * to
4179           // C *.
4180           bool IsFirstSame =
4181               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4182           bool IsSecondSame =
4183               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4184           if (IsFirstSame) {
4185             if (!IsSecondSame)
4186               return ImplicitConversionSequence::Better;
4187           } else if (IsSecondSame)
4188             return ImplicitConversionSequence::Worse;
4189         }
4190         return ToAssignLeft? ImplicitConversionSequence::Worse
4191                            : ImplicitConversionSequence::Better;
4192       }
4193 
4194       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4195       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4196           (FromAssignLeft != FromAssignRight))
4197         return FromAssignLeft? ImplicitConversionSequence::Better
4198         : ImplicitConversionSequence::Worse;
4199     }
4200   }
4201 
4202   // Ranking of member-pointer types.
4203   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4204       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4205       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4206     const MemberPointerType * FromMemPointer1 =
4207                                         FromType1->getAs<MemberPointerType>();
4208     const MemberPointerType * ToMemPointer1 =
4209                                           ToType1->getAs<MemberPointerType>();
4210     const MemberPointerType * FromMemPointer2 =
4211                                           FromType2->getAs<MemberPointerType>();
4212     const MemberPointerType * ToMemPointer2 =
4213                                           ToType2->getAs<MemberPointerType>();
4214     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4215     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4216     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4217     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4218     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4219     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4220     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4221     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4222     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4223     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4224       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4225         return ImplicitConversionSequence::Worse;
4226       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4227         return ImplicitConversionSequence::Better;
4228     }
4229     // conversion of B::* to C::* is better than conversion of A::* to C::*
4230     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4231       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4232         return ImplicitConversionSequence::Better;
4233       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4234         return ImplicitConversionSequence::Worse;
4235     }
4236   }
4237 
4238   if (SCS1.Second == ICK_Derived_To_Base) {
4239     //   -- conversion of C to B is better than conversion of C to A,
4240     //   -- binding of an expression of type C to a reference of type
4241     //      B& is better than binding an expression of type C to a
4242     //      reference of type A&,
4243     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4244         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4245       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4246         return ImplicitConversionSequence::Better;
4247       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4248         return ImplicitConversionSequence::Worse;
4249     }
4250 
4251     //   -- conversion of B to A is better than conversion of C to A.
4252     //   -- binding of an expression of type B to a reference of type
4253     //      A& is better than binding an expression of type C to a
4254     //      reference of type A&,
4255     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4256         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4257       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4258         return ImplicitConversionSequence::Better;
4259       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4260         return ImplicitConversionSequence::Worse;
4261     }
4262   }
4263 
4264   return ImplicitConversionSequence::Indistinguishable;
4265 }
4266 
4267 /// Determine whether the given type is valid, e.g., it is not an invalid
4268 /// C++ class.
4269 static bool isTypeValid(QualType T) {
4270   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4271     return !Record->isInvalidDecl();
4272 
4273   return true;
4274 }
4275 
4276 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4277 /// determine whether they are reference-related,
4278 /// reference-compatible, reference-compatible with added
4279 /// qualification, or incompatible, for use in C++ initialization by
4280 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4281 /// type, and the first type (T1) is the pointee type of the reference
4282 /// type being initialized.
4283 Sema::ReferenceCompareResult
4284 Sema::CompareReferenceRelationship(SourceLocation Loc,
4285                                    QualType OrigT1, QualType OrigT2,
4286                                    bool &DerivedToBase,
4287                                    bool &ObjCConversion,
4288                                    bool &ObjCLifetimeConversion) {
4289   assert(!OrigT1->isReferenceType() &&
4290     "T1 must be the pointee type of the reference type");
4291   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4292 
4293   QualType T1 = Context.getCanonicalType(OrigT1);
4294   QualType T2 = Context.getCanonicalType(OrigT2);
4295   Qualifiers T1Quals, T2Quals;
4296   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4297   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4298 
4299   // C++ [dcl.init.ref]p4:
4300   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4301   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4302   //   T1 is a base class of T2.
4303   DerivedToBase = false;
4304   ObjCConversion = false;
4305   ObjCLifetimeConversion = false;
4306   QualType ConvertedT2;
4307   if (UnqualT1 == UnqualT2) {
4308     // Nothing to do.
4309   } else if (isCompleteType(Loc, OrigT2) &&
4310              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4311              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4312     DerivedToBase = true;
4313   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4314            UnqualT2->isObjCObjectOrInterfaceType() &&
4315            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4316     ObjCConversion = true;
4317   else if (UnqualT2->isFunctionType() &&
4318            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4319     // C++1z [dcl.init.ref]p4:
4320     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4321     //   function" and T1 is "function"
4322     //
4323     // We extend this to also apply to 'noreturn', so allow any function
4324     // conversion between function types.
4325     return Ref_Compatible;
4326   else
4327     return Ref_Incompatible;
4328 
4329   // At this point, we know that T1 and T2 are reference-related (at
4330   // least).
4331 
4332   // If the type is an array type, promote the element qualifiers to the type
4333   // for comparison.
4334   if (isa<ArrayType>(T1) && T1Quals)
4335     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4336   if (isa<ArrayType>(T2) && T2Quals)
4337     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4338 
4339   // C++ [dcl.init.ref]p4:
4340   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4341   //   reference-related to T2 and cv1 is the same cv-qualification
4342   //   as, or greater cv-qualification than, cv2. For purposes of
4343   //   overload resolution, cases for which cv1 is greater
4344   //   cv-qualification than cv2 are identified as
4345   //   reference-compatible with added qualification (see 13.3.3.2).
4346   //
4347   // Note that we also require equivalence of Objective-C GC and address-space
4348   // qualifiers when performing these computations, so that e.g., an int in
4349   // address space 1 is not reference-compatible with an int in address
4350   // space 2.
4351   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4352       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4353     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4354       ObjCLifetimeConversion = true;
4355 
4356     T1Quals.removeObjCLifetime();
4357     T2Quals.removeObjCLifetime();
4358   }
4359 
4360   // MS compiler ignores __unaligned qualifier for references; do the same.
4361   T1Quals.removeUnaligned();
4362   T2Quals.removeUnaligned();
4363 
4364   if (T1Quals.compatiblyIncludes(T2Quals))
4365     return Ref_Compatible;
4366   else
4367     return Ref_Related;
4368 }
4369 
4370 /// Look for a user-defined conversion to a value reference-compatible
4371 ///        with DeclType. Return true if something definite is found.
4372 static bool
4373 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4374                          QualType DeclType, SourceLocation DeclLoc,
4375                          Expr *Init, QualType T2, bool AllowRvalues,
4376                          bool AllowExplicit) {
4377   assert(T2->isRecordType() && "Can only find conversions of record types.");
4378   CXXRecordDecl *T2RecordDecl
4379     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4380 
4381   OverloadCandidateSet CandidateSet(
4382       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4383   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4384   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4385     NamedDecl *D = *I;
4386     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4387     if (isa<UsingShadowDecl>(D))
4388       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4389 
4390     FunctionTemplateDecl *ConvTemplate
4391       = dyn_cast<FunctionTemplateDecl>(D);
4392     CXXConversionDecl *Conv;
4393     if (ConvTemplate)
4394       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4395     else
4396       Conv = cast<CXXConversionDecl>(D);
4397 
4398     // If this is an explicit conversion, and we're not allowed to consider
4399     // explicit conversions, skip it.
4400     if (!AllowExplicit && Conv->isExplicit())
4401       continue;
4402 
4403     if (AllowRvalues) {
4404       bool DerivedToBase = false;
4405       bool ObjCConversion = false;
4406       bool ObjCLifetimeConversion = false;
4407 
4408       // If we are initializing an rvalue reference, don't permit conversion
4409       // functions that return lvalues.
4410       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4411         const ReferenceType *RefType
4412           = Conv->getConversionType()->getAs<LValueReferenceType>();
4413         if (RefType && !RefType->getPointeeType()->isFunctionType())
4414           continue;
4415       }
4416 
4417       if (!ConvTemplate &&
4418           S.CompareReferenceRelationship(
4419             DeclLoc,
4420             Conv->getConversionType().getNonReferenceType()
4421               .getUnqualifiedType(),
4422             DeclType.getNonReferenceType().getUnqualifiedType(),
4423             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4424           Sema::Ref_Incompatible)
4425         continue;
4426     } else {
4427       // If the conversion function doesn't return a reference type,
4428       // it can't be considered for this conversion. An rvalue reference
4429       // is only acceptable if its referencee is a function type.
4430 
4431       const ReferenceType *RefType =
4432         Conv->getConversionType()->getAs<ReferenceType>();
4433       if (!RefType ||
4434           (!RefType->isLValueReferenceType() &&
4435            !RefType->getPointeeType()->isFunctionType()))
4436         continue;
4437     }
4438 
4439     if (ConvTemplate)
4440       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4441                                        Init, DeclType, CandidateSet,
4442                                        /*AllowObjCConversionOnExplicit=*/false);
4443     else
4444       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4445                                DeclType, CandidateSet,
4446                                /*AllowObjCConversionOnExplicit=*/false);
4447   }
4448 
4449   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4450 
4451   OverloadCandidateSet::iterator Best;
4452   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4453   case OR_Success:
4454     // C++ [over.ics.ref]p1:
4455     //
4456     //   [...] If the parameter binds directly to the result of
4457     //   applying a conversion function to the argument
4458     //   expression, the implicit conversion sequence is a
4459     //   user-defined conversion sequence (13.3.3.1.2), with the
4460     //   second standard conversion sequence either an identity
4461     //   conversion or, if the conversion function returns an
4462     //   entity of a type that is a derived class of the parameter
4463     //   type, a derived-to-base Conversion.
4464     if (!Best->FinalConversion.DirectBinding)
4465       return false;
4466 
4467     ICS.setUserDefined();
4468     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4469     ICS.UserDefined.After = Best->FinalConversion;
4470     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4471     ICS.UserDefined.ConversionFunction = Best->Function;
4472     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4473     ICS.UserDefined.EllipsisConversion = false;
4474     assert(ICS.UserDefined.After.ReferenceBinding &&
4475            ICS.UserDefined.After.DirectBinding &&
4476            "Expected a direct reference binding!");
4477     return true;
4478 
4479   case OR_Ambiguous:
4480     ICS.setAmbiguous();
4481     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4482          Cand != CandidateSet.end(); ++Cand)
4483       if (Cand->Viable)
4484         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4485     return true;
4486 
4487   case OR_No_Viable_Function:
4488   case OR_Deleted:
4489     // There was no suitable conversion, or we found a deleted
4490     // conversion; continue with other checks.
4491     return false;
4492   }
4493 
4494   llvm_unreachable("Invalid OverloadResult!");
4495 }
4496 
4497 /// Compute an implicit conversion sequence for reference
4498 /// initialization.
4499 static ImplicitConversionSequence
4500 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4501                  SourceLocation DeclLoc,
4502                  bool SuppressUserConversions,
4503                  bool AllowExplicit) {
4504   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4505 
4506   // Most paths end in a failed conversion.
4507   ImplicitConversionSequence ICS;
4508   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4509 
4510   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4511   QualType T2 = Init->getType();
4512 
4513   // If the initializer is the address of an overloaded function, try
4514   // to resolve the overloaded function. If all goes well, T2 is the
4515   // type of the resulting function.
4516   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4517     DeclAccessPair Found;
4518     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4519                                                                 false, Found))
4520       T2 = Fn->getType();
4521   }
4522 
4523   // Compute some basic properties of the types and the initializer.
4524   bool isRValRef = DeclType->isRValueReferenceType();
4525   bool DerivedToBase = false;
4526   bool ObjCConversion = false;
4527   bool ObjCLifetimeConversion = false;
4528   Expr::Classification InitCategory = Init->Classify(S.Context);
4529   Sema::ReferenceCompareResult RefRelationship
4530     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4531                                      ObjCConversion, ObjCLifetimeConversion);
4532 
4533 
4534   // C++0x [dcl.init.ref]p5:
4535   //   A reference to type "cv1 T1" is initialized by an expression
4536   //   of type "cv2 T2" as follows:
4537 
4538   //     -- If reference is an lvalue reference and the initializer expression
4539   if (!isRValRef) {
4540     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4541     //        reference-compatible with "cv2 T2," or
4542     //
4543     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4544     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4545       // C++ [over.ics.ref]p1:
4546       //   When a parameter of reference type binds directly (8.5.3)
4547       //   to an argument expression, the implicit conversion sequence
4548       //   is the identity conversion, unless the argument expression
4549       //   has a type that is a derived class of the parameter type,
4550       //   in which case the implicit conversion sequence is a
4551       //   derived-to-base Conversion (13.3.3.1).
4552       ICS.setStandard();
4553       ICS.Standard.First = ICK_Identity;
4554       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4555                          : ObjCConversion? ICK_Compatible_Conversion
4556                          : ICK_Identity;
4557       ICS.Standard.Third = ICK_Identity;
4558       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4559       ICS.Standard.setToType(0, T2);
4560       ICS.Standard.setToType(1, T1);
4561       ICS.Standard.setToType(2, T1);
4562       ICS.Standard.ReferenceBinding = true;
4563       ICS.Standard.DirectBinding = true;
4564       ICS.Standard.IsLvalueReference = !isRValRef;
4565       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4566       ICS.Standard.BindsToRvalue = false;
4567       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4568       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4569       ICS.Standard.CopyConstructor = nullptr;
4570       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4571 
4572       // Nothing more to do: the inaccessibility/ambiguity check for
4573       // derived-to-base conversions is suppressed when we're
4574       // computing the implicit conversion sequence (C++
4575       // [over.best.ics]p2).
4576       return ICS;
4577     }
4578 
4579     //       -- has a class type (i.e., T2 is a class type), where T1 is
4580     //          not reference-related to T2, and can be implicitly
4581     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4582     //          is reference-compatible with "cv3 T3" 92) (this
4583     //          conversion is selected by enumerating the applicable
4584     //          conversion functions (13.3.1.6) and choosing the best
4585     //          one through overload resolution (13.3)),
4586     if (!SuppressUserConversions && T2->isRecordType() &&
4587         S.isCompleteType(DeclLoc, T2) &&
4588         RefRelationship == Sema::Ref_Incompatible) {
4589       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4590                                    Init, T2, /*AllowRvalues=*/false,
4591                                    AllowExplicit))
4592         return ICS;
4593     }
4594   }
4595 
4596   //     -- Otherwise, the reference shall be an lvalue reference to a
4597   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4598   //        shall be an rvalue reference.
4599   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4600     return ICS;
4601 
4602   //       -- If the initializer expression
4603   //
4604   //            -- is an xvalue, class prvalue, array prvalue or function
4605   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4606   if (RefRelationship == Sema::Ref_Compatible &&
4607       (InitCategory.isXValue() ||
4608        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4609        (InitCategory.isLValue() && T2->isFunctionType()))) {
4610     ICS.setStandard();
4611     ICS.Standard.First = ICK_Identity;
4612     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4613                       : ObjCConversion? ICK_Compatible_Conversion
4614                       : ICK_Identity;
4615     ICS.Standard.Third = ICK_Identity;
4616     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4617     ICS.Standard.setToType(0, T2);
4618     ICS.Standard.setToType(1, T1);
4619     ICS.Standard.setToType(2, T1);
4620     ICS.Standard.ReferenceBinding = true;
4621     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4622     // binding unless we're binding to a class prvalue.
4623     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4624     // allow the use of rvalue references in C++98/03 for the benefit of
4625     // standard library implementors; therefore, we need the xvalue check here.
4626     ICS.Standard.DirectBinding =
4627       S.getLangOpts().CPlusPlus11 ||
4628       !(InitCategory.isPRValue() || T2->isRecordType());
4629     ICS.Standard.IsLvalueReference = !isRValRef;
4630     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4631     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4632     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4633     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4634     ICS.Standard.CopyConstructor = nullptr;
4635     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4636     return ICS;
4637   }
4638 
4639   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4640   //               reference-related to T2, and can be implicitly converted to
4641   //               an xvalue, class prvalue, or function lvalue of type
4642   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4643   //               "cv3 T3",
4644   //
4645   //          then the reference is bound to the value of the initializer
4646   //          expression in the first case and to the result of the conversion
4647   //          in the second case (or, in either case, to an appropriate base
4648   //          class subobject).
4649   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4650       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4651       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4652                                Init, T2, /*AllowRvalues=*/true,
4653                                AllowExplicit)) {
4654     // In the second case, if the reference is an rvalue reference
4655     // and the second standard conversion sequence of the
4656     // user-defined conversion sequence includes an lvalue-to-rvalue
4657     // conversion, the program is ill-formed.
4658     if (ICS.isUserDefined() && isRValRef &&
4659         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4660       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4661 
4662     return ICS;
4663   }
4664 
4665   // A temporary of function type cannot be created; don't even try.
4666   if (T1->isFunctionType())
4667     return ICS;
4668 
4669   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4670   //          initialized from the initializer expression using the
4671   //          rules for a non-reference copy initialization (8.5). The
4672   //          reference is then bound to the temporary. If T1 is
4673   //          reference-related to T2, cv1 must be the same
4674   //          cv-qualification as, or greater cv-qualification than,
4675   //          cv2; otherwise, the program is ill-formed.
4676   if (RefRelationship == Sema::Ref_Related) {
4677     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4678     // we would be reference-compatible or reference-compatible with
4679     // added qualification. But that wasn't the case, so the reference
4680     // initialization fails.
4681     //
4682     // Note that we only want to check address spaces and cvr-qualifiers here.
4683     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4684     Qualifiers T1Quals = T1.getQualifiers();
4685     Qualifiers T2Quals = T2.getQualifiers();
4686     T1Quals.removeObjCGCAttr();
4687     T1Quals.removeObjCLifetime();
4688     T2Quals.removeObjCGCAttr();
4689     T2Quals.removeObjCLifetime();
4690     // MS compiler ignores __unaligned qualifier for references; do the same.
4691     T1Quals.removeUnaligned();
4692     T2Quals.removeUnaligned();
4693     if (!T1Quals.compatiblyIncludes(T2Quals))
4694       return ICS;
4695   }
4696 
4697   // If at least one of the types is a class type, the types are not
4698   // related, and we aren't allowed any user conversions, the
4699   // reference binding fails. This case is important for breaking
4700   // recursion, since TryImplicitConversion below will attempt to
4701   // create a temporary through the use of a copy constructor.
4702   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4703       (T1->isRecordType() || T2->isRecordType()))
4704     return ICS;
4705 
4706   // If T1 is reference-related to T2 and the reference is an rvalue
4707   // reference, the initializer expression shall not be an lvalue.
4708   if (RefRelationship >= Sema::Ref_Related &&
4709       isRValRef && Init->Classify(S.Context).isLValue())
4710     return ICS;
4711 
4712   // C++ [over.ics.ref]p2:
4713   //   When a parameter of reference type is not bound directly to
4714   //   an argument expression, the conversion sequence is the one
4715   //   required to convert the argument expression to the
4716   //   underlying type of the reference according to
4717   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4718   //   to copy-initializing a temporary of the underlying type with
4719   //   the argument expression. Any difference in top-level
4720   //   cv-qualification is subsumed by the initialization itself
4721   //   and does not constitute a conversion.
4722   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4723                               /*AllowExplicit=*/false,
4724                               /*InOverloadResolution=*/false,
4725                               /*CStyle=*/false,
4726                               /*AllowObjCWritebackConversion=*/false,
4727                               /*AllowObjCConversionOnExplicit=*/false);
4728 
4729   // Of course, that's still a reference binding.
4730   if (ICS.isStandard()) {
4731     ICS.Standard.ReferenceBinding = true;
4732     ICS.Standard.IsLvalueReference = !isRValRef;
4733     ICS.Standard.BindsToFunctionLvalue = false;
4734     ICS.Standard.BindsToRvalue = true;
4735     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4736     ICS.Standard.ObjCLifetimeConversionBinding = false;
4737   } else if (ICS.isUserDefined()) {
4738     const ReferenceType *LValRefType =
4739         ICS.UserDefined.ConversionFunction->getReturnType()
4740             ->getAs<LValueReferenceType>();
4741 
4742     // C++ [over.ics.ref]p3:
4743     //   Except for an implicit object parameter, for which see 13.3.1, a
4744     //   standard conversion sequence cannot be formed if it requires [...]
4745     //   binding an rvalue reference to an lvalue other than a function
4746     //   lvalue.
4747     // Note that the function case is not possible here.
4748     if (DeclType->isRValueReferenceType() && LValRefType) {
4749       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4750       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4751       // reference to an rvalue!
4752       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4753       return ICS;
4754     }
4755 
4756     ICS.UserDefined.After.ReferenceBinding = true;
4757     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4758     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4759     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4760     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4761     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4762   }
4763 
4764   return ICS;
4765 }
4766 
4767 static ImplicitConversionSequence
4768 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4769                       bool SuppressUserConversions,
4770                       bool InOverloadResolution,
4771                       bool AllowObjCWritebackConversion,
4772                       bool AllowExplicit = false);
4773 
4774 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4775 /// initializer list From.
4776 static ImplicitConversionSequence
4777 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4778                   bool SuppressUserConversions,
4779                   bool InOverloadResolution,
4780                   bool AllowObjCWritebackConversion) {
4781   // C++11 [over.ics.list]p1:
4782   //   When an argument is an initializer list, it is not an expression and
4783   //   special rules apply for converting it to a parameter type.
4784 
4785   ImplicitConversionSequence Result;
4786   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4787 
4788   // We need a complete type for what follows. Incomplete types can never be
4789   // initialized from init lists.
4790   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4791     return Result;
4792 
4793   // Per DR1467:
4794   //   If the parameter type is a class X and the initializer list has a single
4795   //   element of type cv U, where U is X or a class derived from X, the
4796   //   implicit conversion sequence is the one required to convert the element
4797   //   to the parameter type.
4798   //
4799   //   Otherwise, if the parameter type is a character array [... ]
4800   //   and the initializer list has a single element that is an
4801   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4802   //   implicit conversion sequence is the identity conversion.
4803   if (From->getNumInits() == 1) {
4804     if (ToType->isRecordType()) {
4805       QualType InitType = From->getInit(0)->getType();
4806       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4807           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4808         return TryCopyInitialization(S, From->getInit(0), ToType,
4809                                      SuppressUserConversions,
4810                                      InOverloadResolution,
4811                                      AllowObjCWritebackConversion);
4812     }
4813     // FIXME: Check the other conditions here: array of character type,
4814     // initializer is a string literal.
4815     if (ToType->isArrayType()) {
4816       InitializedEntity Entity =
4817         InitializedEntity::InitializeParameter(S.Context, ToType,
4818                                                /*Consumed=*/false);
4819       if (S.CanPerformCopyInitialization(Entity, From)) {
4820         Result.setStandard();
4821         Result.Standard.setAsIdentityConversion();
4822         Result.Standard.setFromType(ToType);
4823         Result.Standard.setAllToTypes(ToType);
4824         return Result;
4825       }
4826     }
4827   }
4828 
4829   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4830   // C++11 [over.ics.list]p2:
4831   //   If the parameter type is std::initializer_list<X> or "array of X" and
4832   //   all the elements can be implicitly converted to X, the implicit
4833   //   conversion sequence is the worst conversion necessary to convert an
4834   //   element of the list to X.
4835   //
4836   // C++14 [over.ics.list]p3:
4837   //   Otherwise, if the parameter type is "array of N X", if the initializer
4838   //   list has exactly N elements or if it has fewer than N elements and X is
4839   //   default-constructible, and if all the elements of the initializer list
4840   //   can be implicitly converted to X, the implicit conversion sequence is
4841   //   the worst conversion necessary to convert an element of the list to X.
4842   //
4843   // FIXME: We're missing a lot of these checks.
4844   bool toStdInitializerList = false;
4845   QualType X;
4846   if (ToType->isArrayType())
4847     X = S.Context.getAsArrayType(ToType)->getElementType();
4848   else
4849     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4850   if (!X.isNull()) {
4851     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4852       Expr *Init = From->getInit(i);
4853       ImplicitConversionSequence ICS =
4854           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4855                                 InOverloadResolution,
4856                                 AllowObjCWritebackConversion);
4857       // If a single element isn't convertible, fail.
4858       if (ICS.isBad()) {
4859         Result = ICS;
4860         break;
4861       }
4862       // Otherwise, look for the worst conversion.
4863       if (Result.isBad() || CompareImplicitConversionSequences(
4864                                 S, From->getBeginLoc(), ICS, Result) ==
4865                                 ImplicitConversionSequence::Worse)
4866         Result = ICS;
4867     }
4868 
4869     // For an empty list, we won't have computed any conversion sequence.
4870     // Introduce the identity conversion sequence.
4871     if (From->getNumInits() == 0) {
4872       Result.setStandard();
4873       Result.Standard.setAsIdentityConversion();
4874       Result.Standard.setFromType(ToType);
4875       Result.Standard.setAllToTypes(ToType);
4876     }
4877 
4878     Result.setStdInitializerListElement(toStdInitializerList);
4879     return Result;
4880   }
4881 
4882   // C++14 [over.ics.list]p4:
4883   // C++11 [over.ics.list]p3:
4884   //   Otherwise, if the parameter is a non-aggregate class X and overload
4885   //   resolution chooses a single best constructor [...] the implicit
4886   //   conversion sequence is a user-defined conversion sequence. If multiple
4887   //   constructors are viable but none is better than the others, the
4888   //   implicit conversion sequence is a user-defined conversion sequence.
4889   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4890     // This function can deal with initializer lists.
4891     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4892                                     /*AllowExplicit=*/false,
4893                                     InOverloadResolution, /*CStyle=*/false,
4894                                     AllowObjCWritebackConversion,
4895                                     /*AllowObjCConversionOnExplicit=*/false);
4896   }
4897 
4898   // C++14 [over.ics.list]p5:
4899   // C++11 [over.ics.list]p4:
4900   //   Otherwise, if the parameter has an aggregate type which can be
4901   //   initialized from the initializer list [...] the implicit conversion
4902   //   sequence is a user-defined conversion sequence.
4903   if (ToType->isAggregateType()) {
4904     // Type is an aggregate, argument is an init list. At this point it comes
4905     // down to checking whether the initialization works.
4906     // FIXME: Find out whether this parameter is consumed or not.
4907     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4908     // need to call into the initialization code here; overload resolution
4909     // should not be doing that.
4910     InitializedEntity Entity =
4911         InitializedEntity::InitializeParameter(S.Context, ToType,
4912                                                /*Consumed=*/false);
4913     if (S.CanPerformCopyInitialization(Entity, From)) {
4914       Result.setUserDefined();
4915       Result.UserDefined.Before.setAsIdentityConversion();
4916       // Initializer lists don't have a type.
4917       Result.UserDefined.Before.setFromType(QualType());
4918       Result.UserDefined.Before.setAllToTypes(QualType());
4919 
4920       Result.UserDefined.After.setAsIdentityConversion();
4921       Result.UserDefined.After.setFromType(ToType);
4922       Result.UserDefined.After.setAllToTypes(ToType);
4923       Result.UserDefined.ConversionFunction = nullptr;
4924     }
4925     return Result;
4926   }
4927 
4928   // C++14 [over.ics.list]p6:
4929   // C++11 [over.ics.list]p5:
4930   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4931   if (ToType->isReferenceType()) {
4932     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4933     // mention initializer lists in any way. So we go by what list-
4934     // initialization would do and try to extrapolate from that.
4935 
4936     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4937 
4938     // If the initializer list has a single element that is reference-related
4939     // to the parameter type, we initialize the reference from that.
4940     if (From->getNumInits() == 1) {
4941       Expr *Init = From->getInit(0);
4942 
4943       QualType T2 = Init->getType();
4944 
4945       // If the initializer is the address of an overloaded function, try
4946       // to resolve the overloaded function. If all goes well, T2 is the
4947       // type of the resulting function.
4948       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4949         DeclAccessPair Found;
4950         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4951                                    Init, ToType, false, Found))
4952           T2 = Fn->getType();
4953       }
4954 
4955       // Compute some basic properties of the types and the initializer.
4956       bool dummy1 = false;
4957       bool dummy2 = false;
4958       bool dummy3 = false;
4959       Sema::ReferenceCompareResult RefRelationship =
4960           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4961                                          dummy2, dummy3);
4962 
4963       if (RefRelationship >= Sema::Ref_Related) {
4964         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4965                                 SuppressUserConversions,
4966                                 /*AllowExplicit=*/false);
4967       }
4968     }
4969 
4970     // Otherwise, we bind the reference to a temporary created from the
4971     // initializer list.
4972     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4973                                InOverloadResolution,
4974                                AllowObjCWritebackConversion);
4975     if (Result.isFailure())
4976       return Result;
4977     assert(!Result.isEllipsis() &&
4978            "Sub-initialization cannot result in ellipsis conversion.");
4979 
4980     // Can we even bind to a temporary?
4981     if (ToType->isRValueReferenceType() ||
4982         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4983       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4984                                             Result.UserDefined.After;
4985       SCS.ReferenceBinding = true;
4986       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4987       SCS.BindsToRvalue = true;
4988       SCS.BindsToFunctionLvalue = false;
4989       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4990       SCS.ObjCLifetimeConversionBinding = false;
4991     } else
4992       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4993                     From, ToType);
4994     return Result;
4995   }
4996 
4997   // C++14 [over.ics.list]p7:
4998   // C++11 [over.ics.list]p6:
4999   //   Otherwise, if the parameter type is not a class:
5000   if (!ToType->isRecordType()) {
5001     //    - if the initializer list has one element that is not itself an
5002     //      initializer list, the implicit conversion sequence is the one
5003     //      required to convert the element to the parameter type.
5004     unsigned NumInits = From->getNumInits();
5005     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5006       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5007                                      SuppressUserConversions,
5008                                      InOverloadResolution,
5009                                      AllowObjCWritebackConversion);
5010     //    - if the initializer list has no elements, the implicit conversion
5011     //      sequence is the identity conversion.
5012     else if (NumInits == 0) {
5013       Result.setStandard();
5014       Result.Standard.setAsIdentityConversion();
5015       Result.Standard.setFromType(ToType);
5016       Result.Standard.setAllToTypes(ToType);
5017     }
5018     return Result;
5019   }
5020 
5021   // C++14 [over.ics.list]p8:
5022   // C++11 [over.ics.list]p7:
5023   //   In all cases other than those enumerated above, no conversion is possible
5024   return Result;
5025 }
5026 
5027 /// TryCopyInitialization - Try to copy-initialize a value of type
5028 /// ToType from the expression From. Return the implicit conversion
5029 /// sequence required to pass this argument, which may be a bad
5030 /// conversion sequence (meaning that the argument cannot be passed to
5031 /// a parameter of this type). If @p SuppressUserConversions, then we
5032 /// do not permit any user-defined conversion sequences.
5033 static ImplicitConversionSequence
5034 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5035                       bool SuppressUserConversions,
5036                       bool InOverloadResolution,
5037                       bool AllowObjCWritebackConversion,
5038                       bool AllowExplicit) {
5039   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5040     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5041                              InOverloadResolution,AllowObjCWritebackConversion);
5042 
5043   if (ToType->isReferenceType())
5044     return TryReferenceInit(S, From, ToType,
5045                             /*FIXME:*/ From->getBeginLoc(),
5046                             SuppressUserConversions, AllowExplicit);
5047 
5048   return TryImplicitConversion(S, From, ToType,
5049                                SuppressUserConversions,
5050                                /*AllowExplicit=*/false,
5051                                InOverloadResolution,
5052                                /*CStyle=*/false,
5053                                AllowObjCWritebackConversion,
5054                                /*AllowObjCConversionOnExplicit=*/false);
5055 }
5056 
5057 static bool TryCopyInitialization(const CanQualType FromQTy,
5058                                   const CanQualType ToQTy,
5059                                   Sema &S,
5060                                   SourceLocation Loc,
5061                                   ExprValueKind FromVK) {
5062   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5063   ImplicitConversionSequence ICS =
5064     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5065 
5066   return !ICS.isBad();
5067 }
5068 
5069 /// TryObjectArgumentInitialization - Try to initialize the object
5070 /// parameter of the given member function (@c Method) from the
5071 /// expression @p From.
5072 static ImplicitConversionSequence
5073 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5074                                 Expr::Classification FromClassification,
5075                                 CXXMethodDecl *Method,
5076                                 CXXRecordDecl *ActingContext) {
5077   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5078   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5079   //                 const volatile object.
5080   Qualifiers Quals;
5081   if (isa<CXXDestructorDecl>(Method)) {
5082     Quals.addConst();
5083     Quals.addVolatile();
5084   } else {
5085     Quals = Method->getMethodQualifiers();
5086   }
5087 
5088   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5089 
5090   // Set up the conversion sequence as a "bad" conversion, to allow us
5091   // to exit early.
5092   ImplicitConversionSequence ICS;
5093 
5094   // We need to have an object of class type.
5095   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5096     FromType = PT->getPointeeType();
5097 
5098     // When we had a pointer, it's implicitly dereferenced, so we
5099     // better have an lvalue.
5100     assert(FromClassification.isLValue());
5101   }
5102 
5103   assert(FromType->isRecordType());
5104 
5105   // C++0x [over.match.funcs]p4:
5106   //   For non-static member functions, the type of the implicit object
5107   //   parameter is
5108   //
5109   //     - "lvalue reference to cv X" for functions declared without a
5110   //        ref-qualifier or with the & ref-qualifier
5111   //     - "rvalue reference to cv X" for functions declared with the &&
5112   //        ref-qualifier
5113   //
5114   // where X is the class of which the function is a member and cv is the
5115   // cv-qualification on the member function declaration.
5116   //
5117   // However, when finding an implicit conversion sequence for the argument, we
5118   // are not allowed to perform user-defined conversions
5119   // (C++ [over.match.funcs]p5). We perform a simplified version of
5120   // reference binding here, that allows class rvalues to bind to
5121   // non-constant references.
5122 
5123   // First check the qualifiers.
5124   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5125   if (ImplicitParamType.getCVRQualifiers()
5126                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5127       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5128     ICS.setBad(BadConversionSequence::bad_qualifiers,
5129                FromType, ImplicitParamType);
5130     return ICS;
5131   }
5132 
5133   if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5134     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5135     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5136     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5137       ICS.setBad(BadConversionSequence::bad_qualifiers,
5138                  FromType, ImplicitParamType);
5139       return ICS;
5140     }
5141   }
5142 
5143   // Check that we have either the same type or a derived type. It
5144   // affects the conversion rank.
5145   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5146   ImplicitConversionKind SecondKind;
5147   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5148     SecondKind = ICK_Identity;
5149   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5150     SecondKind = ICK_Derived_To_Base;
5151   else {
5152     ICS.setBad(BadConversionSequence::unrelated_class,
5153                FromType, ImplicitParamType);
5154     return ICS;
5155   }
5156 
5157   // Check the ref-qualifier.
5158   switch (Method->getRefQualifier()) {
5159   case RQ_None:
5160     // Do nothing; we don't care about lvalueness or rvalueness.
5161     break;
5162 
5163   case RQ_LValue:
5164     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5165       // non-const lvalue reference cannot bind to an rvalue
5166       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5167                  ImplicitParamType);
5168       return ICS;
5169     }
5170     break;
5171 
5172   case RQ_RValue:
5173     if (!FromClassification.isRValue()) {
5174       // rvalue reference cannot bind to an lvalue
5175       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5176                  ImplicitParamType);
5177       return ICS;
5178     }
5179     break;
5180   }
5181 
5182   // Success. Mark this as a reference binding.
5183   ICS.setStandard();
5184   ICS.Standard.setAsIdentityConversion();
5185   ICS.Standard.Second = SecondKind;
5186   ICS.Standard.setFromType(FromType);
5187   ICS.Standard.setAllToTypes(ImplicitParamType);
5188   ICS.Standard.ReferenceBinding = true;
5189   ICS.Standard.DirectBinding = true;
5190   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5191   ICS.Standard.BindsToFunctionLvalue = false;
5192   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5193   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5194     = (Method->getRefQualifier() == RQ_None);
5195   return ICS;
5196 }
5197 
5198 /// PerformObjectArgumentInitialization - Perform initialization of
5199 /// the implicit object parameter for the given Method with the given
5200 /// expression.
5201 ExprResult
5202 Sema::PerformObjectArgumentInitialization(Expr *From,
5203                                           NestedNameSpecifier *Qualifier,
5204                                           NamedDecl *FoundDecl,
5205                                           CXXMethodDecl *Method) {
5206   QualType FromRecordType, DestType;
5207   QualType ImplicitParamRecordType  =
5208     Method->getThisType()->getAs<PointerType>()->getPointeeType();
5209 
5210   Expr::Classification FromClassification;
5211   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5212     FromRecordType = PT->getPointeeType();
5213     DestType = Method->getThisType();
5214     FromClassification = Expr::Classification::makeSimpleLValue();
5215   } else {
5216     FromRecordType = From->getType();
5217     DestType = ImplicitParamRecordType;
5218     FromClassification = From->Classify(Context);
5219 
5220     // When performing member access on an rvalue, materialize a temporary.
5221     if (From->isRValue()) {
5222       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5223                                             Method->getRefQualifier() !=
5224                                                 RefQualifierKind::RQ_RValue);
5225     }
5226   }
5227 
5228   // Note that we always use the true parent context when performing
5229   // the actual argument initialization.
5230   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5231       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5232       Method->getParent());
5233   if (ICS.isBad()) {
5234     switch (ICS.Bad.Kind) {
5235     case BadConversionSequence::bad_qualifiers: {
5236       Qualifiers FromQs = FromRecordType.getQualifiers();
5237       Qualifiers ToQs = DestType.getQualifiers();
5238       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5239       if (CVR) {
5240         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5241             << Method->getDeclName() << FromRecordType << (CVR - 1)
5242             << From->getSourceRange();
5243         Diag(Method->getLocation(), diag::note_previous_decl)
5244           << Method->getDeclName();
5245         return ExprError();
5246       }
5247       break;
5248     }
5249 
5250     case BadConversionSequence::lvalue_ref_to_rvalue:
5251     case BadConversionSequence::rvalue_ref_to_lvalue: {
5252       bool IsRValueQualified =
5253         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5254       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5255           << Method->getDeclName() << FromClassification.isRValue()
5256           << IsRValueQualified;
5257       Diag(Method->getLocation(), diag::note_previous_decl)
5258         << Method->getDeclName();
5259       return ExprError();
5260     }
5261 
5262     case BadConversionSequence::no_conversion:
5263     case BadConversionSequence::unrelated_class:
5264       break;
5265     }
5266 
5267     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5268            << ImplicitParamRecordType << FromRecordType
5269            << From->getSourceRange();
5270   }
5271 
5272   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5273     ExprResult FromRes =
5274       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5275     if (FromRes.isInvalid())
5276       return ExprError();
5277     From = FromRes.get();
5278   }
5279 
5280   if (!Context.hasSameType(From->getType(), DestType)) {
5281     if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5282       From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5283                              From->getValueKind()).get();
5284     else
5285       From = ImpCastExprToType(From, DestType, CK_NoOp,
5286                              From->getValueKind()).get();
5287   }
5288   return From;
5289 }
5290 
5291 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5292 /// expression From to bool (C++0x [conv]p3).
5293 static ImplicitConversionSequence
5294 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5295   return TryImplicitConversion(S, From, S.Context.BoolTy,
5296                                /*SuppressUserConversions=*/false,
5297                                /*AllowExplicit=*/true,
5298                                /*InOverloadResolution=*/false,
5299                                /*CStyle=*/false,
5300                                /*AllowObjCWritebackConversion=*/false,
5301                                /*AllowObjCConversionOnExplicit=*/false);
5302 }
5303 
5304 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5305 /// of the expression From to bool (C++0x [conv]p3).
5306 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5307   if (checkPlaceholderForOverload(*this, From))
5308     return ExprError();
5309 
5310   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5311   if (!ICS.isBad())
5312     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5313 
5314   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5315     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5316            << From->getType() << From->getSourceRange();
5317   return ExprError();
5318 }
5319 
5320 /// Check that the specified conversion is permitted in a converted constant
5321 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5322 /// is acceptable.
5323 static bool CheckConvertedConstantConversions(Sema &S,
5324                                               StandardConversionSequence &SCS) {
5325   // Since we know that the target type is an integral or unscoped enumeration
5326   // type, most conversion kinds are impossible. All possible First and Third
5327   // conversions are fine.
5328   switch (SCS.Second) {
5329   case ICK_Identity:
5330   case ICK_Function_Conversion:
5331   case ICK_Integral_Promotion:
5332   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5333   case ICK_Zero_Queue_Conversion:
5334     return true;
5335 
5336   case ICK_Boolean_Conversion:
5337     // Conversion from an integral or unscoped enumeration type to bool is
5338     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5339     // conversion, so we allow it in a converted constant expression.
5340     //
5341     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5342     // a lot of popular code. We should at least add a warning for this
5343     // (non-conforming) extension.
5344     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5345            SCS.getToType(2)->isBooleanType();
5346 
5347   case ICK_Pointer_Conversion:
5348   case ICK_Pointer_Member:
5349     // C++1z: null pointer conversions and null member pointer conversions are
5350     // only permitted if the source type is std::nullptr_t.
5351     return SCS.getFromType()->isNullPtrType();
5352 
5353   case ICK_Floating_Promotion:
5354   case ICK_Complex_Promotion:
5355   case ICK_Floating_Conversion:
5356   case ICK_Complex_Conversion:
5357   case ICK_Floating_Integral:
5358   case ICK_Compatible_Conversion:
5359   case ICK_Derived_To_Base:
5360   case ICK_Vector_Conversion:
5361   case ICK_Vector_Splat:
5362   case ICK_Complex_Real:
5363   case ICK_Block_Pointer_Conversion:
5364   case ICK_TransparentUnionConversion:
5365   case ICK_Writeback_Conversion:
5366   case ICK_Zero_Event_Conversion:
5367   case ICK_C_Only_Conversion:
5368   case ICK_Incompatible_Pointer_Conversion:
5369     return false;
5370 
5371   case ICK_Lvalue_To_Rvalue:
5372   case ICK_Array_To_Pointer:
5373   case ICK_Function_To_Pointer:
5374     llvm_unreachable("found a first conversion kind in Second");
5375 
5376   case ICK_Qualification:
5377     llvm_unreachable("found a third conversion kind in Second");
5378 
5379   case ICK_Num_Conversion_Kinds:
5380     break;
5381   }
5382 
5383   llvm_unreachable("unknown conversion kind");
5384 }
5385 
5386 /// CheckConvertedConstantExpression - Check that the expression From is a
5387 /// converted constant expression of type T, perform the conversion and produce
5388 /// the converted expression, per C++11 [expr.const]p3.
5389 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5390                                                    QualType T, APValue &Value,
5391                                                    Sema::CCEKind CCE,
5392                                                    bool RequireInt) {
5393   assert(S.getLangOpts().CPlusPlus11 &&
5394          "converted constant expression outside C++11");
5395 
5396   if (checkPlaceholderForOverload(S, From))
5397     return ExprError();
5398 
5399   // C++1z [expr.const]p3:
5400   //  A converted constant expression of type T is an expression,
5401   //  implicitly converted to type T, where the converted
5402   //  expression is a constant expression and the implicit conversion
5403   //  sequence contains only [... list of conversions ...].
5404   // C++1z [stmt.if]p2:
5405   //  If the if statement is of the form if constexpr, the value of the
5406   //  condition shall be a contextually converted constant expression of type
5407   //  bool.
5408   ImplicitConversionSequence ICS =
5409       CCE == Sema::CCEK_ConstexprIf
5410           ? TryContextuallyConvertToBool(S, From)
5411           : TryCopyInitialization(S, From, T,
5412                                   /*SuppressUserConversions=*/false,
5413                                   /*InOverloadResolution=*/false,
5414                                   /*AllowObjcWritebackConversion=*/false,
5415                                   /*AllowExplicit=*/false);
5416   StandardConversionSequence *SCS = nullptr;
5417   switch (ICS.getKind()) {
5418   case ImplicitConversionSequence::StandardConversion:
5419     SCS = &ICS.Standard;
5420     break;
5421   case ImplicitConversionSequence::UserDefinedConversion:
5422     // We are converting to a non-class type, so the Before sequence
5423     // must be trivial.
5424     SCS = &ICS.UserDefined.After;
5425     break;
5426   case ImplicitConversionSequence::AmbiguousConversion:
5427   case ImplicitConversionSequence::BadConversion:
5428     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5429       return S.Diag(From->getBeginLoc(),
5430                     diag::err_typecheck_converted_constant_expression)
5431              << From->getType() << From->getSourceRange() << T;
5432     return ExprError();
5433 
5434   case ImplicitConversionSequence::EllipsisConversion:
5435     llvm_unreachable("ellipsis conversion in converted constant expression");
5436   }
5437 
5438   // Check that we would only use permitted conversions.
5439   if (!CheckConvertedConstantConversions(S, *SCS)) {
5440     return S.Diag(From->getBeginLoc(),
5441                   diag::err_typecheck_converted_constant_expression_disallowed)
5442            << From->getType() << From->getSourceRange() << T;
5443   }
5444   // [...] and where the reference binding (if any) binds directly.
5445   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5446     return S.Diag(From->getBeginLoc(),
5447                   diag::err_typecheck_converted_constant_expression_indirect)
5448            << From->getType() << From->getSourceRange() << T;
5449   }
5450 
5451   ExprResult Result =
5452       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5453   if (Result.isInvalid())
5454     return Result;
5455 
5456   // Check for a narrowing implicit conversion.
5457   APValue PreNarrowingValue;
5458   QualType PreNarrowingType;
5459   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5460                                 PreNarrowingType)) {
5461   case NK_Dependent_Narrowing:
5462     // Implicit conversion to a narrower type, but the expression is
5463     // value-dependent so we can't tell whether it's actually narrowing.
5464   case NK_Variable_Narrowing:
5465     // Implicit conversion to a narrower type, and the value is not a constant
5466     // expression. We'll diagnose this in a moment.
5467   case NK_Not_Narrowing:
5468     break;
5469 
5470   case NK_Constant_Narrowing:
5471     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5472         << CCE << /*Constant*/ 1
5473         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5474     break;
5475 
5476   case NK_Type_Narrowing:
5477     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5478         << CCE << /*Constant*/ 0 << From->getType() << T;
5479     break;
5480   }
5481 
5482   if (Result.get()->isValueDependent()) {
5483     Value = APValue();
5484     return Result;
5485   }
5486 
5487   // Check the expression is a constant expression.
5488   SmallVector<PartialDiagnosticAt, 8> Notes;
5489   Expr::EvalResult Eval;
5490   Eval.Diag = &Notes;
5491   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5492                                    ? Expr::EvaluateForMangling
5493                                    : Expr::EvaluateForCodeGen;
5494 
5495   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5496       (RequireInt && !Eval.Val.isInt())) {
5497     // The expression can't be folded, so we can't keep it at this position in
5498     // the AST.
5499     Result = ExprError();
5500   } else {
5501     Value = Eval.Val;
5502 
5503     if (Notes.empty()) {
5504       // It's a constant expression.
5505       return ConstantExpr::Create(S.Context, Result.get());
5506     }
5507   }
5508 
5509   // It's not a constant expression. Produce an appropriate diagnostic.
5510   if (Notes.size() == 1 &&
5511       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5512     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5513   else {
5514     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5515         << CCE << From->getSourceRange();
5516     for (unsigned I = 0; I < Notes.size(); ++I)
5517       S.Diag(Notes[I].first, Notes[I].second);
5518   }
5519   return ExprError();
5520 }
5521 
5522 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5523                                                   APValue &Value, CCEKind CCE) {
5524   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5525 }
5526 
5527 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5528                                                   llvm::APSInt &Value,
5529                                                   CCEKind CCE) {
5530   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5531 
5532   APValue V;
5533   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5534   if (!R.isInvalid() && !R.get()->isValueDependent())
5535     Value = V.getInt();
5536   return R;
5537 }
5538 
5539 
5540 /// dropPointerConversions - If the given standard conversion sequence
5541 /// involves any pointer conversions, remove them.  This may change
5542 /// the result type of the conversion sequence.
5543 static void dropPointerConversion(StandardConversionSequence &SCS) {
5544   if (SCS.Second == ICK_Pointer_Conversion) {
5545     SCS.Second = ICK_Identity;
5546     SCS.Third = ICK_Identity;
5547     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5548   }
5549 }
5550 
5551 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5552 /// convert the expression From to an Objective-C pointer type.
5553 static ImplicitConversionSequence
5554 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5555   // Do an implicit conversion to 'id'.
5556   QualType Ty = S.Context.getObjCIdType();
5557   ImplicitConversionSequence ICS
5558     = TryImplicitConversion(S, From, Ty,
5559                             // FIXME: Are these flags correct?
5560                             /*SuppressUserConversions=*/false,
5561                             /*AllowExplicit=*/true,
5562                             /*InOverloadResolution=*/false,
5563                             /*CStyle=*/false,
5564                             /*AllowObjCWritebackConversion=*/false,
5565                             /*AllowObjCConversionOnExplicit=*/true);
5566 
5567   // Strip off any final conversions to 'id'.
5568   switch (ICS.getKind()) {
5569   case ImplicitConversionSequence::BadConversion:
5570   case ImplicitConversionSequence::AmbiguousConversion:
5571   case ImplicitConversionSequence::EllipsisConversion:
5572     break;
5573 
5574   case ImplicitConversionSequence::UserDefinedConversion:
5575     dropPointerConversion(ICS.UserDefined.After);
5576     break;
5577 
5578   case ImplicitConversionSequence::StandardConversion:
5579     dropPointerConversion(ICS.Standard);
5580     break;
5581   }
5582 
5583   return ICS;
5584 }
5585 
5586 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5587 /// conversion of the expression From to an Objective-C pointer type.
5588 /// Returns a valid but null ExprResult if no conversion sequence exists.
5589 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5590   if (checkPlaceholderForOverload(*this, From))
5591     return ExprError();
5592 
5593   QualType Ty = Context.getObjCIdType();
5594   ImplicitConversionSequence ICS =
5595     TryContextuallyConvertToObjCPointer(*this, From);
5596   if (!ICS.isBad())
5597     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5598   return ExprResult();
5599 }
5600 
5601 /// Determine whether the provided type is an integral type, or an enumeration
5602 /// type of a permitted flavor.
5603 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5604   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5605                                  : T->isIntegralOrUnscopedEnumerationType();
5606 }
5607 
5608 static ExprResult
5609 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5610                             Sema::ContextualImplicitConverter &Converter,
5611                             QualType T, UnresolvedSetImpl &ViableConversions) {
5612 
5613   if (Converter.Suppress)
5614     return ExprError();
5615 
5616   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5617   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5618     CXXConversionDecl *Conv =
5619         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5620     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5621     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5622   }
5623   return From;
5624 }
5625 
5626 static bool
5627 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5628                            Sema::ContextualImplicitConverter &Converter,
5629                            QualType T, bool HadMultipleCandidates,
5630                            UnresolvedSetImpl &ExplicitConversions) {
5631   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5632     DeclAccessPair Found = ExplicitConversions[0];
5633     CXXConversionDecl *Conversion =
5634         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5635 
5636     // The user probably meant to invoke the given explicit
5637     // conversion; use it.
5638     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5639     std::string TypeStr;
5640     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5641 
5642     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5643         << FixItHint::CreateInsertion(From->getBeginLoc(),
5644                                       "static_cast<" + TypeStr + ">(")
5645         << FixItHint::CreateInsertion(
5646                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5647     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5648 
5649     // If we aren't in a SFINAE context, build a call to the
5650     // explicit conversion function.
5651     if (SemaRef.isSFINAEContext())
5652       return true;
5653 
5654     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5655     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5656                                                        HadMultipleCandidates);
5657     if (Result.isInvalid())
5658       return true;
5659     // Record usage of conversion in an implicit cast.
5660     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5661                                     CK_UserDefinedConversion, Result.get(),
5662                                     nullptr, Result.get()->getValueKind());
5663   }
5664   return false;
5665 }
5666 
5667 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5668                              Sema::ContextualImplicitConverter &Converter,
5669                              QualType T, bool HadMultipleCandidates,
5670                              DeclAccessPair &Found) {
5671   CXXConversionDecl *Conversion =
5672       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5673   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5674 
5675   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5676   if (!Converter.SuppressConversion) {
5677     if (SemaRef.isSFINAEContext())
5678       return true;
5679 
5680     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5681         << From->getSourceRange();
5682   }
5683 
5684   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5685                                                      HadMultipleCandidates);
5686   if (Result.isInvalid())
5687     return true;
5688   // Record usage of conversion in an implicit cast.
5689   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5690                                   CK_UserDefinedConversion, Result.get(),
5691                                   nullptr, Result.get()->getValueKind());
5692   return false;
5693 }
5694 
5695 static ExprResult finishContextualImplicitConversion(
5696     Sema &SemaRef, SourceLocation Loc, Expr *From,
5697     Sema::ContextualImplicitConverter &Converter) {
5698   if (!Converter.match(From->getType()) && !Converter.Suppress)
5699     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5700         << From->getSourceRange();
5701 
5702   return SemaRef.DefaultLvalueConversion(From);
5703 }
5704 
5705 static void
5706 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5707                                   UnresolvedSetImpl &ViableConversions,
5708                                   OverloadCandidateSet &CandidateSet) {
5709   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5710     DeclAccessPair FoundDecl = ViableConversions[I];
5711     NamedDecl *D = FoundDecl.getDecl();
5712     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5713     if (isa<UsingShadowDecl>(D))
5714       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5715 
5716     CXXConversionDecl *Conv;
5717     FunctionTemplateDecl *ConvTemplate;
5718     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5719       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5720     else
5721       Conv = cast<CXXConversionDecl>(D);
5722 
5723     if (ConvTemplate)
5724       SemaRef.AddTemplateConversionCandidate(
5725         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5726         /*AllowObjCConversionOnExplicit=*/false);
5727     else
5728       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5729                                      ToType, CandidateSet,
5730                                      /*AllowObjCConversionOnExplicit=*/false);
5731   }
5732 }
5733 
5734 /// Attempt to convert the given expression to a type which is accepted
5735 /// by the given converter.
5736 ///
5737 /// This routine will attempt to convert an expression of class type to a
5738 /// type accepted by the specified converter. In C++11 and before, the class
5739 /// must have a single non-explicit conversion function converting to a matching
5740 /// type. In C++1y, there can be multiple such conversion functions, but only
5741 /// one target type.
5742 ///
5743 /// \param Loc The source location of the construct that requires the
5744 /// conversion.
5745 ///
5746 /// \param From The expression we're converting from.
5747 ///
5748 /// \param Converter Used to control and diagnose the conversion process.
5749 ///
5750 /// \returns The expression, converted to an integral or enumeration type if
5751 /// successful.
5752 ExprResult Sema::PerformContextualImplicitConversion(
5753     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5754   // We can't perform any more checking for type-dependent expressions.
5755   if (From->isTypeDependent())
5756     return From;
5757 
5758   // Process placeholders immediately.
5759   if (From->hasPlaceholderType()) {
5760     ExprResult result = CheckPlaceholderExpr(From);
5761     if (result.isInvalid())
5762       return result;
5763     From = result.get();
5764   }
5765 
5766   // If the expression already has a matching type, we're golden.
5767   QualType T = From->getType();
5768   if (Converter.match(T))
5769     return DefaultLvalueConversion(From);
5770 
5771   // FIXME: Check for missing '()' if T is a function type?
5772 
5773   // We can only perform contextual implicit conversions on objects of class
5774   // type.
5775   const RecordType *RecordTy = T->getAs<RecordType>();
5776   if (!RecordTy || !getLangOpts().CPlusPlus) {
5777     if (!Converter.Suppress)
5778       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5779     return From;
5780   }
5781 
5782   // We must have a complete class type.
5783   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5784     ContextualImplicitConverter &Converter;
5785     Expr *From;
5786 
5787     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5788         : Converter(Converter), From(From) {}
5789 
5790     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5791       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5792     }
5793   } IncompleteDiagnoser(Converter, From);
5794 
5795   if (Converter.Suppress ? !isCompleteType(Loc, T)
5796                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5797     return From;
5798 
5799   // Look for a conversion to an integral or enumeration type.
5800   UnresolvedSet<4>
5801       ViableConversions; // These are *potentially* viable in C++1y.
5802   UnresolvedSet<4> ExplicitConversions;
5803   const auto &Conversions =
5804       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5805 
5806   bool HadMultipleCandidates =
5807       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5808 
5809   // To check that there is only one target type, in C++1y:
5810   QualType ToType;
5811   bool HasUniqueTargetType = true;
5812 
5813   // Collect explicit or viable (potentially in C++1y) conversions.
5814   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5815     NamedDecl *D = (*I)->getUnderlyingDecl();
5816     CXXConversionDecl *Conversion;
5817     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5818     if (ConvTemplate) {
5819       if (getLangOpts().CPlusPlus14)
5820         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5821       else
5822         continue; // C++11 does not consider conversion operator templates(?).
5823     } else
5824       Conversion = cast<CXXConversionDecl>(D);
5825 
5826     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5827            "Conversion operator templates are considered potentially "
5828            "viable in C++1y");
5829 
5830     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5831     if (Converter.match(CurToType) || ConvTemplate) {
5832 
5833       if (Conversion->isExplicit()) {
5834         // FIXME: For C++1y, do we need this restriction?
5835         // cf. diagnoseNoViableConversion()
5836         if (!ConvTemplate)
5837           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5838       } else {
5839         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5840           if (ToType.isNull())
5841             ToType = CurToType.getUnqualifiedType();
5842           else if (HasUniqueTargetType &&
5843                    (CurToType.getUnqualifiedType() != ToType))
5844             HasUniqueTargetType = false;
5845         }
5846         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5847       }
5848     }
5849   }
5850 
5851   if (getLangOpts().CPlusPlus14) {
5852     // C++1y [conv]p6:
5853     // ... An expression e of class type E appearing in such a context
5854     // is said to be contextually implicitly converted to a specified
5855     // type T and is well-formed if and only if e can be implicitly
5856     // converted to a type T that is determined as follows: E is searched
5857     // for conversion functions whose return type is cv T or reference to
5858     // cv T such that T is allowed by the context. There shall be
5859     // exactly one such T.
5860 
5861     // If no unique T is found:
5862     if (ToType.isNull()) {
5863       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5864                                      HadMultipleCandidates,
5865                                      ExplicitConversions))
5866         return ExprError();
5867       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5868     }
5869 
5870     // If more than one unique Ts are found:
5871     if (!HasUniqueTargetType)
5872       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5873                                          ViableConversions);
5874 
5875     // If one unique T is found:
5876     // First, build a candidate set from the previously recorded
5877     // potentially viable conversions.
5878     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5879     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5880                                       CandidateSet);
5881 
5882     // Then, perform overload resolution over the candidate set.
5883     OverloadCandidateSet::iterator Best;
5884     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5885     case OR_Success: {
5886       // Apply this conversion.
5887       DeclAccessPair Found =
5888           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5889       if (recordConversion(*this, Loc, From, Converter, T,
5890                            HadMultipleCandidates, Found))
5891         return ExprError();
5892       break;
5893     }
5894     case OR_Ambiguous:
5895       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5896                                          ViableConversions);
5897     case OR_No_Viable_Function:
5898       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5899                                      HadMultipleCandidates,
5900                                      ExplicitConversions))
5901         return ExprError();
5902       LLVM_FALLTHROUGH;
5903     case OR_Deleted:
5904       // We'll complain below about a non-integral condition type.
5905       break;
5906     }
5907   } else {
5908     switch (ViableConversions.size()) {
5909     case 0: {
5910       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5911                                      HadMultipleCandidates,
5912                                      ExplicitConversions))
5913         return ExprError();
5914 
5915       // We'll complain below about a non-integral condition type.
5916       break;
5917     }
5918     case 1: {
5919       // Apply this conversion.
5920       DeclAccessPair Found = ViableConversions[0];
5921       if (recordConversion(*this, Loc, From, Converter, T,
5922                            HadMultipleCandidates, Found))
5923         return ExprError();
5924       break;
5925     }
5926     default:
5927       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5928                                          ViableConversions);
5929     }
5930   }
5931 
5932   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5933 }
5934 
5935 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5936 /// an acceptable non-member overloaded operator for a call whose
5937 /// arguments have types T1 (and, if non-empty, T2). This routine
5938 /// implements the check in C++ [over.match.oper]p3b2 concerning
5939 /// enumeration types.
5940 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5941                                                    FunctionDecl *Fn,
5942                                                    ArrayRef<Expr *> Args) {
5943   QualType T1 = Args[0]->getType();
5944   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5945 
5946   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5947     return true;
5948 
5949   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5950     return true;
5951 
5952   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5953   if (Proto->getNumParams() < 1)
5954     return false;
5955 
5956   if (T1->isEnumeralType()) {
5957     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5958     if (Context.hasSameUnqualifiedType(T1, ArgType))
5959       return true;
5960   }
5961 
5962   if (Proto->getNumParams() < 2)
5963     return false;
5964 
5965   if (!T2.isNull() && T2->isEnumeralType()) {
5966     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5967     if (Context.hasSameUnqualifiedType(T2, ArgType))
5968       return true;
5969   }
5970 
5971   return false;
5972 }
5973 
5974 /// AddOverloadCandidate - Adds the given function to the set of
5975 /// candidate functions, using the given function call arguments.  If
5976 /// @p SuppressUserConversions, then don't allow user-defined
5977 /// conversions via constructors or conversion operators.
5978 ///
5979 /// \param PartialOverloading true if we are performing "partial" overloading
5980 /// based on an incomplete set of function arguments. This feature is used by
5981 /// code completion.
5982 void Sema::AddOverloadCandidate(FunctionDecl *Function,
5983                                 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5984                                 OverloadCandidateSet &CandidateSet,
5985                                 bool SuppressUserConversions,
5986                                 bool PartialOverloading, bool AllowExplicit,
5987                                 ADLCallKind IsADLCandidate,
5988                                 ConversionSequenceList EarlyConversions) {
5989   const FunctionProtoType *Proto
5990     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5991   assert(Proto && "Functions without a prototype cannot be overloaded");
5992   assert(!Function->getDescribedFunctionTemplate() &&
5993          "Use AddTemplateOverloadCandidate for function templates");
5994 
5995   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5996     if (!isa<CXXConstructorDecl>(Method)) {
5997       // If we get here, it's because we're calling a member function
5998       // that is named without a member access expression (e.g.,
5999       // "this->f") that was either written explicitly or created
6000       // implicitly. This can happen with a qualified call to a member
6001       // function, e.g., X::f(). We use an empty type for the implied
6002       // object argument (C++ [over.call.func]p3), and the acting context
6003       // is irrelevant.
6004       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6005                          Expr::Classification::makeSimpleLValue(), Args,
6006                          CandidateSet, SuppressUserConversions,
6007                          PartialOverloading, EarlyConversions);
6008       return;
6009     }
6010     // We treat a constructor like a non-member function, since its object
6011     // argument doesn't participate in overload resolution.
6012   }
6013 
6014   if (!CandidateSet.isNewCandidate(Function))
6015     return;
6016 
6017   // C++ [over.match.oper]p3:
6018   //   if no operand has a class type, only those non-member functions in the
6019   //   lookup set that have a first parameter of type T1 or "reference to
6020   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6021   //   is a right operand) a second parameter of type T2 or "reference to
6022   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6023   //   candidate functions.
6024   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6025       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6026     return;
6027 
6028   // C++11 [class.copy]p11: [DR1402]
6029   //   A defaulted move constructor that is defined as deleted is ignored by
6030   //   overload resolution.
6031   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6032   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6033       Constructor->isMoveConstructor())
6034     return;
6035 
6036   // Overload resolution is always an unevaluated context.
6037   EnterExpressionEvaluationContext Unevaluated(
6038       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6039 
6040   // Add this candidate
6041   OverloadCandidate &Candidate =
6042       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6043   Candidate.FoundDecl = FoundDecl;
6044   Candidate.Function = Function;
6045   Candidate.Viable = true;
6046   Candidate.IsSurrogate = false;
6047   Candidate.IsADLCandidate = IsADLCandidate;
6048   Candidate.IgnoreObjectArgument = false;
6049   Candidate.ExplicitCallArguments = Args.size();
6050 
6051   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6052       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6053     Candidate.Viable = false;
6054     Candidate.FailureKind = ovl_non_default_multiversion_function;
6055     return;
6056   }
6057 
6058   if (Constructor) {
6059     // C++ [class.copy]p3:
6060     //   A member function template is never instantiated to perform the copy
6061     //   of a class object to an object of its class type.
6062     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6063     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6064         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6065          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6066                        ClassType))) {
6067       Candidate.Viable = false;
6068       Candidate.FailureKind = ovl_fail_illegal_constructor;
6069       return;
6070     }
6071 
6072     // C++ [over.match.funcs]p8: (proposed DR resolution)
6073     //   A constructor inherited from class type C that has a first parameter
6074     //   of type "reference to P" (including such a constructor instantiated
6075     //   from a template) is excluded from the set of candidate functions when
6076     //   constructing an object of type cv D if the argument list has exactly
6077     //   one argument and D is reference-related to P and P is reference-related
6078     //   to C.
6079     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6080     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6081         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6082       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6083       QualType C = Context.getRecordType(Constructor->getParent());
6084       QualType D = Context.getRecordType(Shadow->getParent());
6085       SourceLocation Loc = Args.front()->getExprLoc();
6086       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6087           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6088         Candidate.Viable = false;
6089         Candidate.FailureKind = ovl_fail_inhctor_slice;
6090         return;
6091       }
6092     }
6093   }
6094 
6095   unsigned NumParams = Proto->getNumParams();
6096 
6097   // (C++ 13.3.2p2): A candidate function having fewer than m
6098   // parameters is viable only if it has an ellipsis in its parameter
6099   // list (8.3.5).
6100   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6101       !Proto->isVariadic()) {
6102     Candidate.Viable = false;
6103     Candidate.FailureKind = ovl_fail_too_many_arguments;
6104     return;
6105   }
6106 
6107   // (C++ 13.3.2p2): A candidate function having more than m parameters
6108   // is viable only if the (m+1)st parameter has a default argument
6109   // (8.3.6). For the purposes of overload resolution, the
6110   // parameter list is truncated on the right, so that there are
6111   // exactly m parameters.
6112   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6113   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6114     // Not enough arguments.
6115     Candidate.Viable = false;
6116     Candidate.FailureKind = ovl_fail_too_few_arguments;
6117     return;
6118   }
6119 
6120   // (CUDA B.1): Check for invalid calls between targets.
6121   if (getLangOpts().CUDA)
6122     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6123       // Skip the check for callers that are implicit members, because in this
6124       // case we may not yet know what the member's target is; the target is
6125       // inferred for the member automatically, based on the bases and fields of
6126       // the class.
6127       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6128         Candidate.Viable = false;
6129         Candidate.FailureKind = ovl_fail_bad_target;
6130         return;
6131       }
6132 
6133   // Determine the implicit conversion sequences for each of the
6134   // arguments.
6135   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6136     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6137       // We already formed a conversion sequence for this parameter during
6138       // template argument deduction.
6139     } else if (ArgIdx < NumParams) {
6140       // (C++ 13.3.2p3): for F to be a viable function, there shall
6141       // exist for each argument an implicit conversion sequence
6142       // (13.3.3.1) that converts that argument to the corresponding
6143       // parameter of F.
6144       QualType ParamType = Proto->getParamType(ArgIdx);
6145       Candidate.Conversions[ArgIdx]
6146         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6147                                 SuppressUserConversions,
6148                                 /*InOverloadResolution=*/true,
6149                                 /*AllowObjCWritebackConversion=*/
6150                                   getLangOpts().ObjCAutoRefCount,
6151                                 AllowExplicit);
6152       if (Candidate.Conversions[ArgIdx].isBad()) {
6153         Candidate.Viable = false;
6154         Candidate.FailureKind = ovl_fail_bad_conversion;
6155         return;
6156       }
6157     } else {
6158       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6159       // argument for which there is no corresponding parameter is
6160       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6161       Candidate.Conversions[ArgIdx].setEllipsis();
6162     }
6163   }
6164 
6165   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6166     Candidate.Viable = false;
6167     Candidate.FailureKind = ovl_fail_enable_if;
6168     Candidate.DeductionFailure.Data = FailedAttr;
6169     return;
6170   }
6171 
6172   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6173     Candidate.Viable = false;
6174     Candidate.FailureKind = ovl_fail_ext_disabled;
6175     return;
6176   }
6177 }
6178 
6179 ObjCMethodDecl *
6180 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6181                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6182   if (Methods.size() <= 1)
6183     return nullptr;
6184 
6185   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6186     bool Match = true;
6187     ObjCMethodDecl *Method = Methods[b];
6188     unsigned NumNamedArgs = Sel.getNumArgs();
6189     // Method might have more arguments than selector indicates. This is due
6190     // to addition of c-style arguments in method.
6191     if (Method->param_size() > NumNamedArgs)
6192       NumNamedArgs = Method->param_size();
6193     if (Args.size() < NumNamedArgs)
6194       continue;
6195 
6196     for (unsigned i = 0; i < NumNamedArgs; i++) {
6197       // We can't do any type-checking on a type-dependent argument.
6198       if (Args[i]->isTypeDependent()) {
6199         Match = false;
6200         break;
6201       }
6202 
6203       ParmVarDecl *param = Method->parameters()[i];
6204       Expr *argExpr = Args[i];
6205       assert(argExpr && "SelectBestMethod(): missing expression");
6206 
6207       // Strip the unbridged-cast placeholder expression off unless it's
6208       // a consumed argument.
6209       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6210           !param->hasAttr<CFConsumedAttr>())
6211         argExpr = stripARCUnbridgedCast(argExpr);
6212 
6213       // If the parameter is __unknown_anytype, move on to the next method.
6214       if (param->getType() == Context.UnknownAnyTy) {
6215         Match = false;
6216         break;
6217       }
6218 
6219       ImplicitConversionSequence ConversionState
6220         = TryCopyInitialization(*this, argExpr, param->getType(),
6221                                 /*SuppressUserConversions*/false,
6222                                 /*InOverloadResolution=*/true,
6223                                 /*AllowObjCWritebackConversion=*/
6224                                 getLangOpts().ObjCAutoRefCount,
6225                                 /*AllowExplicit*/false);
6226       // This function looks for a reasonably-exact match, so we consider
6227       // incompatible pointer conversions to be a failure here.
6228       if (ConversionState.isBad() ||
6229           (ConversionState.isStandard() &&
6230            ConversionState.Standard.Second ==
6231                ICK_Incompatible_Pointer_Conversion)) {
6232         Match = false;
6233         break;
6234       }
6235     }
6236     // Promote additional arguments to variadic methods.
6237     if (Match && Method->isVariadic()) {
6238       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6239         if (Args[i]->isTypeDependent()) {
6240           Match = false;
6241           break;
6242         }
6243         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6244                                                           nullptr);
6245         if (Arg.isInvalid()) {
6246           Match = false;
6247           break;
6248         }
6249       }
6250     } else {
6251       // Check for extra arguments to non-variadic methods.
6252       if (Args.size() != NumNamedArgs)
6253         Match = false;
6254       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6255         // Special case when selectors have no argument. In this case, select
6256         // one with the most general result type of 'id'.
6257         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6258           QualType ReturnT = Methods[b]->getReturnType();
6259           if (ReturnT->isObjCIdType())
6260             return Methods[b];
6261         }
6262       }
6263     }
6264 
6265     if (Match)
6266       return Method;
6267   }
6268   return nullptr;
6269 }
6270 
6271 static bool
6272 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6273                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6274                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6275                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6276   if (ThisArg) {
6277     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6278     assert(!isa<CXXConstructorDecl>(Method) &&
6279            "Shouldn't have `this` for ctors!");
6280     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6281     ExprResult R = S.PerformObjectArgumentInitialization(
6282         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6283     if (R.isInvalid())
6284       return false;
6285     ConvertedThis = R.get();
6286   } else {
6287     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6288       (void)MD;
6289       assert((MissingImplicitThis || MD->isStatic() ||
6290               isa<CXXConstructorDecl>(MD)) &&
6291              "Expected `this` for non-ctor instance methods");
6292     }
6293     ConvertedThis = nullptr;
6294   }
6295 
6296   // Ignore any variadic arguments. Converting them is pointless, since the
6297   // user can't refer to them in the function condition.
6298   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6299 
6300   // Convert the arguments.
6301   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6302     ExprResult R;
6303     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6304                                         S.Context, Function->getParamDecl(I)),
6305                                     SourceLocation(), Args[I]);
6306 
6307     if (R.isInvalid())
6308       return false;
6309 
6310     ConvertedArgs.push_back(R.get());
6311   }
6312 
6313   if (Trap.hasErrorOccurred())
6314     return false;
6315 
6316   // Push default arguments if needed.
6317   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6318     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6319       ParmVarDecl *P = Function->getParamDecl(i);
6320       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6321                          ? P->getUninstantiatedDefaultArg()
6322                          : P->getDefaultArg();
6323       // This can only happen in code completion, i.e. when PartialOverloading
6324       // is true.
6325       if (!DefArg)
6326         return false;
6327       ExprResult R =
6328           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6329                                           S.Context, Function->getParamDecl(i)),
6330                                       SourceLocation(), DefArg);
6331       if (R.isInvalid())
6332         return false;
6333       ConvertedArgs.push_back(R.get());
6334     }
6335 
6336     if (Trap.hasErrorOccurred())
6337       return false;
6338   }
6339   return true;
6340 }
6341 
6342 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6343                                   bool MissingImplicitThis) {
6344   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6345   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6346     return nullptr;
6347 
6348   SFINAETrap Trap(*this);
6349   SmallVector<Expr *, 16> ConvertedArgs;
6350   // FIXME: We should look into making enable_if late-parsed.
6351   Expr *DiscardedThis;
6352   if (!convertArgsForAvailabilityChecks(
6353           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6354           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6355     return *EnableIfAttrs.begin();
6356 
6357   for (auto *EIA : EnableIfAttrs) {
6358     APValue Result;
6359     // FIXME: This doesn't consider value-dependent cases, because doing so is
6360     // very difficult. Ideally, we should handle them more gracefully.
6361     if (!EIA->getCond()->EvaluateWithSubstitution(
6362             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6363       return EIA;
6364 
6365     if (!Result.isInt() || !Result.getInt().getBoolValue())
6366       return EIA;
6367   }
6368   return nullptr;
6369 }
6370 
6371 template <typename CheckFn>
6372 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6373                                         bool ArgDependent, SourceLocation Loc,
6374                                         CheckFn &&IsSuccessful) {
6375   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6376   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6377     if (ArgDependent == DIA->getArgDependent())
6378       Attrs.push_back(DIA);
6379   }
6380 
6381   // Common case: No diagnose_if attributes, so we can quit early.
6382   if (Attrs.empty())
6383     return false;
6384 
6385   auto WarningBegin = std::stable_partition(
6386       Attrs.begin(), Attrs.end(),
6387       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6388 
6389   // Note that diagnose_if attributes are late-parsed, so they appear in the
6390   // correct order (unlike enable_if attributes).
6391   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6392                                IsSuccessful);
6393   if (ErrAttr != WarningBegin) {
6394     const DiagnoseIfAttr *DIA = *ErrAttr;
6395     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6396     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6397         << DIA->getParent() << DIA->getCond()->getSourceRange();
6398     return true;
6399   }
6400 
6401   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6402     if (IsSuccessful(DIA)) {
6403       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6404       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6405           << DIA->getParent() << DIA->getCond()->getSourceRange();
6406     }
6407 
6408   return false;
6409 }
6410 
6411 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6412                                                const Expr *ThisArg,
6413                                                ArrayRef<const Expr *> Args,
6414                                                SourceLocation Loc) {
6415   return diagnoseDiagnoseIfAttrsWith(
6416       *this, Function, /*ArgDependent=*/true, Loc,
6417       [&](const DiagnoseIfAttr *DIA) {
6418         APValue Result;
6419         // It's sane to use the same Args for any redecl of this function, since
6420         // EvaluateWithSubstitution only cares about the position of each
6421         // argument in the arg list, not the ParmVarDecl* it maps to.
6422         if (!DIA->getCond()->EvaluateWithSubstitution(
6423                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6424           return false;
6425         return Result.isInt() && Result.getInt().getBoolValue();
6426       });
6427 }
6428 
6429 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6430                                                  SourceLocation Loc) {
6431   return diagnoseDiagnoseIfAttrsWith(
6432       *this, ND, /*ArgDependent=*/false, Loc,
6433       [&](const DiagnoseIfAttr *DIA) {
6434         bool Result;
6435         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6436                Result;
6437       });
6438 }
6439 
6440 /// Add all of the function declarations in the given function set to
6441 /// the overload candidate set.
6442 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6443                                  ArrayRef<Expr *> Args,
6444                                  OverloadCandidateSet &CandidateSet,
6445                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6446                                  bool SuppressUserConversions,
6447                                  bool PartialOverloading,
6448                                  bool FirstArgumentIsBase) {
6449   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6450     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6451     ArrayRef<Expr *> FunctionArgs = Args;
6452 
6453     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6454     FunctionDecl *FD =
6455         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6456 
6457     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6458       QualType ObjectType;
6459       Expr::Classification ObjectClassification;
6460       if (Args.size() > 0) {
6461         if (Expr *E = Args[0]) {
6462           // Use the explicit base to restrict the lookup:
6463           ObjectType = E->getType();
6464           // Pointers in the object arguments are implicitly dereferenced, so we
6465           // always classify them as l-values.
6466           if (!ObjectType.isNull() && ObjectType->isPointerType())
6467             ObjectClassification = Expr::Classification::makeSimpleLValue();
6468           else
6469             ObjectClassification = E->Classify(Context);
6470         } // .. else there is an implicit base.
6471         FunctionArgs = Args.slice(1);
6472       }
6473       if (FunTmpl) {
6474         AddMethodTemplateCandidate(
6475             FunTmpl, F.getPair(),
6476             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6477             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6478             FunctionArgs, CandidateSet, SuppressUserConversions,
6479             PartialOverloading);
6480       } else {
6481         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6482                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6483                            ObjectClassification, FunctionArgs, CandidateSet,
6484                            SuppressUserConversions, PartialOverloading);
6485       }
6486     } else {
6487       // This branch handles both standalone functions and static methods.
6488 
6489       // Slice the first argument (which is the base) when we access
6490       // static method as non-static.
6491       if (Args.size() > 0 &&
6492           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6493                         !isa<CXXConstructorDecl>(FD)))) {
6494         assert(cast<CXXMethodDecl>(FD)->isStatic());
6495         FunctionArgs = Args.slice(1);
6496       }
6497       if (FunTmpl) {
6498         AddTemplateOverloadCandidate(
6499             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6500             CandidateSet, SuppressUserConversions, PartialOverloading);
6501       } else {
6502         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6503                              SuppressUserConversions, PartialOverloading);
6504       }
6505     }
6506   }
6507 }
6508 
6509 /// AddMethodCandidate - Adds a named decl (which is some kind of
6510 /// method) as a method candidate to the given overload set.
6511 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6512                               QualType ObjectType,
6513                               Expr::Classification ObjectClassification,
6514                               ArrayRef<Expr *> Args,
6515                               OverloadCandidateSet& CandidateSet,
6516                               bool SuppressUserConversions) {
6517   NamedDecl *Decl = FoundDecl.getDecl();
6518   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6519 
6520   if (isa<UsingShadowDecl>(Decl))
6521     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6522 
6523   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6524     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6525            "Expected a member function template");
6526     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6527                                /*ExplicitArgs*/ nullptr, ObjectType,
6528                                ObjectClassification, Args, CandidateSet,
6529                                SuppressUserConversions);
6530   } else {
6531     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6532                        ObjectType, ObjectClassification, Args, CandidateSet,
6533                        SuppressUserConversions);
6534   }
6535 }
6536 
6537 /// AddMethodCandidate - Adds the given C++ member function to the set
6538 /// of candidate functions, using the given function call arguments
6539 /// and the object argument (@c Object). For example, in a call
6540 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6541 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6542 /// allow user-defined conversions via constructors or conversion
6543 /// operators.
6544 void
6545 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6546                          CXXRecordDecl *ActingContext, QualType ObjectType,
6547                          Expr::Classification ObjectClassification,
6548                          ArrayRef<Expr *> Args,
6549                          OverloadCandidateSet &CandidateSet,
6550                          bool SuppressUserConversions,
6551                          bool PartialOverloading,
6552                          ConversionSequenceList EarlyConversions) {
6553   const FunctionProtoType *Proto
6554     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6555   assert(Proto && "Methods without a prototype cannot be overloaded");
6556   assert(!isa<CXXConstructorDecl>(Method) &&
6557          "Use AddOverloadCandidate for constructors");
6558 
6559   if (!CandidateSet.isNewCandidate(Method))
6560     return;
6561 
6562   // C++11 [class.copy]p23: [DR1402]
6563   //   A defaulted move assignment operator that is defined as deleted is
6564   //   ignored by overload resolution.
6565   if (Method->isDefaulted() && Method->isDeleted() &&
6566       Method->isMoveAssignmentOperator())
6567     return;
6568 
6569   // Overload resolution is always an unevaluated context.
6570   EnterExpressionEvaluationContext Unevaluated(
6571       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6572 
6573   // Add this candidate
6574   OverloadCandidate &Candidate =
6575       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6576   Candidate.FoundDecl = FoundDecl;
6577   Candidate.Function = Method;
6578   Candidate.IsSurrogate = false;
6579   Candidate.IgnoreObjectArgument = false;
6580   Candidate.ExplicitCallArguments = Args.size();
6581 
6582   unsigned NumParams = Proto->getNumParams();
6583 
6584   // (C++ 13.3.2p2): A candidate function having fewer than m
6585   // parameters is viable only if it has an ellipsis in its parameter
6586   // list (8.3.5).
6587   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6588       !Proto->isVariadic()) {
6589     Candidate.Viable = false;
6590     Candidate.FailureKind = ovl_fail_too_many_arguments;
6591     return;
6592   }
6593 
6594   // (C++ 13.3.2p2): A candidate function having more than m parameters
6595   // is viable only if the (m+1)st parameter has a default argument
6596   // (8.3.6). For the purposes of overload resolution, the
6597   // parameter list is truncated on the right, so that there are
6598   // exactly m parameters.
6599   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6600   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6601     // Not enough arguments.
6602     Candidate.Viable = false;
6603     Candidate.FailureKind = ovl_fail_too_few_arguments;
6604     return;
6605   }
6606 
6607   Candidate.Viable = true;
6608 
6609   if (Method->isStatic() || ObjectType.isNull())
6610     // The implicit object argument is ignored.
6611     Candidate.IgnoreObjectArgument = true;
6612   else {
6613     // Determine the implicit conversion sequence for the object
6614     // parameter.
6615     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6616         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6617         Method, ActingContext);
6618     if (Candidate.Conversions[0].isBad()) {
6619       Candidate.Viable = false;
6620       Candidate.FailureKind = ovl_fail_bad_conversion;
6621       return;
6622     }
6623   }
6624 
6625   // (CUDA B.1): Check for invalid calls between targets.
6626   if (getLangOpts().CUDA)
6627     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6628       if (!IsAllowedCUDACall(Caller, Method)) {
6629         Candidate.Viable = false;
6630         Candidate.FailureKind = ovl_fail_bad_target;
6631         return;
6632       }
6633 
6634   // Determine the implicit conversion sequences for each of the
6635   // arguments.
6636   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6637     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6638       // We already formed a conversion sequence for this parameter during
6639       // template argument deduction.
6640     } else if (ArgIdx < NumParams) {
6641       // (C++ 13.3.2p3): for F to be a viable function, there shall
6642       // exist for each argument an implicit conversion sequence
6643       // (13.3.3.1) that converts that argument to the corresponding
6644       // parameter of F.
6645       QualType ParamType = Proto->getParamType(ArgIdx);
6646       Candidate.Conversions[ArgIdx + 1]
6647         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6648                                 SuppressUserConversions,
6649                                 /*InOverloadResolution=*/true,
6650                                 /*AllowObjCWritebackConversion=*/
6651                                   getLangOpts().ObjCAutoRefCount);
6652       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6653         Candidate.Viable = false;
6654         Candidate.FailureKind = ovl_fail_bad_conversion;
6655         return;
6656       }
6657     } else {
6658       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6659       // argument for which there is no corresponding parameter is
6660       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6661       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6662     }
6663   }
6664 
6665   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6666     Candidate.Viable = false;
6667     Candidate.FailureKind = ovl_fail_enable_if;
6668     Candidate.DeductionFailure.Data = FailedAttr;
6669     return;
6670   }
6671 
6672   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6673       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6674     Candidate.Viable = false;
6675     Candidate.FailureKind = ovl_non_default_multiversion_function;
6676   }
6677 }
6678 
6679 /// Add a C++ member function template as a candidate to the candidate
6680 /// set, using template argument deduction to produce an appropriate member
6681 /// function template specialization.
6682 void
6683 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6684                                  DeclAccessPair FoundDecl,
6685                                  CXXRecordDecl *ActingContext,
6686                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6687                                  QualType ObjectType,
6688                                  Expr::Classification ObjectClassification,
6689                                  ArrayRef<Expr *> Args,
6690                                  OverloadCandidateSet& CandidateSet,
6691                                  bool SuppressUserConversions,
6692                                  bool PartialOverloading) {
6693   if (!CandidateSet.isNewCandidate(MethodTmpl))
6694     return;
6695 
6696   // C++ [over.match.funcs]p7:
6697   //   In each case where a candidate is a function template, candidate
6698   //   function template specializations are generated using template argument
6699   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6700   //   candidate functions in the usual way.113) A given name can refer to one
6701   //   or more function templates and also to a set of overloaded non-template
6702   //   functions. In such a case, the candidate functions generated from each
6703   //   function template are combined with the set of non-template candidate
6704   //   functions.
6705   TemplateDeductionInfo Info(CandidateSet.getLocation());
6706   FunctionDecl *Specialization = nullptr;
6707   ConversionSequenceList Conversions;
6708   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6709           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6710           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6711             return CheckNonDependentConversions(
6712                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6713                 SuppressUserConversions, ActingContext, ObjectType,
6714                 ObjectClassification);
6715           })) {
6716     OverloadCandidate &Candidate =
6717         CandidateSet.addCandidate(Conversions.size(), Conversions);
6718     Candidate.FoundDecl = FoundDecl;
6719     Candidate.Function = MethodTmpl->getTemplatedDecl();
6720     Candidate.Viable = false;
6721     Candidate.IsSurrogate = false;
6722     Candidate.IgnoreObjectArgument =
6723         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6724         ObjectType.isNull();
6725     Candidate.ExplicitCallArguments = Args.size();
6726     if (Result == TDK_NonDependentConversionFailure)
6727       Candidate.FailureKind = ovl_fail_bad_conversion;
6728     else {
6729       Candidate.FailureKind = ovl_fail_bad_deduction;
6730       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6731                                                             Info);
6732     }
6733     return;
6734   }
6735 
6736   // Add the function template specialization produced by template argument
6737   // deduction as a candidate.
6738   assert(Specialization && "Missing member function template specialization?");
6739   assert(isa<CXXMethodDecl>(Specialization) &&
6740          "Specialization is not a member function?");
6741   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6742                      ActingContext, ObjectType, ObjectClassification, Args,
6743                      CandidateSet, SuppressUserConversions, PartialOverloading,
6744                      Conversions);
6745 }
6746 
6747 /// Add a C++ function template specialization as a candidate
6748 /// in the candidate set, using template argument deduction to produce
6749 /// an appropriate function template specialization.
6750 void Sema::AddTemplateOverloadCandidate(
6751     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6752     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6753     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6754     bool PartialOverloading, ADLCallKind IsADLCandidate) {
6755   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6756     return;
6757 
6758   // C++ [over.match.funcs]p7:
6759   //   In each case where a candidate is a function template, candidate
6760   //   function template specializations are generated using template argument
6761   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6762   //   candidate functions in the usual way.113) A given name can refer to one
6763   //   or more function templates and also to a set of overloaded non-template
6764   //   functions. In such a case, the candidate functions generated from each
6765   //   function template are combined with the set of non-template candidate
6766   //   functions.
6767   TemplateDeductionInfo Info(CandidateSet.getLocation());
6768   FunctionDecl *Specialization = nullptr;
6769   ConversionSequenceList Conversions;
6770   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6771           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6772           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6773             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6774                                                 Args, CandidateSet, Conversions,
6775                                                 SuppressUserConversions);
6776           })) {
6777     OverloadCandidate &Candidate =
6778         CandidateSet.addCandidate(Conversions.size(), Conversions);
6779     Candidate.FoundDecl = FoundDecl;
6780     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6781     Candidate.Viable = false;
6782     Candidate.IsSurrogate = false;
6783     Candidate.IsADLCandidate = IsADLCandidate;
6784     // Ignore the object argument if there is one, since we don't have an object
6785     // type.
6786     Candidate.IgnoreObjectArgument =
6787         isa<CXXMethodDecl>(Candidate.Function) &&
6788         !isa<CXXConstructorDecl>(Candidate.Function);
6789     Candidate.ExplicitCallArguments = Args.size();
6790     if (Result == TDK_NonDependentConversionFailure)
6791       Candidate.FailureKind = ovl_fail_bad_conversion;
6792     else {
6793       Candidate.FailureKind = ovl_fail_bad_deduction;
6794       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6795                                                             Info);
6796     }
6797     return;
6798   }
6799 
6800   // Add the function template specialization produced by template argument
6801   // deduction as a candidate.
6802   assert(Specialization && "Missing function template specialization?");
6803   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6804                        SuppressUserConversions, PartialOverloading,
6805                        /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6806 }
6807 
6808 /// Check that implicit conversion sequences can be formed for each argument
6809 /// whose corresponding parameter has a non-dependent type, per DR1391's
6810 /// [temp.deduct.call]p10.
6811 bool Sema::CheckNonDependentConversions(
6812     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6813     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6814     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6815     CXXRecordDecl *ActingContext, QualType ObjectType,
6816     Expr::Classification ObjectClassification) {
6817   // FIXME: The cases in which we allow explicit conversions for constructor
6818   // arguments never consider calling a constructor template. It's not clear
6819   // that is correct.
6820   const bool AllowExplicit = false;
6821 
6822   auto *FD = FunctionTemplate->getTemplatedDecl();
6823   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6824   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6825   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6826 
6827   Conversions =
6828       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6829 
6830   // Overload resolution is always an unevaluated context.
6831   EnterExpressionEvaluationContext Unevaluated(
6832       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6833 
6834   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6835   // require that, but this check should never result in a hard error, and
6836   // overload resolution is permitted to sidestep instantiations.
6837   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6838       !ObjectType.isNull()) {
6839     Conversions[0] = TryObjectArgumentInitialization(
6840         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6841         Method, ActingContext);
6842     if (Conversions[0].isBad())
6843       return true;
6844   }
6845 
6846   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6847        ++I) {
6848     QualType ParamType = ParamTypes[I];
6849     if (!ParamType->isDependentType()) {
6850       Conversions[ThisConversions + I]
6851         = TryCopyInitialization(*this, Args[I], ParamType,
6852                                 SuppressUserConversions,
6853                                 /*InOverloadResolution=*/true,
6854                                 /*AllowObjCWritebackConversion=*/
6855                                   getLangOpts().ObjCAutoRefCount,
6856                                 AllowExplicit);
6857       if (Conversions[ThisConversions + I].isBad())
6858         return true;
6859     }
6860   }
6861 
6862   return false;
6863 }
6864 
6865 /// Determine whether this is an allowable conversion from the result
6866 /// of an explicit conversion operator to the expected type, per C++
6867 /// [over.match.conv]p1 and [over.match.ref]p1.
6868 ///
6869 /// \param ConvType The return type of the conversion function.
6870 ///
6871 /// \param ToType The type we are converting to.
6872 ///
6873 /// \param AllowObjCPointerConversion Allow a conversion from one
6874 /// Objective-C pointer to another.
6875 ///
6876 /// \returns true if the conversion is allowable, false otherwise.
6877 static bool isAllowableExplicitConversion(Sema &S,
6878                                           QualType ConvType, QualType ToType,
6879                                           bool AllowObjCPointerConversion) {
6880   QualType ToNonRefType = ToType.getNonReferenceType();
6881 
6882   // Easy case: the types are the same.
6883   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6884     return true;
6885 
6886   // Allow qualification conversions.
6887   bool ObjCLifetimeConversion;
6888   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6889                                   ObjCLifetimeConversion))
6890     return true;
6891 
6892   // If we're not allowed to consider Objective-C pointer conversions,
6893   // we're done.
6894   if (!AllowObjCPointerConversion)
6895     return false;
6896 
6897   // Is this an Objective-C pointer conversion?
6898   bool IncompatibleObjC = false;
6899   QualType ConvertedType;
6900   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6901                                    IncompatibleObjC);
6902 }
6903 
6904 /// AddConversionCandidate - Add a C++ conversion function as a
6905 /// candidate in the candidate set (C++ [over.match.conv],
6906 /// C++ [over.match.copy]). From is the expression we're converting from,
6907 /// and ToType is the type that we're eventually trying to convert to
6908 /// (which may or may not be the same type as the type that the
6909 /// conversion function produces).
6910 void
6911 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6912                              DeclAccessPair FoundDecl,
6913                              CXXRecordDecl *ActingContext,
6914                              Expr *From, QualType ToType,
6915                              OverloadCandidateSet& CandidateSet,
6916                              bool AllowObjCConversionOnExplicit,
6917                              bool AllowResultConversion) {
6918   assert(!Conversion->getDescribedFunctionTemplate() &&
6919          "Conversion function templates use AddTemplateConversionCandidate");
6920   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6921   if (!CandidateSet.isNewCandidate(Conversion))
6922     return;
6923 
6924   // If the conversion function has an undeduced return type, trigger its
6925   // deduction now.
6926   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6927     if (DeduceReturnType(Conversion, From->getExprLoc()))
6928       return;
6929     ConvType = Conversion->getConversionType().getNonReferenceType();
6930   }
6931 
6932   // If we don't allow any conversion of the result type, ignore conversion
6933   // functions that don't convert to exactly (possibly cv-qualified) T.
6934   if (!AllowResultConversion &&
6935       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6936     return;
6937 
6938   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6939   // operator is only a candidate if its return type is the target type or
6940   // can be converted to the target type with a qualification conversion.
6941   if (Conversion->isExplicit() &&
6942       !isAllowableExplicitConversion(*this, ConvType, ToType,
6943                                      AllowObjCConversionOnExplicit))
6944     return;
6945 
6946   // Overload resolution is always an unevaluated context.
6947   EnterExpressionEvaluationContext Unevaluated(
6948       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6949 
6950   // Add this candidate
6951   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6952   Candidate.FoundDecl = FoundDecl;
6953   Candidate.Function = Conversion;
6954   Candidate.IsSurrogate = false;
6955   Candidate.IgnoreObjectArgument = false;
6956   Candidate.FinalConversion.setAsIdentityConversion();
6957   Candidate.FinalConversion.setFromType(ConvType);
6958   Candidate.FinalConversion.setAllToTypes(ToType);
6959   Candidate.Viable = true;
6960   Candidate.ExplicitCallArguments = 1;
6961 
6962   // C++ [over.match.funcs]p4:
6963   //   For conversion functions, the function is considered to be a member of
6964   //   the class of the implicit implied object argument for the purpose of
6965   //   defining the type of the implicit object parameter.
6966   //
6967   // Determine the implicit conversion sequence for the implicit
6968   // object parameter.
6969   QualType ImplicitParamType = From->getType();
6970   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6971     ImplicitParamType = FromPtrType->getPointeeType();
6972   CXXRecordDecl *ConversionContext
6973     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6974 
6975   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6976       *this, CandidateSet.getLocation(), From->getType(),
6977       From->Classify(Context), Conversion, ConversionContext);
6978 
6979   if (Candidate.Conversions[0].isBad()) {
6980     Candidate.Viable = false;
6981     Candidate.FailureKind = ovl_fail_bad_conversion;
6982     return;
6983   }
6984 
6985   // We won't go through a user-defined type conversion function to convert a
6986   // derived to base as such conversions are given Conversion Rank. They only
6987   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6988   QualType FromCanon
6989     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6990   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6991   if (FromCanon == ToCanon ||
6992       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6993     Candidate.Viable = false;
6994     Candidate.FailureKind = ovl_fail_trivial_conversion;
6995     return;
6996   }
6997 
6998   // To determine what the conversion from the result of calling the
6999   // conversion function to the type we're eventually trying to
7000   // convert to (ToType), we need to synthesize a call to the
7001   // conversion function and attempt copy initialization from it. This
7002   // makes sure that we get the right semantics with respect to
7003   // lvalues/rvalues and the type. Fortunately, we can allocate this
7004   // call on the stack and we don't need its arguments to be
7005   // well-formed.
7006   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7007                             VK_LValue, From->getBeginLoc());
7008   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7009                                 Context.getPointerType(Conversion->getType()),
7010                                 CK_FunctionToPointerDecay,
7011                                 &ConversionRef, VK_RValue);
7012 
7013   QualType ConversionType = Conversion->getConversionType();
7014   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7015     Candidate.Viable = false;
7016     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7017     return;
7018   }
7019 
7020   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7021 
7022   // Note that it is safe to allocate CallExpr on the stack here because
7023   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7024   // allocator).
7025   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7026 
7027   llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7028       Buffer;
7029   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7030       Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7031 
7032   ImplicitConversionSequence ICS =
7033       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7034                             /*SuppressUserConversions=*/true,
7035                             /*InOverloadResolution=*/false,
7036                             /*AllowObjCWritebackConversion=*/false);
7037 
7038   switch (ICS.getKind()) {
7039   case ImplicitConversionSequence::StandardConversion:
7040     Candidate.FinalConversion = ICS.Standard;
7041 
7042     // C++ [over.ics.user]p3:
7043     //   If the user-defined conversion is specified by a specialization of a
7044     //   conversion function template, the second standard conversion sequence
7045     //   shall have exact match rank.
7046     if (Conversion->getPrimaryTemplate() &&
7047         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7048       Candidate.Viable = false;
7049       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7050       return;
7051     }
7052 
7053     // C++0x [dcl.init.ref]p5:
7054     //    In the second case, if the reference is an rvalue reference and
7055     //    the second standard conversion sequence of the user-defined
7056     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7057     //    program is ill-formed.
7058     if (ToType->isRValueReferenceType() &&
7059         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7060       Candidate.Viable = false;
7061       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7062       return;
7063     }
7064     break;
7065 
7066   case ImplicitConversionSequence::BadConversion:
7067     Candidate.Viable = false;
7068     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7069     return;
7070 
7071   default:
7072     llvm_unreachable(
7073            "Can only end up with a standard conversion sequence or failure");
7074   }
7075 
7076   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7077     Candidate.Viable = false;
7078     Candidate.FailureKind = ovl_fail_enable_if;
7079     Candidate.DeductionFailure.Data = FailedAttr;
7080     return;
7081   }
7082 
7083   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7084       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7085     Candidate.Viable = false;
7086     Candidate.FailureKind = ovl_non_default_multiversion_function;
7087   }
7088 }
7089 
7090 /// Adds a conversion function template specialization
7091 /// candidate to the overload set, using template argument deduction
7092 /// to deduce the template arguments of the conversion function
7093 /// template from the type that we are converting to (C++
7094 /// [temp.deduct.conv]).
7095 void
7096 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7097                                      DeclAccessPair FoundDecl,
7098                                      CXXRecordDecl *ActingDC,
7099                                      Expr *From, QualType ToType,
7100                                      OverloadCandidateSet &CandidateSet,
7101                                      bool AllowObjCConversionOnExplicit,
7102                                      bool AllowResultConversion) {
7103   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7104          "Only conversion function templates permitted here");
7105 
7106   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7107     return;
7108 
7109   TemplateDeductionInfo Info(CandidateSet.getLocation());
7110   CXXConversionDecl *Specialization = nullptr;
7111   if (TemplateDeductionResult Result
7112         = DeduceTemplateArguments(FunctionTemplate, ToType,
7113                                   Specialization, Info)) {
7114     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7115     Candidate.FoundDecl = FoundDecl;
7116     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7117     Candidate.Viable = false;
7118     Candidate.FailureKind = ovl_fail_bad_deduction;
7119     Candidate.IsSurrogate = false;
7120     Candidate.IgnoreObjectArgument = false;
7121     Candidate.ExplicitCallArguments = 1;
7122     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7123                                                           Info);
7124     return;
7125   }
7126 
7127   // Add the conversion function template specialization produced by
7128   // template argument deduction as a candidate.
7129   assert(Specialization && "Missing function template specialization?");
7130   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7131                          CandidateSet, AllowObjCConversionOnExplicit,
7132                          AllowResultConversion);
7133 }
7134 
7135 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7136 /// converts the given @c Object to a function pointer via the
7137 /// conversion function @c Conversion, and then attempts to call it
7138 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7139 /// the type of function that we'll eventually be calling.
7140 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7141                                  DeclAccessPair FoundDecl,
7142                                  CXXRecordDecl *ActingContext,
7143                                  const FunctionProtoType *Proto,
7144                                  Expr *Object,
7145                                  ArrayRef<Expr *> Args,
7146                                  OverloadCandidateSet& CandidateSet) {
7147   if (!CandidateSet.isNewCandidate(Conversion))
7148     return;
7149 
7150   // Overload resolution is always an unevaluated context.
7151   EnterExpressionEvaluationContext Unevaluated(
7152       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7153 
7154   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7155   Candidate.FoundDecl = FoundDecl;
7156   Candidate.Function = nullptr;
7157   Candidate.Surrogate = Conversion;
7158   Candidate.Viable = true;
7159   Candidate.IsSurrogate = true;
7160   Candidate.IgnoreObjectArgument = false;
7161   Candidate.ExplicitCallArguments = Args.size();
7162 
7163   // Determine the implicit conversion sequence for the implicit
7164   // object parameter.
7165   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7166       *this, CandidateSet.getLocation(), Object->getType(),
7167       Object->Classify(Context), Conversion, ActingContext);
7168   if (ObjectInit.isBad()) {
7169     Candidate.Viable = false;
7170     Candidate.FailureKind = ovl_fail_bad_conversion;
7171     Candidate.Conversions[0] = ObjectInit;
7172     return;
7173   }
7174 
7175   // The first conversion is actually a user-defined conversion whose
7176   // first conversion is ObjectInit's standard conversion (which is
7177   // effectively a reference binding). Record it as such.
7178   Candidate.Conversions[0].setUserDefined();
7179   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7180   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7181   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7182   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7183   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7184   Candidate.Conversions[0].UserDefined.After
7185     = Candidate.Conversions[0].UserDefined.Before;
7186   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7187 
7188   // Find the
7189   unsigned NumParams = Proto->getNumParams();
7190 
7191   // (C++ 13.3.2p2): A candidate function having fewer than m
7192   // parameters is viable only if it has an ellipsis in its parameter
7193   // list (8.3.5).
7194   if (Args.size() > NumParams && !Proto->isVariadic()) {
7195     Candidate.Viable = false;
7196     Candidate.FailureKind = ovl_fail_too_many_arguments;
7197     return;
7198   }
7199 
7200   // Function types don't have any default arguments, so just check if
7201   // we have enough arguments.
7202   if (Args.size() < NumParams) {
7203     // Not enough arguments.
7204     Candidate.Viable = false;
7205     Candidate.FailureKind = ovl_fail_too_few_arguments;
7206     return;
7207   }
7208 
7209   // Determine the implicit conversion sequences for each of the
7210   // arguments.
7211   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7212     if (ArgIdx < NumParams) {
7213       // (C++ 13.3.2p3): for F to be a viable function, there shall
7214       // exist for each argument an implicit conversion sequence
7215       // (13.3.3.1) that converts that argument to the corresponding
7216       // parameter of F.
7217       QualType ParamType = Proto->getParamType(ArgIdx);
7218       Candidate.Conversions[ArgIdx + 1]
7219         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7220                                 /*SuppressUserConversions=*/false,
7221                                 /*InOverloadResolution=*/false,
7222                                 /*AllowObjCWritebackConversion=*/
7223                                   getLangOpts().ObjCAutoRefCount);
7224       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7225         Candidate.Viable = false;
7226         Candidate.FailureKind = ovl_fail_bad_conversion;
7227         return;
7228       }
7229     } else {
7230       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7231       // argument for which there is no corresponding parameter is
7232       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7233       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7234     }
7235   }
7236 
7237   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7238     Candidate.Viable = false;
7239     Candidate.FailureKind = ovl_fail_enable_if;
7240     Candidate.DeductionFailure.Data = FailedAttr;
7241     return;
7242   }
7243 }
7244 
7245 /// Add overload candidates for overloaded operators that are
7246 /// member functions.
7247 ///
7248 /// Add the overloaded operator candidates that are member functions
7249 /// for the operator Op that was used in an operator expression such
7250 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7251 /// CandidateSet will store the added overload candidates. (C++
7252 /// [over.match.oper]).
7253 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7254                                        SourceLocation OpLoc,
7255                                        ArrayRef<Expr *> Args,
7256                                        OverloadCandidateSet& CandidateSet,
7257                                        SourceRange OpRange) {
7258   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7259 
7260   // C++ [over.match.oper]p3:
7261   //   For a unary operator @ with an operand of a type whose
7262   //   cv-unqualified version is T1, and for a binary operator @ with
7263   //   a left operand of a type whose cv-unqualified version is T1 and
7264   //   a right operand of a type whose cv-unqualified version is T2,
7265   //   three sets of candidate functions, designated member
7266   //   candidates, non-member candidates and built-in candidates, are
7267   //   constructed as follows:
7268   QualType T1 = Args[0]->getType();
7269 
7270   //     -- If T1 is a complete class type or a class currently being
7271   //        defined, the set of member candidates is the result of the
7272   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7273   //        the set of member candidates is empty.
7274   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7275     // Complete the type if it can be completed.
7276     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7277       return;
7278     // If the type is neither complete nor being defined, bail out now.
7279     if (!T1Rec->getDecl()->getDefinition())
7280       return;
7281 
7282     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7283     LookupQualifiedName(Operators, T1Rec->getDecl());
7284     Operators.suppressDiagnostics();
7285 
7286     for (LookupResult::iterator Oper = Operators.begin(),
7287                              OperEnd = Operators.end();
7288          Oper != OperEnd;
7289          ++Oper)
7290       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7291                          Args[0]->Classify(Context), Args.slice(1),
7292                          CandidateSet, /*SuppressUserConversions=*/false);
7293   }
7294 }
7295 
7296 /// AddBuiltinCandidate - Add a candidate for a built-in
7297 /// operator. ResultTy and ParamTys are the result and parameter types
7298 /// of the built-in candidate, respectively. Args and NumArgs are the
7299 /// arguments being passed to the candidate. IsAssignmentOperator
7300 /// should be true when this built-in candidate is an assignment
7301 /// operator. NumContextualBoolArguments is the number of arguments
7302 /// (at the beginning of the argument list) that will be contextually
7303 /// converted to bool.
7304 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7305                                OverloadCandidateSet& CandidateSet,
7306                                bool IsAssignmentOperator,
7307                                unsigned NumContextualBoolArguments) {
7308   // Overload resolution is always an unevaluated context.
7309   EnterExpressionEvaluationContext Unevaluated(
7310       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7311 
7312   // Add this candidate
7313   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7314   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7315   Candidate.Function = nullptr;
7316   Candidate.IsSurrogate = false;
7317   Candidate.IgnoreObjectArgument = false;
7318   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7319 
7320   // Determine the implicit conversion sequences for each of the
7321   // arguments.
7322   Candidate.Viable = true;
7323   Candidate.ExplicitCallArguments = Args.size();
7324   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7325     // C++ [over.match.oper]p4:
7326     //   For the built-in assignment operators, conversions of the
7327     //   left operand are restricted as follows:
7328     //     -- no temporaries are introduced to hold the left operand, and
7329     //     -- no user-defined conversions are applied to the left
7330     //        operand to achieve a type match with the left-most
7331     //        parameter of a built-in candidate.
7332     //
7333     // We block these conversions by turning off user-defined
7334     // conversions, since that is the only way that initialization of
7335     // a reference to a non-class type can occur from something that
7336     // is not of the same type.
7337     if (ArgIdx < NumContextualBoolArguments) {
7338       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7339              "Contextual conversion to bool requires bool type");
7340       Candidate.Conversions[ArgIdx]
7341         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7342     } else {
7343       Candidate.Conversions[ArgIdx]
7344         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7345                                 ArgIdx == 0 && IsAssignmentOperator,
7346                                 /*InOverloadResolution=*/false,
7347                                 /*AllowObjCWritebackConversion=*/
7348                                   getLangOpts().ObjCAutoRefCount);
7349     }
7350     if (Candidate.Conversions[ArgIdx].isBad()) {
7351       Candidate.Viable = false;
7352       Candidate.FailureKind = ovl_fail_bad_conversion;
7353       break;
7354     }
7355   }
7356 }
7357 
7358 namespace {
7359 
7360 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7361 /// candidate operator functions for built-in operators (C++
7362 /// [over.built]). The types are separated into pointer types and
7363 /// enumeration types.
7364 class BuiltinCandidateTypeSet  {
7365   /// TypeSet - A set of types.
7366   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7367                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7368 
7369   /// PointerTypes - The set of pointer types that will be used in the
7370   /// built-in candidates.
7371   TypeSet PointerTypes;
7372 
7373   /// MemberPointerTypes - The set of member pointer types that will be
7374   /// used in the built-in candidates.
7375   TypeSet MemberPointerTypes;
7376 
7377   /// EnumerationTypes - The set of enumeration types that will be
7378   /// used in the built-in candidates.
7379   TypeSet EnumerationTypes;
7380 
7381   /// The set of vector types that will be used in the built-in
7382   /// candidates.
7383   TypeSet VectorTypes;
7384 
7385   /// A flag indicating non-record types are viable candidates
7386   bool HasNonRecordTypes;
7387 
7388   /// A flag indicating whether either arithmetic or enumeration types
7389   /// were present in the candidate set.
7390   bool HasArithmeticOrEnumeralTypes;
7391 
7392   /// A flag indicating whether the nullptr type was present in the
7393   /// candidate set.
7394   bool HasNullPtrType;
7395 
7396   /// Sema - The semantic analysis instance where we are building the
7397   /// candidate type set.
7398   Sema &SemaRef;
7399 
7400   /// Context - The AST context in which we will build the type sets.
7401   ASTContext &Context;
7402 
7403   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7404                                                const Qualifiers &VisibleQuals);
7405   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7406 
7407 public:
7408   /// iterator - Iterates through the types that are part of the set.
7409   typedef TypeSet::iterator iterator;
7410 
7411   BuiltinCandidateTypeSet(Sema &SemaRef)
7412     : HasNonRecordTypes(false),
7413       HasArithmeticOrEnumeralTypes(false),
7414       HasNullPtrType(false),
7415       SemaRef(SemaRef),
7416       Context(SemaRef.Context) { }
7417 
7418   void AddTypesConvertedFrom(QualType Ty,
7419                              SourceLocation Loc,
7420                              bool AllowUserConversions,
7421                              bool AllowExplicitConversions,
7422                              const Qualifiers &VisibleTypeConversionsQuals);
7423 
7424   /// pointer_begin - First pointer type found;
7425   iterator pointer_begin() { return PointerTypes.begin(); }
7426 
7427   /// pointer_end - Past the last pointer type found;
7428   iterator pointer_end() { return PointerTypes.end(); }
7429 
7430   /// member_pointer_begin - First member pointer type found;
7431   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7432 
7433   /// member_pointer_end - Past the last member pointer type found;
7434   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7435 
7436   /// enumeration_begin - First enumeration type found;
7437   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7438 
7439   /// enumeration_end - Past the last enumeration type found;
7440   iterator enumeration_end() { return EnumerationTypes.end(); }
7441 
7442   iterator vector_begin() { return VectorTypes.begin(); }
7443   iterator vector_end() { return VectorTypes.end(); }
7444 
7445   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7446   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7447   bool hasNullPtrType() const { return HasNullPtrType; }
7448 };
7449 
7450 } // end anonymous namespace
7451 
7452 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7453 /// the set of pointer types along with any more-qualified variants of
7454 /// that type. For example, if @p Ty is "int const *", this routine
7455 /// will add "int const *", "int const volatile *", "int const
7456 /// restrict *", and "int const volatile restrict *" to the set of
7457 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7458 /// false otherwise.
7459 ///
7460 /// FIXME: what to do about extended qualifiers?
7461 bool
7462 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7463                                              const Qualifiers &VisibleQuals) {
7464 
7465   // Insert this type.
7466   if (!PointerTypes.insert(Ty))
7467     return false;
7468 
7469   QualType PointeeTy;
7470   const PointerType *PointerTy = Ty->getAs<PointerType>();
7471   bool buildObjCPtr = false;
7472   if (!PointerTy) {
7473     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7474     PointeeTy = PTy->getPointeeType();
7475     buildObjCPtr = true;
7476   } else {
7477     PointeeTy = PointerTy->getPointeeType();
7478   }
7479 
7480   // Don't add qualified variants of arrays. For one, they're not allowed
7481   // (the qualifier would sink to the element type), and for another, the
7482   // only overload situation where it matters is subscript or pointer +- int,
7483   // and those shouldn't have qualifier variants anyway.
7484   if (PointeeTy->isArrayType())
7485     return true;
7486 
7487   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7488   bool hasVolatile = VisibleQuals.hasVolatile();
7489   bool hasRestrict = VisibleQuals.hasRestrict();
7490 
7491   // Iterate through all strict supersets of BaseCVR.
7492   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7493     if ((CVR | BaseCVR) != CVR) continue;
7494     // Skip over volatile if no volatile found anywhere in the types.
7495     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7496 
7497     // Skip over restrict if no restrict found anywhere in the types, or if
7498     // the type cannot be restrict-qualified.
7499     if ((CVR & Qualifiers::Restrict) &&
7500         (!hasRestrict ||
7501          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7502       continue;
7503 
7504     // Build qualified pointee type.
7505     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7506 
7507     // Build qualified pointer type.
7508     QualType QPointerTy;
7509     if (!buildObjCPtr)
7510       QPointerTy = Context.getPointerType(QPointeeTy);
7511     else
7512       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7513 
7514     // Insert qualified pointer type.
7515     PointerTypes.insert(QPointerTy);
7516   }
7517 
7518   return true;
7519 }
7520 
7521 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7522 /// to the set of pointer types along with any more-qualified variants of
7523 /// that type. For example, if @p Ty is "int const *", this routine
7524 /// will add "int const *", "int const volatile *", "int const
7525 /// restrict *", and "int const volatile restrict *" to the set of
7526 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7527 /// false otherwise.
7528 ///
7529 /// FIXME: what to do about extended qualifiers?
7530 bool
7531 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7532     QualType Ty) {
7533   // Insert this type.
7534   if (!MemberPointerTypes.insert(Ty))
7535     return false;
7536 
7537   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7538   assert(PointerTy && "type was not a member pointer type!");
7539 
7540   QualType PointeeTy = PointerTy->getPointeeType();
7541   // Don't add qualified variants of arrays. For one, they're not allowed
7542   // (the qualifier would sink to the element type), and for another, the
7543   // only overload situation where it matters is subscript or pointer +- int,
7544   // and those shouldn't have qualifier variants anyway.
7545   if (PointeeTy->isArrayType())
7546     return true;
7547   const Type *ClassTy = PointerTy->getClass();
7548 
7549   // Iterate through all strict supersets of the pointee type's CVR
7550   // qualifiers.
7551   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7552   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7553     if ((CVR | BaseCVR) != CVR) continue;
7554 
7555     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7556     MemberPointerTypes.insert(
7557       Context.getMemberPointerType(QPointeeTy, ClassTy));
7558   }
7559 
7560   return true;
7561 }
7562 
7563 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7564 /// Ty can be implicit converted to the given set of @p Types. We're
7565 /// primarily interested in pointer types and enumeration types. We also
7566 /// take member pointer types, for the conditional operator.
7567 /// AllowUserConversions is true if we should look at the conversion
7568 /// functions of a class type, and AllowExplicitConversions if we
7569 /// should also include the explicit conversion functions of a class
7570 /// type.
7571 void
7572 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7573                                                SourceLocation Loc,
7574                                                bool AllowUserConversions,
7575                                                bool AllowExplicitConversions,
7576                                                const Qualifiers &VisibleQuals) {
7577   // Only deal with canonical types.
7578   Ty = Context.getCanonicalType(Ty);
7579 
7580   // Look through reference types; they aren't part of the type of an
7581   // expression for the purposes of conversions.
7582   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7583     Ty = RefTy->getPointeeType();
7584 
7585   // If we're dealing with an array type, decay to the pointer.
7586   if (Ty->isArrayType())
7587     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7588 
7589   // Otherwise, we don't care about qualifiers on the type.
7590   Ty = Ty.getLocalUnqualifiedType();
7591 
7592   // Flag if we ever add a non-record type.
7593   const RecordType *TyRec = Ty->getAs<RecordType>();
7594   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7595 
7596   // Flag if we encounter an arithmetic type.
7597   HasArithmeticOrEnumeralTypes =
7598     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7599 
7600   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7601     PointerTypes.insert(Ty);
7602   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7603     // Insert our type, and its more-qualified variants, into the set
7604     // of types.
7605     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7606       return;
7607   } else if (Ty->isMemberPointerType()) {
7608     // Member pointers are far easier, since the pointee can't be converted.
7609     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7610       return;
7611   } else if (Ty->isEnumeralType()) {
7612     HasArithmeticOrEnumeralTypes = true;
7613     EnumerationTypes.insert(Ty);
7614   } else if (Ty->isVectorType()) {
7615     // We treat vector types as arithmetic types in many contexts as an
7616     // extension.
7617     HasArithmeticOrEnumeralTypes = true;
7618     VectorTypes.insert(Ty);
7619   } else if (Ty->isNullPtrType()) {
7620     HasNullPtrType = true;
7621   } else if (AllowUserConversions && TyRec) {
7622     // No conversion functions in incomplete types.
7623     if (!SemaRef.isCompleteType(Loc, Ty))
7624       return;
7625 
7626     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7627     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7628       if (isa<UsingShadowDecl>(D))
7629         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7630 
7631       // Skip conversion function templates; they don't tell us anything
7632       // about which builtin types we can convert to.
7633       if (isa<FunctionTemplateDecl>(D))
7634         continue;
7635 
7636       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7637       if (AllowExplicitConversions || !Conv->isExplicit()) {
7638         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7639                               VisibleQuals);
7640       }
7641     }
7642   }
7643 }
7644 /// Helper function for adjusting address spaces for the pointer or reference
7645 /// operands of builtin operators depending on the argument.
7646 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7647                                                         Expr *Arg) {
7648   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7649 }
7650 
7651 /// Helper function for AddBuiltinOperatorCandidates() that adds
7652 /// the volatile- and non-volatile-qualified assignment operators for the
7653 /// given type to the candidate set.
7654 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7655                                                    QualType T,
7656                                                    ArrayRef<Expr *> Args,
7657                                     OverloadCandidateSet &CandidateSet) {
7658   QualType ParamTypes[2];
7659 
7660   // T& operator=(T&, T)
7661   ParamTypes[0] = S.Context.getLValueReferenceType(
7662       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7663   ParamTypes[1] = T;
7664   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7665                         /*IsAssignmentOperator=*/true);
7666 
7667   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7668     // volatile T& operator=(volatile T&, T)
7669     ParamTypes[0] = S.Context.getLValueReferenceType(
7670         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7671                                                 Args[0]));
7672     ParamTypes[1] = T;
7673     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7674                           /*IsAssignmentOperator=*/true);
7675   }
7676 }
7677 
7678 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7679 /// if any, found in visible type conversion functions found in ArgExpr's type.
7680 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7681     Qualifiers VRQuals;
7682     const RecordType *TyRec;
7683     if (const MemberPointerType *RHSMPType =
7684         ArgExpr->getType()->getAs<MemberPointerType>())
7685       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7686     else
7687       TyRec = ArgExpr->getType()->getAs<RecordType>();
7688     if (!TyRec) {
7689       // Just to be safe, assume the worst case.
7690       VRQuals.addVolatile();
7691       VRQuals.addRestrict();
7692       return VRQuals;
7693     }
7694 
7695     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7696     if (!ClassDecl->hasDefinition())
7697       return VRQuals;
7698 
7699     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7700       if (isa<UsingShadowDecl>(D))
7701         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7702       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7703         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7704         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7705           CanTy = ResTypeRef->getPointeeType();
7706         // Need to go down the pointer/mempointer chain and add qualifiers
7707         // as see them.
7708         bool done = false;
7709         while (!done) {
7710           if (CanTy.isRestrictQualified())
7711             VRQuals.addRestrict();
7712           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7713             CanTy = ResTypePtr->getPointeeType();
7714           else if (const MemberPointerType *ResTypeMPtr =
7715                 CanTy->getAs<MemberPointerType>())
7716             CanTy = ResTypeMPtr->getPointeeType();
7717           else
7718             done = true;
7719           if (CanTy.isVolatileQualified())
7720             VRQuals.addVolatile();
7721           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7722             return VRQuals;
7723         }
7724       }
7725     }
7726     return VRQuals;
7727 }
7728 
7729 namespace {
7730 
7731 /// Helper class to manage the addition of builtin operator overload
7732 /// candidates. It provides shared state and utility methods used throughout
7733 /// the process, as well as a helper method to add each group of builtin
7734 /// operator overloads from the standard to a candidate set.
7735 class BuiltinOperatorOverloadBuilder {
7736   // Common instance state available to all overload candidate addition methods.
7737   Sema &S;
7738   ArrayRef<Expr *> Args;
7739   Qualifiers VisibleTypeConversionsQuals;
7740   bool HasArithmeticOrEnumeralCandidateType;
7741   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7742   OverloadCandidateSet &CandidateSet;
7743 
7744   static constexpr int ArithmeticTypesCap = 24;
7745   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7746 
7747   // Define some indices used to iterate over the arithemetic types in
7748   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7749   // types are that preserved by promotion (C++ [over.built]p2).
7750   unsigned FirstIntegralType,
7751            LastIntegralType;
7752   unsigned FirstPromotedIntegralType,
7753            LastPromotedIntegralType;
7754   unsigned FirstPromotedArithmeticType,
7755            LastPromotedArithmeticType;
7756   unsigned NumArithmeticTypes;
7757 
7758   void InitArithmeticTypes() {
7759     // Start of promoted types.
7760     FirstPromotedArithmeticType = 0;
7761     ArithmeticTypes.push_back(S.Context.FloatTy);
7762     ArithmeticTypes.push_back(S.Context.DoubleTy);
7763     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7764     if (S.Context.getTargetInfo().hasFloat128Type())
7765       ArithmeticTypes.push_back(S.Context.Float128Ty);
7766 
7767     // Start of integral types.
7768     FirstIntegralType = ArithmeticTypes.size();
7769     FirstPromotedIntegralType = ArithmeticTypes.size();
7770     ArithmeticTypes.push_back(S.Context.IntTy);
7771     ArithmeticTypes.push_back(S.Context.LongTy);
7772     ArithmeticTypes.push_back(S.Context.LongLongTy);
7773     if (S.Context.getTargetInfo().hasInt128Type())
7774       ArithmeticTypes.push_back(S.Context.Int128Ty);
7775     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7776     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7777     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7778     if (S.Context.getTargetInfo().hasInt128Type())
7779       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7780     LastPromotedIntegralType = ArithmeticTypes.size();
7781     LastPromotedArithmeticType = ArithmeticTypes.size();
7782     // End of promoted types.
7783 
7784     ArithmeticTypes.push_back(S.Context.BoolTy);
7785     ArithmeticTypes.push_back(S.Context.CharTy);
7786     ArithmeticTypes.push_back(S.Context.WCharTy);
7787     if (S.Context.getLangOpts().Char8)
7788       ArithmeticTypes.push_back(S.Context.Char8Ty);
7789     ArithmeticTypes.push_back(S.Context.Char16Ty);
7790     ArithmeticTypes.push_back(S.Context.Char32Ty);
7791     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7792     ArithmeticTypes.push_back(S.Context.ShortTy);
7793     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7794     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7795     LastIntegralType = ArithmeticTypes.size();
7796     NumArithmeticTypes = ArithmeticTypes.size();
7797     // End of integral types.
7798     // FIXME: What about complex? What about half?
7799 
7800     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7801            "Enough inline storage for all arithmetic types.");
7802   }
7803 
7804   /// Helper method to factor out the common pattern of adding overloads
7805   /// for '++' and '--' builtin operators.
7806   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7807                                            bool HasVolatile,
7808                                            bool HasRestrict) {
7809     QualType ParamTypes[2] = {
7810       S.Context.getLValueReferenceType(CandidateTy),
7811       S.Context.IntTy
7812     };
7813 
7814     // Non-volatile version.
7815     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7816 
7817     // Use a heuristic to reduce number of builtin candidates in the set:
7818     // add volatile version only if there are conversions to a volatile type.
7819     if (HasVolatile) {
7820       ParamTypes[0] =
7821         S.Context.getLValueReferenceType(
7822           S.Context.getVolatileType(CandidateTy));
7823       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7824     }
7825 
7826     // Add restrict version only if there are conversions to a restrict type
7827     // and our candidate type is a non-restrict-qualified pointer.
7828     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7829         !CandidateTy.isRestrictQualified()) {
7830       ParamTypes[0]
7831         = S.Context.getLValueReferenceType(
7832             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7833       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7834 
7835       if (HasVolatile) {
7836         ParamTypes[0]
7837           = S.Context.getLValueReferenceType(
7838               S.Context.getCVRQualifiedType(CandidateTy,
7839                                             (Qualifiers::Volatile |
7840                                              Qualifiers::Restrict)));
7841         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7842       }
7843     }
7844 
7845   }
7846 
7847 public:
7848   BuiltinOperatorOverloadBuilder(
7849     Sema &S, ArrayRef<Expr *> Args,
7850     Qualifiers VisibleTypeConversionsQuals,
7851     bool HasArithmeticOrEnumeralCandidateType,
7852     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7853     OverloadCandidateSet &CandidateSet)
7854     : S(S), Args(Args),
7855       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7856       HasArithmeticOrEnumeralCandidateType(
7857         HasArithmeticOrEnumeralCandidateType),
7858       CandidateTypes(CandidateTypes),
7859       CandidateSet(CandidateSet) {
7860 
7861     InitArithmeticTypes();
7862   }
7863 
7864   // Increment is deprecated for bool since C++17.
7865   //
7866   // C++ [over.built]p3:
7867   //
7868   //   For every pair (T, VQ), where T is an arithmetic type other
7869   //   than bool, and VQ is either volatile or empty, there exist
7870   //   candidate operator functions of the form
7871   //
7872   //       VQ T&      operator++(VQ T&);
7873   //       T          operator++(VQ T&, int);
7874   //
7875   // C++ [over.built]p4:
7876   //
7877   //   For every pair (T, VQ), where T is an arithmetic type other
7878   //   than bool, and VQ is either volatile or empty, there exist
7879   //   candidate operator functions of the form
7880   //
7881   //       VQ T&      operator--(VQ T&);
7882   //       T          operator--(VQ T&, int);
7883   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7884     if (!HasArithmeticOrEnumeralCandidateType)
7885       return;
7886 
7887     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7888       const auto TypeOfT = ArithmeticTypes[Arith];
7889       if (TypeOfT == S.Context.BoolTy) {
7890         if (Op == OO_MinusMinus)
7891           continue;
7892         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7893           continue;
7894       }
7895       addPlusPlusMinusMinusStyleOverloads(
7896         TypeOfT,
7897         VisibleTypeConversionsQuals.hasVolatile(),
7898         VisibleTypeConversionsQuals.hasRestrict());
7899     }
7900   }
7901 
7902   // C++ [over.built]p5:
7903   //
7904   //   For every pair (T, VQ), where T is a cv-qualified or
7905   //   cv-unqualified object type, and VQ is either volatile or
7906   //   empty, there exist candidate operator functions of the form
7907   //
7908   //       T*VQ&      operator++(T*VQ&);
7909   //       T*VQ&      operator--(T*VQ&);
7910   //       T*         operator++(T*VQ&, int);
7911   //       T*         operator--(T*VQ&, int);
7912   void addPlusPlusMinusMinusPointerOverloads() {
7913     for (BuiltinCandidateTypeSet::iterator
7914               Ptr = CandidateTypes[0].pointer_begin(),
7915            PtrEnd = CandidateTypes[0].pointer_end();
7916          Ptr != PtrEnd; ++Ptr) {
7917       // Skip pointer types that aren't pointers to object types.
7918       if (!(*Ptr)->getPointeeType()->isObjectType())
7919         continue;
7920 
7921       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7922         (!(*Ptr).isVolatileQualified() &&
7923          VisibleTypeConversionsQuals.hasVolatile()),
7924         (!(*Ptr).isRestrictQualified() &&
7925          VisibleTypeConversionsQuals.hasRestrict()));
7926     }
7927   }
7928 
7929   // C++ [over.built]p6:
7930   //   For every cv-qualified or cv-unqualified object type T, there
7931   //   exist candidate operator functions of the form
7932   //
7933   //       T&         operator*(T*);
7934   //
7935   // C++ [over.built]p7:
7936   //   For every function type T that does not have cv-qualifiers or a
7937   //   ref-qualifier, there exist candidate operator functions of the form
7938   //       T&         operator*(T*);
7939   void addUnaryStarPointerOverloads() {
7940     for (BuiltinCandidateTypeSet::iterator
7941               Ptr = CandidateTypes[0].pointer_begin(),
7942            PtrEnd = CandidateTypes[0].pointer_end();
7943          Ptr != PtrEnd; ++Ptr) {
7944       QualType ParamTy = *Ptr;
7945       QualType PointeeTy = ParamTy->getPointeeType();
7946       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7947         continue;
7948 
7949       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7950         if (Proto->getMethodQuals() || Proto->getRefQualifier())
7951           continue;
7952 
7953       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7954     }
7955   }
7956 
7957   // C++ [over.built]p9:
7958   //  For every promoted arithmetic type T, there exist candidate
7959   //  operator functions of the form
7960   //
7961   //       T         operator+(T);
7962   //       T         operator-(T);
7963   void addUnaryPlusOrMinusArithmeticOverloads() {
7964     if (!HasArithmeticOrEnumeralCandidateType)
7965       return;
7966 
7967     for (unsigned Arith = FirstPromotedArithmeticType;
7968          Arith < LastPromotedArithmeticType; ++Arith) {
7969       QualType ArithTy = ArithmeticTypes[Arith];
7970       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7971     }
7972 
7973     // Extension: We also add these operators for vector types.
7974     for (BuiltinCandidateTypeSet::iterator
7975               Vec = CandidateTypes[0].vector_begin(),
7976            VecEnd = CandidateTypes[0].vector_end();
7977          Vec != VecEnd; ++Vec) {
7978       QualType VecTy = *Vec;
7979       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7980     }
7981   }
7982 
7983   // C++ [over.built]p8:
7984   //   For every type T, there exist candidate operator functions of
7985   //   the form
7986   //
7987   //       T*         operator+(T*);
7988   void addUnaryPlusPointerOverloads() {
7989     for (BuiltinCandidateTypeSet::iterator
7990               Ptr = CandidateTypes[0].pointer_begin(),
7991            PtrEnd = CandidateTypes[0].pointer_end();
7992          Ptr != PtrEnd; ++Ptr) {
7993       QualType ParamTy = *Ptr;
7994       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7995     }
7996   }
7997 
7998   // C++ [over.built]p10:
7999   //   For every promoted integral type T, there exist candidate
8000   //   operator functions of the form
8001   //
8002   //        T         operator~(T);
8003   void addUnaryTildePromotedIntegralOverloads() {
8004     if (!HasArithmeticOrEnumeralCandidateType)
8005       return;
8006 
8007     for (unsigned Int = FirstPromotedIntegralType;
8008          Int < LastPromotedIntegralType; ++Int) {
8009       QualType IntTy = ArithmeticTypes[Int];
8010       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8011     }
8012 
8013     // Extension: We also add this operator for vector types.
8014     for (BuiltinCandidateTypeSet::iterator
8015               Vec = CandidateTypes[0].vector_begin(),
8016            VecEnd = CandidateTypes[0].vector_end();
8017          Vec != VecEnd; ++Vec) {
8018       QualType VecTy = *Vec;
8019       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8020     }
8021   }
8022 
8023   // C++ [over.match.oper]p16:
8024   //   For every pointer to member type T or type std::nullptr_t, there
8025   //   exist candidate operator functions of the form
8026   //
8027   //        bool operator==(T,T);
8028   //        bool operator!=(T,T);
8029   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8030     /// Set of (canonical) types that we've already handled.
8031     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8032 
8033     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8034       for (BuiltinCandidateTypeSet::iterator
8035                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8036              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8037            MemPtr != MemPtrEnd;
8038            ++MemPtr) {
8039         // Don't add the same builtin candidate twice.
8040         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8041           continue;
8042 
8043         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8044         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8045       }
8046 
8047       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8048         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8049         if (AddedTypes.insert(NullPtrTy).second) {
8050           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8051           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8052         }
8053       }
8054     }
8055   }
8056 
8057   // C++ [over.built]p15:
8058   //
8059   //   For every T, where T is an enumeration type or a pointer type,
8060   //   there exist candidate operator functions of the form
8061   //
8062   //        bool       operator<(T, T);
8063   //        bool       operator>(T, T);
8064   //        bool       operator<=(T, T);
8065   //        bool       operator>=(T, T);
8066   //        bool       operator==(T, T);
8067   //        bool       operator!=(T, T);
8068   //           R       operator<=>(T, T)
8069   void addGenericBinaryPointerOrEnumeralOverloads() {
8070     // C++ [over.match.oper]p3:
8071     //   [...]the built-in candidates include all of the candidate operator
8072     //   functions defined in 13.6 that, compared to the given operator, [...]
8073     //   do not have the same parameter-type-list as any non-template non-member
8074     //   candidate.
8075     //
8076     // Note that in practice, this only affects enumeration types because there
8077     // aren't any built-in candidates of record type, and a user-defined operator
8078     // must have an operand of record or enumeration type. Also, the only other
8079     // overloaded operator with enumeration arguments, operator=,
8080     // cannot be overloaded for enumeration types, so this is the only place
8081     // where we must suppress candidates like this.
8082     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8083       UserDefinedBinaryOperators;
8084 
8085     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8086       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8087           CandidateTypes[ArgIdx].enumeration_end()) {
8088         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8089                                          CEnd = CandidateSet.end();
8090              C != CEnd; ++C) {
8091           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8092             continue;
8093 
8094           if (C->Function->isFunctionTemplateSpecialization())
8095             continue;
8096 
8097           QualType FirstParamType =
8098             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8099           QualType SecondParamType =
8100             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8101 
8102           // Skip if either parameter isn't of enumeral type.
8103           if (!FirstParamType->isEnumeralType() ||
8104               !SecondParamType->isEnumeralType())
8105             continue;
8106 
8107           // Add this operator to the set of known user-defined operators.
8108           UserDefinedBinaryOperators.insert(
8109             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8110                            S.Context.getCanonicalType(SecondParamType)));
8111         }
8112       }
8113     }
8114 
8115     /// Set of (canonical) types that we've already handled.
8116     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8117 
8118     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8119       for (BuiltinCandidateTypeSet::iterator
8120                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8121              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8122            Ptr != PtrEnd; ++Ptr) {
8123         // Don't add the same builtin candidate twice.
8124         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8125           continue;
8126 
8127         QualType ParamTypes[2] = { *Ptr, *Ptr };
8128         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129       }
8130       for (BuiltinCandidateTypeSet::iterator
8131                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8132              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8133            Enum != EnumEnd; ++Enum) {
8134         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8135 
8136         // Don't add the same builtin candidate twice, or if a user defined
8137         // candidate exists.
8138         if (!AddedTypes.insert(CanonType).second ||
8139             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8140                                                             CanonType)))
8141           continue;
8142         QualType ParamTypes[2] = { *Enum, *Enum };
8143         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8144       }
8145     }
8146   }
8147 
8148   // C++ [over.built]p13:
8149   //
8150   //   For every cv-qualified or cv-unqualified object type T
8151   //   there exist candidate operator functions of the form
8152   //
8153   //      T*         operator+(T*, ptrdiff_t);
8154   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8155   //      T*         operator-(T*, ptrdiff_t);
8156   //      T*         operator+(ptrdiff_t, T*);
8157   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8158   //
8159   // C++ [over.built]p14:
8160   //
8161   //   For every T, where T is a pointer to object type, there
8162   //   exist candidate operator functions of the form
8163   //
8164   //      ptrdiff_t  operator-(T, T);
8165   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8166     /// Set of (canonical) types that we've already handled.
8167     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8168 
8169     for (int Arg = 0; Arg < 2; ++Arg) {
8170       QualType AsymmetricParamTypes[2] = {
8171         S.Context.getPointerDiffType(),
8172         S.Context.getPointerDiffType(),
8173       };
8174       for (BuiltinCandidateTypeSet::iterator
8175                 Ptr = CandidateTypes[Arg].pointer_begin(),
8176              PtrEnd = CandidateTypes[Arg].pointer_end();
8177            Ptr != PtrEnd; ++Ptr) {
8178         QualType PointeeTy = (*Ptr)->getPointeeType();
8179         if (!PointeeTy->isObjectType())
8180           continue;
8181 
8182         AsymmetricParamTypes[Arg] = *Ptr;
8183         if (Arg == 0 || Op == OO_Plus) {
8184           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8185           // T* operator+(ptrdiff_t, T*);
8186           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8187         }
8188         if (Op == OO_Minus) {
8189           // ptrdiff_t operator-(T, T);
8190           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8191             continue;
8192 
8193           QualType ParamTypes[2] = { *Ptr, *Ptr };
8194           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8195         }
8196       }
8197     }
8198   }
8199 
8200   // C++ [over.built]p12:
8201   //
8202   //   For every pair of promoted arithmetic types L and R, there
8203   //   exist candidate operator functions of the form
8204   //
8205   //        LR         operator*(L, R);
8206   //        LR         operator/(L, R);
8207   //        LR         operator+(L, R);
8208   //        LR         operator-(L, R);
8209   //        bool       operator<(L, R);
8210   //        bool       operator>(L, R);
8211   //        bool       operator<=(L, R);
8212   //        bool       operator>=(L, R);
8213   //        bool       operator==(L, R);
8214   //        bool       operator!=(L, R);
8215   //
8216   //   where LR is the result of the usual arithmetic conversions
8217   //   between types L and R.
8218   //
8219   // C++ [over.built]p24:
8220   //
8221   //   For every pair of promoted arithmetic types L and R, there exist
8222   //   candidate operator functions of the form
8223   //
8224   //        LR       operator?(bool, L, R);
8225   //
8226   //   where LR is the result of the usual arithmetic conversions
8227   //   between types L and R.
8228   // Our candidates ignore the first parameter.
8229   void addGenericBinaryArithmeticOverloads() {
8230     if (!HasArithmeticOrEnumeralCandidateType)
8231       return;
8232 
8233     for (unsigned Left = FirstPromotedArithmeticType;
8234          Left < LastPromotedArithmeticType; ++Left) {
8235       for (unsigned Right = FirstPromotedArithmeticType;
8236            Right < LastPromotedArithmeticType; ++Right) {
8237         QualType LandR[2] = { ArithmeticTypes[Left],
8238                               ArithmeticTypes[Right] };
8239         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8240       }
8241     }
8242 
8243     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8244     // conditional operator for vector types.
8245     for (BuiltinCandidateTypeSet::iterator
8246               Vec1 = CandidateTypes[0].vector_begin(),
8247            Vec1End = CandidateTypes[0].vector_end();
8248          Vec1 != Vec1End; ++Vec1) {
8249       for (BuiltinCandidateTypeSet::iterator
8250                 Vec2 = CandidateTypes[1].vector_begin(),
8251              Vec2End = CandidateTypes[1].vector_end();
8252            Vec2 != Vec2End; ++Vec2) {
8253         QualType LandR[2] = { *Vec1, *Vec2 };
8254         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8255       }
8256     }
8257   }
8258 
8259   // C++2a [over.built]p14:
8260   //
8261   //   For every integral type T there exists a candidate operator function
8262   //   of the form
8263   //
8264   //        std::strong_ordering operator<=>(T, T)
8265   //
8266   // C++2a [over.built]p15:
8267   //
8268   //   For every pair of floating-point types L and R, there exists a candidate
8269   //   operator function of the form
8270   //
8271   //       std::partial_ordering operator<=>(L, R);
8272   //
8273   // FIXME: The current specification for integral types doesn't play nice with
8274   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8275   // comparisons. Under the current spec this can lead to ambiguity during
8276   // overload resolution. For example:
8277   //
8278   //   enum A : int {a};
8279   //   auto x = (a <=> (long)42);
8280   //
8281   //   error: call is ambiguous for arguments 'A' and 'long'.
8282   //   note: candidate operator<=>(int, int)
8283   //   note: candidate operator<=>(long, long)
8284   //
8285   // To avoid this error, this function deviates from the specification and adds
8286   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8287   // arithmetic types (the same as the generic relational overloads).
8288   //
8289   // For now this function acts as a placeholder.
8290   void addThreeWayArithmeticOverloads() {
8291     addGenericBinaryArithmeticOverloads();
8292   }
8293 
8294   // C++ [over.built]p17:
8295   //
8296   //   For every pair of promoted integral types L and R, there
8297   //   exist candidate operator functions of the form
8298   //
8299   //      LR         operator%(L, R);
8300   //      LR         operator&(L, R);
8301   //      LR         operator^(L, R);
8302   //      LR         operator|(L, R);
8303   //      L          operator<<(L, R);
8304   //      L          operator>>(L, R);
8305   //
8306   //   where LR is the result of the usual arithmetic conversions
8307   //   between types L and R.
8308   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8309     if (!HasArithmeticOrEnumeralCandidateType)
8310       return;
8311 
8312     for (unsigned Left = FirstPromotedIntegralType;
8313          Left < LastPromotedIntegralType; ++Left) {
8314       for (unsigned Right = FirstPromotedIntegralType;
8315            Right < LastPromotedIntegralType; ++Right) {
8316         QualType LandR[2] = { ArithmeticTypes[Left],
8317                               ArithmeticTypes[Right] };
8318         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8319       }
8320     }
8321   }
8322 
8323   // C++ [over.built]p20:
8324   //
8325   //   For every pair (T, VQ), where T is an enumeration or
8326   //   pointer to member type and VQ is either volatile or
8327   //   empty, there exist candidate operator functions of the form
8328   //
8329   //        VQ T&      operator=(VQ T&, T);
8330   void addAssignmentMemberPointerOrEnumeralOverloads() {
8331     /// Set of (canonical) types that we've already handled.
8332     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8333 
8334     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8335       for (BuiltinCandidateTypeSet::iterator
8336                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8337              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8338            Enum != EnumEnd; ++Enum) {
8339         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8340           continue;
8341 
8342         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8343       }
8344 
8345       for (BuiltinCandidateTypeSet::iterator
8346                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8347              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8348            MemPtr != MemPtrEnd; ++MemPtr) {
8349         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8350           continue;
8351 
8352         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8353       }
8354     }
8355   }
8356 
8357   // C++ [over.built]p19:
8358   //
8359   //   For every pair (T, VQ), where T is any type and VQ is either
8360   //   volatile or empty, there exist candidate operator functions
8361   //   of the form
8362   //
8363   //        T*VQ&      operator=(T*VQ&, T*);
8364   //
8365   // C++ [over.built]p21:
8366   //
8367   //   For every pair (T, VQ), where T is a cv-qualified or
8368   //   cv-unqualified object type and VQ is either volatile or
8369   //   empty, there exist candidate operator functions of the form
8370   //
8371   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8372   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8373   void addAssignmentPointerOverloads(bool isEqualOp) {
8374     /// Set of (canonical) types that we've already handled.
8375     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8376 
8377     for (BuiltinCandidateTypeSet::iterator
8378               Ptr = CandidateTypes[0].pointer_begin(),
8379            PtrEnd = CandidateTypes[0].pointer_end();
8380          Ptr != PtrEnd; ++Ptr) {
8381       // If this is operator=, keep track of the builtin candidates we added.
8382       if (isEqualOp)
8383         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8384       else if (!(*Ptr)->getPointeeType()->isObjectType())
8385         continue;
8386 
8387       // non-volatile version
8388       QualType ParamTypes[2] = {
8389         S.Context.getLValueReferenceType(*Ptr),
8390         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8391       };
8392       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8393                             /*IsAssigmentOperator=*/ isEqualOp);
8394 
8395       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8396                           VisibleTypeConversionsQuals.hasVolatile();
8397       if (NeedVolatile) {
8398         // volatile version
8399         ParamTypes[0] =
8400           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8401         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402                               /*IsAssigmentOperator=*/isEqualOp);
8403       }
8404 
8405       if (!(*Ptr).isRestrictQualified() &&
8406           VisibleTypeConversionsQuals.hasRestrict()) {
8407         // restrict version
8408         ParamTypes[0]
8409           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8410         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8411                               /*IsAssigmentOperator=*/isEqualOp);
8412 
8413         if (NeedVolatile) {
8414           // volatile restrict version
8415           ParamTypes[0]
8416             = S.Context.getLValueReferenceType(
8417                 S.Context.getCVRQualifiedType(*Ptr,
8418                                               (Qualifiers::Volatile |
8419                                                Qualifiers::Restrict)));
8420           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421                                 /*IsAssigmentOperator=*/isEqualOp);
8422         }
8423       }
8424     }
8425 
8426     if (isEqualOp) {
8427       for (BuiltinCandidateTypeSet::iterator
8428                 Ptr = CandidateTypes[1].pointer_begin(),
8429              PtrEnd = CandidateTypes[1].pointer_end();
8430            Ptr != PtrEnd; ++Ptr) {
8431         // Make sure we don't add the same candidate twice.
8432         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8433           continue;
8434 
8435         QualType ParamTypes[2] = {
8436           S.Context.getLValueReferenceType(*Ptr),
8437           *Ptr,
8438         };
8439 
8440         // non-volatile version
8441         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8442                               /*IsAssigmentOperator=*/true);
8443 
8444         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8445                            VisibleTypeConversionsQuals.hasVolatile();
8446         if (NeedVolatile) {
8447           // volatile version
8448           ParamTypes[0] =
8449             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8450           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8451                                 /*IsAssigmentOperator=*/true);
8452         }
8453 
8454         if (!(*Ptr).isRestrictQualified() &&
8455             VisibleTypeConversionsQuals.hasRestrict()) {
8456           // restrict version
8457           ParamTypes[0]
8458             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8459           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8460                                 /*IsAssigmentOperator=*/true);
8461 
8462           if (NeedVolatile) {
8463             // volatile restrict version
8464             ParamTypes[0]
8465               = S.Context.getLValueReferenceType(
8466                   S.Context.getCVRQualifiedType(*Ptr,
8467                                                 (Qualifiers::Volatile |
8468                                                  Qualifiers::Restrict)));
8469             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8470                                   /*IsAssigmentOperator=*/true);
8471           }
8472         }
8473       }
8474     }
8475   }
8476 
8477   // C++ [over.built]p18:
8478   //
8479   //   For every triple (L, VQ, R), where L is an arithmetic type,
8480   //   VQ is either volatile or empty, and R is a promoted
8481   //   arithmetic type, there exist candidate operator functions of
8482   //   the form
8483   //
8484   //        VQ L&      operator=(VQ L&, R);
8485   //        VQ L&      operator*=(VQ L&, R);
8486   //        VQ L&      operator/=(VQ L&, R);
8487   //        VQ L&      operator+=(VQ L&, R);
8488   //        VQ L&      operator-=(VQ L&, R);
8489   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8490     if (!HasArithmeticOrEnumeralCandidateType)
8491       return;
8492 
8493     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8494       for (unsigned Right = FirstPromotedArithmeticType;
8495            Right < LastPromotedArithmeticType; ++Right) {
8496         QualType ParamTypes[2];
8497         ParamTypes[1] = ArithmeticTypes[Right];
8498         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8499             S, ArithmeticTypes[Left], Args[0]);
8500         // Add this built-in operator as a candidate (VQ is empty).
8501         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8502         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8503                               /*IsAssigmentOperator=*/isEqualOp);
8504 
8505         // Add this built-in operator as a candidate (VQ is 'volatile').
8506         if (VisibleTypeConversionsQuals.hasVolatile()) {
8507           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8508           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8509           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8510                                 /*IsAssigmentOperator=*/isEqualOp);
8511         }
8512       }
8513     }
8514 
8515     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8516     for (BuiltinCandidateTypeSet::iterator
8517               Vec1 = CandidateTypes[0].vector_begin(),
8518            Vec1End = CandidateTypes[0].vector_end();
8519          Vec1 != Vec1End; ++Vec1) {
8520       for (BuiltinCandidateTypeSet::iterator
8521                 Vec2 = CandidateTypes[1].vector_begin(),
8522              Vec2End = CandidateTypes[1].vector_end();
8523            Vec2 != Vec2End; ++Vec2) {
8524         QualType ParamTypes[2];
8525         ParamTypes[1] = *Vec2;
8526         // Add this built-in operator as a candidate (VQ is empty).
8527         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8528         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8529                               /*IsAssigmentOperator=*/isEqualOp);
8530 
8531         // Add this built-in operator as a candidate (VQ is 'volatile').
8532         if (VisibleTypeConversionsQuals.hasVolatile()) {
8533           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8534           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8535           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8536                                 /*IsAssigmentOperator=*/isEqualOp);
8537         }
8538       }
8539     }
8540   }
8541 
8542   // C++ [over.built]p22:
8543   //
8544   //   For every triple (L, VQ, R), where L is an integral type, VQ
8545   //   is either volatile or empty, and R is a promoted integral
8546   //   type, there exist candidate operator functions of the form
8547   //
8548   //        VQ L&       operator%=(VQ L&, R);
8549   //        VQ L&       operator<<=(VQ L&, R);
8550   //        VQ L&       operator>>=(VQ L&, R);
8551   //        VQ L&       operator&=(VQ L&, R);
8552   //        VQ L&       operator^=(VQ L&, R);
8553   //        VQ L&       operator|=(VQ L&, R);
8554   void addAssignmentIntegralOverloads() {
8555     if (!HasArithmeticOrEnumeralCandidateType)
8556       return;
8557 
8558     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8559       for (unsigned Right = FirstPromotedIntegralType;
8560            Right < LastPromotedIntegralType; ++Right) {
8561         QualType ParamTypes[2];
8562         ParamTypes[1] = ArithmeticTypes[Right];
8563         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8564             S, ArithmeticTypes[Left], Args[0]);
8565         // Add this built-in operator as a candidate (VQ is empty).
8566         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8567         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8568         if (VisibleTypeConversionsQuals.hasVolatile()) {
8569           // Add this built-in operator as a candidate (VQ is 'volatile').
8570           ParamTypes[0] = LeftBaseTy;
8571           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8572           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8573           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8574         }
8575       }
8576     }
8577   }
8578 
8579   // C++ [over.operator]p23:
8580   //
8581   //   There also exist candidate operator functions of the form
8582   //
8583   //        bool        operator!(bool);
8584   //        bool        operator&&(bool, bool);
8585   //        bool        operator||(bool, bool);
8586   void addExclaimOverload() {
8587     QualType ParamTy = S.Context.BoolTy;
8588     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8589                           /*IsAssignmentOperator=*/false,
8590                           /*NumContextualBoolArguments=*/1);
8591   }
8592   void addAmpAmpOrPipePipeOverload() {
8593     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8594     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8595                           /*IsAssignmentOperator=*/false,
8596                           /*NumContextualBoolArguments=*/2);
8597   }
8598 
8599   // C++ [over.built]p13:
8600   //
8601   //   For every cv-qualified or cv-unqualified object type T there
8602   //   exist candidate operator functions of the form
8603   //
8604   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8605   //        T&         operator[](T*, ptrdiff_t);
8606   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8607   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8608   //        T&         operator[](ptrdiff_t, T*);
8609   void addSubscriptOverloads() {
8610     for (BuiltinCandidateTypeSet::iterator
8611               Ptr = CandidateTypes[0].pointer_begin(),
8612            PtrEnd = CandidateTypes[0].pointer_end();
8613          Ptr != PtrEnd; ++Ptr) {
8614       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8615       QualType PointeeType = (*Ptr)->getPointeeType();
8616       if (!PointeeType->isObjectType())
8617         continue;
8618 
8619       // T& operator[](T*, ptrdiff_t)
8620       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8621     }
8622 
8623     for (BuiltinCandidateTypeSet::iterator
8624               Ptr = CandidateTypes[1].pointer_begin(),
8625            PtrEnd = CandidateTypes[1].pointer_end();
8626          Ptr != PtrEnd; ++Ptr) {
8627       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8628       QualType PointeeType = (*Ptr)->getPointeeType();
8629       if (!PointeeType->isObjectType())
8630         continue;
8631 
8632       // T& operator[](ptrdiff_t, T*)
8633       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8634     }
8635   }
8636 
8637   // C++ [over.built]p11:
8638   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8639   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8640   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8641   //    there exist candidate operator functions of the form
8642   //
8643   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8644   //
8645   //    where CV12 is the union of CV1 and CV2.
8646   void addArrowStarOverloads() {
8647     for (BuiltinCandidateTypeSet::iterator
8648              Ptr = CandidateTypes[0].pointer_begin(),
8649            PtrEnd = CandidateTypes[0].pointer_end();
8650          Ptr != PtrEnd; ++Ptr) {
8651       QualType C1Ty = (*Ptr);
8652       QualType C1;
8653       QualifierCollector Q1;
8654       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8655       if (!isa<RecordType>(C1))
8656         continue;
8657       // heuristic to reduce number of builtin candidates in the set.
8658       // Add volatile/restrict version only if there are conversions to a
8659       // volatile/restrict type.
8660       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8661         continue;
8662       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8663         continue;
8664       for (BuiltinCandidateTypeSet::iterator
8665                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8666              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8667            MemPtr != MemPtrEnd; ++MemPtr) {
8668         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8669         QualType C2 = QualType(mptr->getClass(), 0);
8670         C2 = C2.getUnqualifiedType();
8671         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8672           break;
8673         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8674         // build CV12 T&
8675         QualType T = mptr->getPointeeType();
8676         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8677             T.isVolatileQualified())
8678           continue;
8679         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8680             T.isRestrictQualified())
8681           continue;
8682         T = Q1.apply(S.Context, T);
8683         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8684       }
8685     }
8686   }
8687 
8688   // Note that we don't consider the first argument, since it has been
8689   // contextually converted to bool long ago. The candidates below are
8690   // therefore added as binary.
8691   //
8692   // C++ [over.built]p25:
8693   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8694   //   enumeration type, there exist candidate operator functions of the form
8695   //
8696   //        T        operator?(bool, T, T);
8697   //
8698   void addConditionalOperatorOverloads() {
8699     /// Set of (canonical) types that we've already handled.
8700     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8701 
8702     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8703       for (BuiltinCandidateTypeSet::iterator
8704                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8705              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8706            Ptr != PtrEnd; ++Ptr) {
8707         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8708           continue;
8709 
8710         QualType ParamTypes[2] = { *Ptr, *Ptr };
8711         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8712       }
8713 
8714       for (BuiltinCandidateTypeSet::iterator
8715                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8716              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8717            MemPtr != MemPtrEnd; ++MemPtr) {
8718         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8719           continue;
8720 
8721         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8722         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8723       }
8724 
8725       if (S.getLangOpts().CPlusPlus11) {
8726         for (BuiltinCandidateTypeSet::iterator
8727                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8728                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8729              Enum != EnumEnd; ++Enum) {
8730           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8731             continue;
8732 
8733           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8734             continue;
8735 
8736           QualType ParamTypes[2] = { *Enum, *Enum };
8737           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8738         }
8739       }
8740     }
8741   }
8742 };
8743 
8744 } // end anonymous namespace
8745 
8746 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8747 /// operator overloads to the candidate set (C++ [over.built]), based
8748 /// on the operator @p Op and the arguments given. For example, if the
8749 /// operator is a binary '+', this routine might add "int
8750 /// operator+(int, int)" to cover integer addition.
8751 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8752                                         SourceLocation OpLoc,
8753                                         ArrayRef<Expr *> Args,
8754                                         OverloadCandidateSet &CandidateSet) {
8755   // Find all of the types that the arguments can convert to, but only
8756   // if the operator we're looking at has built-in operator candidates
8757   // that make use of these types. Also record whether we encounter non-record
8758   // candidate types or either arithmetic or enumeral candidate types.
8759   Qualifiers VisibleTypeConversionsQuals;
8760   VisibleTypeConversionsQuals.addConst();
8761   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8762     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8763 
8764   bool HasNonRecordCandidateType = false;
8765   bool HasArithmeticOrEnumeralCandidateType = false;
8766   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8767   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8768     CandidateTypes.emplace_back(*this);
8769     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8770                                                  OpLoc,
8771                                                  true,
8772                                                  (Op == OO_Exclaim ||
8773                                                   Op == OO_AmpAmp ||
8774                                                   Op == OO_PipePipe),
8775                                                  VisibleTypeConversionsQuals);
8776     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8777         CandidateTypes[ArgIdx].hasNonRecordTypes();
8778     HasArithmeticOrEnumeralCandidateType =
8779         HasArithmeticOrEnumeralCandidateType ||
8780         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8781   }
8782 
8783   // Exit early when no non-record types have been added to the candidate set
8784   // for any of the arguments to the operator.
8785   //
8786   // We can't exit early for !, ||, or &&, since there we have always have
8787   // 'bool' overloads.
8788   if (!HasNonRecordCandidateType &&
8789       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8790     return;
8791 
8792   // Setup an object to manage the common state for building overloads.
8793   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8794                                            VisibleTypeConversionsQuals,
8795                                            HasArithmeticOrEnumeralCandidateType,
8796                                            CandidateTypes, CandidateSet);
8797 
8798   // Dispatch over the operation to add in only those overloads which apply.
8799   switch (Op) {
8800   case OO_None:
8801   case NUM_OVERLOADED_OPERATORS:
8802     llvm_unreachable("Expected an overloaded operator");
8803 
8804   case OO_New:
8805   case OO_Delete:
8806   case OO_Array_New:
8807   case OO_Array_Delete:
8808   case OO_Call:
8809     llvm_unreachable(
8810                     "Special operators don't use AddBuiltinOperatorCandidates");
8811 
8812   case OO_Comma:
8813   case OO_Arrow:
8814   case OO_Coawait:
8815     // C++ [over.match.oper]p3:
8816     //   -- For the operator ',', the unary operator '&', the
8817     //      operator '->', or the operator 'co_await', the
8818     //      built-in candidates set is empty.
8819     break;
8820 
8821   case OO_Plus: // '+' is either unary or binary
8822     if (Args.size() == 1)
8823       OpBuilder.addUnaryPlusPointerOverloads();
8824     LLVM_FALLTHROUGH;
8825 
8826   case OO_Minus: // '-' is either unary or binary
8827     if (Args.size() == 1) {
8828       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8829     } else {
8830       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8831       OpBuilder.addGenericBinaryArithmeticOverloads();
8832     }
8833     break;
8834 
8835   case OO_Star: // '*' is either unary or binary
8836     if (Args.size() == 1)
8837       OpBuilder.addUnaryStarPointerOverloads();
8838     else
8839       OpBuilder.addGenericBinaryArithmeticOverloads();
8840     break;
8841 
8842   case OO_Slash:
8843     OpBuilder.addGenericBinaryArithmeticOverloads();
8844     break;
8845 
8846   case OO_PlusPlus:
8847   case OO_MinusMinus:
8848     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8849     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8850     break;
8851 
8852   case OO_EqualEqual:
8853   case OO_ExclaimEqual:
8854     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8855     LLVM_FALLTHROUGH;
8856 
8857   case OO_Less:
8858   case OO_Greater:
8859   case OO_LessEqual:
8860   case OO_GreaterEqual:
8861     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8862     OpBuilder.addGenericBinaryArithmeticOverloads();
8863     break;
8864 
8865   case OO_Spaceship:
8866     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8867     OpBuilder.addThreeWayArithmeticOverloads();
8868     break;
8869 
8870   case OO_Percent:
8871   case OO_Caret:
8872   case OO_Pipe:
8873   case OO_LessLess:
8874   case OO_GreaterGreater:
8875     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8876     break;
8877 
8878   case OO_Amp: // '&' is either unary or binary
8879     if (Args.size() == 1)
8880       // C++ [over.match.oper]p3:
8881       //   -- For the operator ',', the unary operator '&', or the
8882       //      operator '->', the built-in candidates set is empty.
8883       break;
8884 
8885     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8886     break;
8887 
8888   case OO_Tilde:
8889     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8890     break;
8891 
8892   case OO_Equal:
8893     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8894     LLVM_FALLTHROUGH;
8895 
8896   case OO_PlusEqual:
8897   case OO_MinusEqual:
8898     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8899     LLVM_FALLTHROUGH;
8900 
8901   case OO_StarEqual:
8902   case OO_SlashEqual:
8903     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8904     break;
8905 
8906   case OO_PercentEqual:
8907   case OO_LessLessEqual:
8908   case OO_GreaterGreaterEqual:
8909   case OO_AmpEqual:
8910   case OO_CaretEqual:
8911   case OO_PipeEqual:
8912     OpBuilder.addAssignmentIntegralOverloads();
8913     break;
8914 
8915   case OO_Exclaim:
8916     OpBuilder.addExclaimOverload();
8917     break;
8918 
8919   case OO_AmpAmp:
8920   case OO_PipePipe:
8921     OpBuilder.addAmpAmpOrPipePipeOverload();
8922     break;
8923 
8924   case OO_Subscript:
8925     OpBuilder.addSubscriptOverloads();
8926     break;
8927 
8928   case OO_ArrowStar:
8929     OpBuilder.addArrowStarOverloads();
8930     break;
8931 
8932   case OO_Conditional:
8933     OpBuilder.addConditionalOperatorOverloads();
8934     OpBuilder.addGenericBinaryArithmeticOverloads();
8935     break;
8936   }
8937 }
8938 
8939 /// Add function candidates found via argument-dependent lookup
8940 /// to the set of overloading candidates.
8941 ///
8942 /// This routine performs argument-dependent name lookup based on the
8943 /// given function name (which may also be an operator name) and adds
8944 /// all of the overload candidates found by ADL to the overload
8945 /// candidate set (C++ [basic.lookup.argdep]).
8946 void
8947 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8948                                            SourceLocation Loc,
8949                                            ArrayRef<Expr *> Args,
8950                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8951                                            OverloadCandidateSet& CandidateSet,
8952                                            bool PartialOverloading) {
8953   ADLResult Fns;
8954 
8955   // FIXME: This approach for uniquing ADL results (and removing
8956   // redundant candidates from the set) relies on pointer-equality,
8957   // which means we need to key off the canonical decl.  However,
8958   // always going back to the canonical decl might not get us the
8959   // right set of default arguments.  What default arguments are
8960   // we supposed to consider on ADL candidates, anyway?
8961 
8962   // FIXME: Pass in the explicit template arguments?
8963   ArgumentDependentLookup(Name, Loc, Args, Fns);
8964 
8965   // Erase all of the candidates we already knew about.
8966   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8967                                    CandEnd = CandidateSet.end();
8968        Cand != CandEnd; ++Cand)
8969     if (Cand->Function) {
8970       Fns.erase(Cand->Function);
8971       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8972         Fns.erase(FunTmpl);
8973     }
8974 
8975   // For each of the ADL candidates we found, add it to the overload
8976   // set.
8977   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8978     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8979 
8980     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8981       if (ExplicitTemplateArgs)
8982         continue;
8983 
8984       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8985                            /*SupressUserConversions=*/false, PartialOverloading,
8986                            /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8987     } else {
8988       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8989                                    ExplicitTemplateArgs, Args, CandidateSet,
8990                                    /*SupressUserConversions=*/false,
8991                                    PartialOverloading, ADLCallKind::UsesADL);
8992     }
8993   }
8994 }
8995 
8996 namespace {
8997 enum class Comparison { Equal, Better, Worse };
8998 }
8999 
9000 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9001 /// overload resolution.
9002 ///
9003 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9004 /// Cand1's first N enable_if attributes have precisely the same conditions as
9005 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9006 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9007 ///
9008 /// Note that you can have a pair of candidates such that Cand1's enable_if
9009 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9010 /// worse than Cand1's.
9011 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9012                                        const FunctionDecl *Cand2) {
9013   // Common case: One (or both) decls don't have enable_if attrs.
9014   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9015   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9016   if (!Cand1Attr || !Cand2Attr) {
9017     if (Cand1Attr == Cand2Attr)
9018       return Comparison::Equal;
9019     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9020   }
9021 
9022   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9023   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9024 
9025   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9026   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9027     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9028     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9029 
9030     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9031     // has fewer enable_if attributes than Cand2, and vice versa.
9032     if (!Cand1A)
9033       return Comparison::Worse;
9034     if (!Cand2A)
9035       return Comparison::Better;
9036 
9037     Cand1ID.clear();
9038     Cand2ID.clear();
9039 
9040     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9041     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9042     if (Cand1ID != Cand2ID)
9043       return Comparison::Worse;
9044   }
9045 
9046   return Comparison::Equal;
9047 }
9048 
9049 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9050                                           const OverloadCandidate &Cand2) {
9051   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9052       !Cand2.Function->isMultiVersion())
9053     return false;
9054 
9055   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9056   // is obviously better.
9057   if (Cand1.Function->isInvalidDecl()) return false;
9058   if (Cand2.Function->isInvalidDecl()) return true;
9059 
9060   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9061   // cpu_dispatch, else arbitrarily based on the identifiers.
9062   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9063   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9064   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9065   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9066 
9067   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9068     return false;
9069 
9070   if (Cand1CPUDisp && !Cand2CPUDisp)
9071     return true;
9072   if (Cand2CPUDisp && !Cand1CPUDisp)
9073     return false;
9074 
9075   if (Cand1CPUSpec && Cand2CPUSpec) {
9076     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9077       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9078 
9079     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9080         FirstDiff = std::mismatch(
9081             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9082             Cand2CPUSpec->cpus_begin(),
9083             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9084               return LHS->getName() == RHS->getName();
9085             });
9086 
9087     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9088            "Two different cpu-specific versions should not have the same "
9089            "identifier list, otherwise they'd be the same decl!");
9090     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9091   }
9092   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9093 }
9094 
9095 /// isBetterOverloadCandidate - Determines whether the first overload
9096 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9097 bool clang::isBetterOverloadCandidate(
9098     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9099     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9100   // Define viable functions to be better candidates than non-viable
9101   // functions.
9102   if (!Cand2.Viable)
9103     return Cand1.Viable;
9104   else if (!Cand1.Viable)
9105     return false;
9106 
9107   // C++ [over.match.best]p1:
9108   //
9109   //   -- if F is a static member function, ICS1(F) is defined such
9110   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9111   //      any function G, and, symmetrically, ICS1(G) is neither
9112   //      better nor worse than ICS1(F).
9113   unsigned StartArg = 0;
9114   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9115     StartArg = 1;
9116 
9117   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9118     // We don't allow incompatible pointer conversions in C++.
9119     if (!S.getLangOpts().CPlusPlus)
9120       return ICS.isStandard() &&
9121              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9122 
9123     // The only ill-formed conversion we allow in C++ is the string literal to
9124     // char* conversion, which is only considered ill-formed after C++11.
9125     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9126            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9127   };
9128 
9129   // Define functions that don't require ill-formed conversions for a given
9130   // argument to be better candidates than functions that do.
9131   unsigned NumArgs = Cand1.Conversions.size();
9132   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9133   bool HasBetterConversion = false;
9134   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9135     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9136     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9137     if (Cand1Bad != Cand2Bad) {
9138       if (Cand1Bad)
9139         return false;
9140       HasBetterConversion = true;
9141     }
9142   }
9143 
9144   if (HasBetterConversion)
9145     return true;
9146 
9147   // C++ [over.match.best]p1:
9148   //   A viable function F1 is defined to be a better function than another
9149   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9150   //   conversion sequence than ICSi(F2), and then...
9151   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9152     switch (CompareImplicitConversionSequences(S, Loc,
9153                                                Cand1.Conversions[ArgIdx],
9154                                                Cand2.Conversions[ArgIdx])) {
9155     case ImplicitConversionSequence::Better:
9156       // Cand1 has a better conversion sequence.
9157       HasBetterConversion = true;
9158       break;
9159 
9160     case ImplicitConversionSequence::Worse:
9161       // Cand1 can't be better than Cand2.
9162       return false;
9163 
9164     case ImplicitConversionSequence::Indistinguishable:
9165       // Do nothing.
9166       break;
9167     }
9168   }
9169 
9170   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9171   //       ICSj(F2), or, if not that,
9172   if (HasBetterConversion)
9173     return true;
9174 
9175   //   -- the context is an initialization by user-defined conversion
9176   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9177   //      from the return type of F1 to the destination type (i.e.,
9178   //      the type of the entity being initialized) is a better
9179   //      conversion sequence than the standard conversion sequence
9180   //      from the return type of F2 to the destination type.
9181   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9182       Cand1.Function && Cand2.Function &&
9183       isa<CXXConversionDecl>(Cand1.Function) &&
9184       isa<CXXConversionDecl>(Cand2.Function)) {
9185     // First check whether we prefer one of the conversion functions over the
9186     // other. This only distinguishes the results in non-standard, extension
9187     // cases such as the conversion from a lambda closure type to a function
9188     // pointer or block.
9189     ImplicitConversionSequence::CompareKind Result =
9190         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9191     if (Result == ImplicitConversionSequence::Indistinguishable)
9192       Result = CompareStandardConversionSequences(S, Loc,
9193                                                   Cand1.FinalConversion,
9194                                                   Cand2.FinalConversion);
9195 
9196     if (Result != ImplicitConversionSequence::Indistinguishable)
9197       return Result == ImplicitConversionSequence::Better;
9198 
9199     // FIXME: Compare kind of reference binding if conversion functions
9200     // convert to a reference type used in direct reference binding, per
9201     // C++14 [over.match.best]p1 section 2 bullet 3.
9202   }
9203 
9204   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9205   // as combined with the resolution to CWG issue 243.
9206   //
9207   // When the context is initialization by constructor ([over.match.ctor] or
9208   // either phase of [over.match.list]), a constructor is preferred over
9209   // a conversion function.
9210   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9211       Cand1.Function && Cand2.Function &&
9212       isa<CXXConstructorDecl>(Cand1.Function) !=
9213           isa<CXXConstructorDecl>(Cand2.Function))
9214     return isa<CXXConstructorDecl>(Cand1.Function);
9215 
9216   //    -- F1 is a non-template function and F2 is a function template
9217   //       specialization, or, if not that,
9218   bool Cand1IsSpecialization = Cand1.Function &&
9219                                Cand1.Function->getPrimaryTemplate();
9220   bool Cand2IsSpecialization = Cand2.Function &&
9221                                Cand2.Function->getPrimaryTemplate();
9222   if (Cand1IsSpecialization != Cand2IsSpecialization)
9223     return Cand2IsSpecialization;
9224 
9225   //   -- F1 and F2 are function template specializations, and the function
9226   //      template for F1 is more specialized than the template for F2
9227   //      according to the partial ordering rules described in 14.5.5.2, or,
9228   //      if not that,
9229   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9230     if (FunctionTemplateDecl *BetterTemplate
9231           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9232                                          Cand2.Function->getPrimaryTemplate(),
9233                                          Loc,
9234                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9235                                                              : TPOC_Call,
9236                                          Cand1.ExplicitCallArguments,
9237                                          Cand2.ExplicitCallArguments))
9238       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9239   }
9240 
9241   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9242   // A derived-class constructor beats an (inherited) base class constructor.
9243   bool Cand1IsInherited =
9244       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9245   bool Cand2IsInherited =
9246       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9247   if (Cand1IsInherited != Cand2IsInherited)
9248     return Cand2IsInherited;
9249   else if (Cand1IsInherited) {
9250     assert(Cand2IsInherited);
9251     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9252     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9253     if (Cand1Class->isDerivedFrom(Cand2Class))
9254       return true;
9255     if (Cand2Class->isDerivedFrom(Cand1Class))
9256       return false;
9257     // Inherited from sibling base classes: still ambiguous.
9258   }
9259 
9260   // Check C++17 tie-breakers for deduction guides.
9261   {
9262     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9263     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9264     if (Guide1 && Guide2) {
9265       //  -- F1 is generated from a deduction-guide and F2 is not
9266       if (Guide1->isImplicit() != Guide2->isImplicit())
9267         return Guide2->isImplicit();
9268 
9269       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9270       if (Guide1->isCopyDeductionCandidate())
9271         return true;
9272     }
9273   }
9274 
9275   // Check for enable_if value-based overload resolution.
9276   if (Cand1.Function && Cand2.Function) {
9277     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9278     if (Cmp != Comparison::Equal)
9279       return Cmp == Comparison::Better;
9280   }
9281 
9282   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9283     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9284     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9285            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9286   }
9287 
9288   bool HasPS1 = Cand1.Function != nullptr &&
9289                 functionHasPassObjectSizeParams(Cand1.Function);
9290   bool HasPS2 = Cand2.Function != nullptr &&
9291                 functionHasPassObjectSizeParams(Cand2.Function);
9292   if (HasPS1 != HasPS2 && HasPS1)
9293     return true;
9294 
9295   return isBetterMultiversionCandidate(Cand1, Cand2);
9296 }
9297 
9298 /// Determine whether two declarations are "equivalent" for the purposes of
9299 /// name lookup and overload resolution. This applies when the same internal/no
9300 /// linkage entity is defined by two modules (probably by textually including
9301 /// the same header). In such a case, we don't consider the declarations to
9302 /// declare the same entity, but we also don't want lookups with both
9303 /// declarations visible to be ambiguous in some cases (this happens when using
9304 /// a modularized libstdc++).
9305 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9306                                                   const NamedDecl *B) {
9307   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9308   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9309   if (!VA || !VB)
9310     return false;
9311 
9312   // The declarations must be declaring the same name as an internal linkage
9313   // entity in different modules.
9314   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9315           VB->getDeclContext()->getRedeclContext()) ||
9316       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9317           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9318       VA->isExternallyVisible() || VB->isExternallyVisible())
9319     return false;
9320 
9321   // Check that the declarations appear to be equivalent.
9322   //
9323   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9324   // For constants and functions, we should check the initializer or body is
9325   // the same. For non-constant variables, we shouldn't allow it at all.
9326   if (Context.hasSameType(VA->getType(), VB->getType()))
9327     return true;
9328 
9329   // Enum constants within unnamed enumerations will have different types, but
9330   // may still be similar enough to be interchangeable for our purposes.
9331   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9332     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9333       // Only handle anonymous enums. If the enumerations were named and
9334       // equivalent, they would have been merged to the same type.
9335       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9336       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9337       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9338           !Context.hasSameType(EnumA->getIntegerType(),
9339                                EnumB->getIntegerType()))
9340         return false;
9341       // Allow this only if the value is the same for both enumerators.
9342       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9343     }
9344   }
9345 
9346   // Nothing else is sufficiently similar.
9347   return false;
9348 }
9349 
9350 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9351     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9352   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9353 
9354   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9355   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9356       << !M << (M ? M->getFullModuleName() : "");
9357 
9358   for (auto *E : Equiv) {
9359     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9360     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9361         << !M << (M ? M->getFullModuleName() : "");
9362   }
9363 }
9364 
9365 /// Computes the best viable function (C++ 13.3.3)
9366 /// within an overload candidate set.
9367 ///
9368 /// \param Loc The location of the function name (or operator symbol) for
9369 /// which overload resolution occurs.
9370 ///
9371 /// \param Best If overload resolution was successful or found a deleted
9372 /// function, \p Best points to the candidate function found.
9373 ///
9374 /// \returns The result of overload resolution.
9375 OverloadingResult
9376 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9377                                          iterator &Best) {
9378   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9379   std::transform(begin(), end(), std::back_inserter(Candidates),
9380                  [](OverloadCandidate &Cand) { return &Cand; });
9381 
9382   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9383   // are accepted by both clang and NVCC. However, during a particular
9384   // compilation mode only one call variant is viable. We need to
9385   // exclude non-viable overload candidates from consideration based
9386   // only on their host/device attributes. Specifically, if one
9387   // candidate call is WrongSide and the other is SameSide, we ignore
9388   // the WrongSide candidate.
9389   if (S.getLangOpts().CUDA) {
9390     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9391     bool ContainsSameSideCandidate =
9392         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9393           return Cand->Function &&
9394                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9395                      Sema::CFP_SameSide;
9396         });
9397     if (ContainsSameSideCandidate) {
9398       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9399         return Cand->Function &&
9400                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9401                    Sema::CFP_WrongSide;
9402       };
9403       llvm::erase_if(Candidates, IsWrongSideCandidate);
9404     }
9405   }
9406 
9407   // Find the best viable function.
9408   Best = end();
9409   for (auto *Cand : Candidates)
9410     if (Cand->Viable)
9411       if (Best == end() ||
9412           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9413         Best = Cand;
9414 
9415   // If we didn't find any viable functions, abort.
9416   if (Best == end())
9417     return OR_No_Viable_Function;
9418 
9419   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9420 
9421   // Make sure that this function is better than every other viable
9422   // function. If not, we have an ambiguity.
9423   for (auto *Cand : Candidates) {
9424     if (Cand->Viable && Cand != Best &&
9425         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9426       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9427                                                    Cand->Function)) {
9428         EquivalentCands.push_back(Cand->Function);
9429         continue;
9430       }
9431 
9432       Best = end();
9433       return OR_Ambiguous;
9434     }
9435   }
9436 
9437   // Best is the best viable function.
9438   if (Best->Function && Best->Function->isDeleted())
9439     return OR_Deleted;
9440 
9441   if (!EquivalentCands.empty())
9442     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9443                                                     EquivalentCands);
9444 
9445   return OR_Success;
9446 }
9447 
9448 namespace {
9449 
9450 enum OverloadCandidateKind {
9451   oc_function,
9452   oc_method,
9453   oc_constructor,
9454   oc_implicit_default_constructor,
9455   oc_implicit_copy_constructor,
9456   oc_implicit_move_constructor,
9457   oc_implicit_copy_assignment,
9458   oc_implicit_move_assignment,
9459   oc_inherited_constructor
9460 };
9461 
9462 enum OverloadCandidateSelect {
9463   ocs_non_template,
9464   ocs_template,
9465   ocs_described_template,
9466 };
9467 
9468 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9469 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9470                           std::string &Description) {
9471 
9472   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9473   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9474     isTemplate = true;
9475     Description = S.getTemplateArgumentBindingsText(
9476         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9477   }
9478 
9479   OverloadCandidateSelect Select = [&]() {
9480     if (!Description.empty())
9481       return ocs_described_template;
9482     return isTemplate ? ocs_template : ocs_non_template;
9483   }();
9484 
9485   OverloadCandidateKind Kind = [&]() {
9486     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9487       if (!Ctor->isImplicit()) {
9488         if (isa<ConstructorUsingShadowDecl>(Found))
9489           return oc_inherited_constructor;
9490         else
9491           return oc_constructor;
9492       }
9493 
9494       if (Ctor->isDefaultConstructor())
9495         return oc_implicit_default_constructor;
9496 
9497       if (Ctor->isMoveConstructor())
9498         return oc_implicit_move_constructor;
9499 
9500       assert(Ctor->isCopyConstructor() &&
9501              "unexpected sort of implicit constructor");
9502       return oc_implicit_copy_constructor;
9503     }
9504 
9505     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9506       // This actually gets spelled 'candidate function' for now, but
9507       // it doesn't hurt to split it out.
9508       if (!Meth->isImplicit())
9509         return oc_method;
9510 
9511       if (Meth->isMoveAssignmentOperator())
9512         return oc_implicit_move_assignment;
9513 
9514       if (Meth->isCopyAssignmentOperator())
9515         return oc_implicit_copy_assignment;
9516 
9517       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9518       return oc_method;
9519     }
9520 
9521     return oc_function;
9522   }();
9523 
9524   return std::make_pair(Kind, Select);
9525 }
9526 
9527 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9528   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9529   // set.
9530   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9531     S.Diag(FoundDecl->getLocation(),
9532            diag::note_ovl_candidate_inherited_constructor)
9533       << Shadow->getNominatedBaseClass();
9534 }
9535 
9536 } // end anonymous namespace
9537 
9538 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9539                                     const FunctionDecl *FD) {
9540   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9541     bool AlwaysTrue;
9542     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9543       return false;
9544     if (!AlwaysTrue)
9545       return false;
9546   }
9547   return true;
9548 }
9549 
9550 /// Returns true if we can take the address of the function.
9551 ///
9552 /// \param Complain - If true, we'll emit a diagnostic
9553 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9554 ///   we in overload resolution?
9555 /// \param Loc - The location of the statement we're complaining about. Ignored
9556 ///   if we're not complaining, or if we're in overload resolution.
9557 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9558                                               bool Complain,
9559                                               bool InOverloadResolution,
9560                                               SourceLocation Loc) {
9561   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9562     if (Complain) {
9563       if (InOverloadResolution)
9564         S.Diag(FD->getBeginLoc(),
9565                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9566       else
9567         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9568     }
9569     return false;
9570   }
9571 
9572   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9573     return P->hasAttr<PassObjectSizeAttr>();
9574   });
9575   if (I == FD->param_end())
9576     return true;
9577 
9578   if (Complain) {
9579     // Add one to ParamNo because it's user-facing
9580     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9581     if (InOverloadResolution)
9582       S.Diag(FD->getLocation(),
9583              diag::note_ovl_candidate_has_pass_object_size_params)
9584           << ParamNo;
9585     else
9586       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9587           << FD << ParamNo;
9588   }
9589   return false;
9590 }
9591 
9592 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9593                                                const FunctionDecl *FD) {
9594   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9595                                            /*InOverloadResolution=*/true,
9596                                            /*Loc=*/SourceLocation());
9597 }
9598 
9599 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9600                                              bool Complain,
9601                                              SourceLocation Loc) {
9602   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9603                                              /*InOverloadResolution=*/false,
9604                                              Loc);
9605 }
9606 
9607 // Notes the location of an overload candidate.
9608 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9609                                  QualType DestType, bool TakingAddress) {
9610   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9611     return;
9612   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9613       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9614     return;
9615 
9616   std::string FnDesc;
9617   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9618       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9619   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9620                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9621                          << Fn << FnDesc;
9622 
9623   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9624   Diag(Fn->getLocation(), PD);
9625   MaybeEmitInheritedConstructorNote(*this, Found);
9626 }
9627 
9628 // Notes the location of all overload candidates designated through
9629 // OverloadedExpr
9630 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9631                                      bool TakingAddress) {
9632   assert(OverloadedExpr->getType() == Context.OverloadTy);
9633 
9634   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9635   OverloadExpr *OvlExpr = Ovl.Expression;
9636 
9637   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9638                             IEnd = OvlExpr->decls_end();
9639        I != IEnd; ++I) {
9640     if (FunctionTemplateDecl *FunTmpl =
9641                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9642       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9643                             TakingAddress);
9644     } else if (FunctionDecl *Fun
9645                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9646       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9647     }
9648   }
9649 }
9650 
9651 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9652 /// "lead" diagnostic; it will be given two arguments, the source and
9653 /// target types of the conversion.
9654 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9655                                  Sema &S,
9656                                  SourceLocation CaretLoc,
9657                                  const PartialDiagnostic &PDiag) const {
9658   S.Diag(CaretLoc, PDiag)
9659     << Ambiguous.getFromType() << Ambiguous.getToType();
9660   // FIXME: The note limiting machinery is borrowed from
9661   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9662   // refactoring here.
9663   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9664   unsigned CandsShown = 0;
9665   AmbiguousConversionSequence::const_iterator I, E;
9666   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9667     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9668       break;
9669     ++CandsShown;
9670     S.NoteOverloadCandidate(I->first, I->second);
9671   }
9672   if (I != E)
9673     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9674 }
9675 
9676 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9677                                   unsigned I, bool TakingCandidateAddress) {
9678   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9679   assert(Conv.isBad());
9680   assert(Cand->Function && "for now, candidate must be a function");
9681   FunctionDecl *Fn = Cand->Function;
9682 
9683   // There's a conversion slot for the object argument if this is a
9684   // non-constructor method.  Note that 'I' corresponds the
9685   // conversion-slot index.
9686   bool isObjectArgument = false;
9687   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9688     if (I == 0)
9689       isObjectArgument = true;
9690     else
9691       I--;
9692   }
9693 
9694   std::string FnDesc;
9695   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9696       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9697 
9698   Expr *FromExpr = Conv.Bad.FromExpr;
9699   QualType FromTy = Conv.Bad.getFromType();
9700   QualType ToTy = Conv.Bad.getToType();
9701 
9702   if (FromTy == S.Context.OverloadTy) {
9703     assert(FromExpr && "overload set argument came from implicit argument?");
9704     Expr *E = FromExpr->IgnoreParens();
9705     if (isa<UnaryOperator>(E))
9706       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9707     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9708 
9709     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9710         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9711         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9712         << Name << I + 1;
9713     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9714     return;
9715   }
9716 
9717   // Do some hand-waving analysis to see if the non-viability is due
9718   // to a qualifier mismatch.
9719   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9720   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9721   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9722     CToTy = RT->getPointeeType();
9723   else {
9724     // TODO: detect and diagnose the full richness of const mismatches.
9725     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9726       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9727         CFromTy = FromPT->getPointeeType();
9728         CToTy = ToPT->getPointeeType();
9729       }
9730   }
9731 
9732   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9733       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9734     Qualifiers FromQs = CFromTy.getQualifiers();
9735     Qualifiers ToQs = CToTy.getQualifiers();
9736 
9737     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9738       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9739           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9740           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9741           << ToTy << (unsigned)isObjectArgument << I + 1;
9742       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9743       return;
9744     }
9745 
9746     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9747       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9748           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9749           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9750           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9751           << (unsigned)isObjectArgument << I + 1;
9752       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9753       return;
9754     }
9755 
9756     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9757       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9758           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9759           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9760           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9761           << (unsigned)isObjectArgument << I + 1;
9762       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9763       return;
9764     }
9765 
9766     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9767       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9768           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9769           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9770           << FromQs.hasUnaligned() << I + 1;
9771       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9772       return;
9773     }
9774 
9775     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9776     assert(CVR && "unexpected qualifiers mismatch");
9777 
9778     if (isObjectArgument) {
9779       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9780           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9781           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9782           << (CVR - 1);
9783     } else {
9784       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9785           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9786           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9787           << (CVR - 1) << I + 1;
9788     }
9789     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9790     return;
9791   }
9792 
9793   // Special diagnostic for failure to convert an initializer list, since
9794   // telling the user that it has type void is not useful.
9795   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9796     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9797         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9798         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9799         << ToTy << (unsigned)isObjectArgument << I + 1;
9800     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9801     return;
9802   }
9803 
9804   // Diagnose references or pointers to incomplete types differently,
9805   // since it's far from impossible that the incompleteness triggered
9806   // the failure.
9807   QualType TempFromTy = FromTy.getNonReferenceType();
9808   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9809     TempFromTy = PTy->getPointeeType();
9810   if (TempFromTy->isIncompleteType()) {
9811     // Emit the generic diagnostic and, optionally, add the hints to it.
9812     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9813         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9814         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9815         << ToTy << (unsigned)isObjectArgument << I + 1
9816         << (unsigned)(Cand->Fix.Kind);
9817 
9818     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9819     return;
9820   }
9821 
9822   // Diagnose base -> derived pointer conversions.
9823   unsigned BaseToDerivedConversion = 0;
9824   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9825     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9826       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9827                                                FromPtrTy->getPointeeType()) &&
9828           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9829           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9830           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9831                           FromPtrTy->getPointeeType()))
9832         BaseToDerivedConversion = 1;
9833     }
9834   } else if (const ObjCObjectPointerType *FromPtrTy
9835                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9836     if (const ObjCObjectPointerType *ToPtrTy
9837                                         = ToTy->getAs<ObjCObjectPointerType>())
9838       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9839         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9840           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9841                                                 FromPtrTy->getPointeeType()) &&
9842               FromIface->isSuperClassOf(ToIface))
9843             BaseToDerivedConversion = 2;
9844   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9845     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9846         !FromTy->isIncompleteType() &&
9847         !ToRefTy->getPointeeType()->isIncompleteType() &&
9848         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9849       BaseToDerivedConversion = 3;
9850     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9851                ToTy.getNonReferenceType().getCanonicalType() ==
9852                FromTy.getNonReferenceType().getCanonicalType()) {
9853       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9854           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9855           << (unsigned)isObjectArgument << I + 1
9856           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9857       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9858       return;
9859     }
9860   }
9861 
9862   if (BaseToDerivedConversion) {
9863     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9864         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9865         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9866         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9867     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9868     return;
9869   }
9870 
9871   if (isa<ObjCObjectPointerType>(CFromTy) &&
9872       isa<PointerType>(CToTy)) {
9873       Qualifiers FromQs = CFromTy.getQualifiers();
9874       Qualifiers ToQs = CToTy.getQualifiers();
9875       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9876         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9877             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9878             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9879             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9880         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9881         return;
9882       }
9883   }
9884 
9885   if (TakingCandidateAddress &&
9886       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9887     return;
9888 
9889   // Emit the generic diagnostic and, optionally, add the hints to it.
9890   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9891   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9892         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9893         << ToTy << (unsigned)isObjectArgument << I + 1
9894         << (unsigned)(Cand->Fix.Kind);
9895 
9896   // If we can fix the conversion, suggest the FixIts.
9897   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9898        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9899     FDiag << *HI;
9900   S.Diag(Fn->getLocation(), FDiag);
9901 
9902   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9903 }
9904 
9905 /// Additional arity mismatch diagnosis specific to a function overload
9906 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9907 /// over a candidate in any candidate set.
9908 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9909                                unsigned NumArgs) {
9910   FunctionDecl *Fn = Cand->Function;
9911   unsigned MinParams = Fn->getMinRequiredArguments();
9912 
9913   // With invalid overloaded operators, it's possible that we think we
9914   // have an arity mismatch when in fact it looks like we have the
9915   // right number of arguments, because only overloaded operators have
9916   // the weird behavior of overloading member and non-member functions.
9917   // Just don't report anything.
9918   if (Fn->isInvalidDecl() &&
9919       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9920     return true;
9921 
9922   if (NumArgs < MinParams) {
9923     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9924            (Cand->FailureKind == ovl_fail_bad_deduction &&
9925             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9926   } else {
9927     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9928            (Cand->FailureKind == ovl_fail_bad_deduction &&
9929             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9930   }
9931 
9932   return false;
9933 }
9934 
9935 /// General arity mismatch diagnosis over a candidate in a candidate set.
9936 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9937                                   unsigned NumFormalArgs) {
9938   assert(isa<FunctionDecl>(D) &&
9939       "The templated declaration should at least be a function"
9940       " when diagnosing bad template argument deduction due to too many"
9941       " or too few arguments");
9942 
9943   FunctionDecl *Fn = cast<FunctionDecl>(D);
9944 
9945   // TODO: treat calls to a missing default constructor as a special case
9946   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9947   unsigned MinParams = Fn->getMinRequiredArguments();
9948 
9949   // at least / at most / exactly
9950   unsigned mode, modeCount;
9951   if (NumFormalArgs < MinParams) {
9952     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9953         FnTy->isTemplateVariadic())
9954       mode = 0; // "at least"
9955     else
9956       mode = 2; // "exactly"
9957     modeCount = MinParams;
9958   } else {
9959     if (MinParams != FnTy->getNumParams())
9960       mode = 1; // "at most"
9961     else
9962       mode = 2; // "exactly"
9963     modeCount = FnTy->getNumParams();
9964   }
9965 
9966   std::string Description;
9967   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9968       ClassifyOverloadCandidate(S, Found, Fn, Description);
9969 
9970   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9971     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9972         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9973         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9974   else
9975     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9976         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9977         << Description << mode << modeCount << NumFormalArgs;
9978 
9979   MaybeEmitInheritedConstructorNote(S, Found);
9980 }
9981 
9982 /// Arity mismatch diagnosis specific to a function overload candidate.
9983 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9984                                   unsigned NumFormalArgs) {
9985   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9986     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9987 }
9988 
9989 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9990   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9991     return TD;
9992   llvm_unreachable("Unsupported: Getting the described template declaration"
9993                    " for bad deduction diagnosis");
9994 }
9995 
9996 /// Diagnose a failed template-argument deduction.
9997 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9998                                  DeductionFailureInfo &DeductionFailure,
9999                                  unsigned NumArgs,
10000                                  bool TakingCandidateAddress) {
10001   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10002   NamedDecl *ParamD;
10003   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10004   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10005   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10006   switch (DeductionFailure.Result) {
10007   case Sema::TDK_Success:
10008     llvm_unreachable("TDK_success while diagnosing bad deduction");
10009 
10010   case Sema::TDK_Incomplete: {
10011     assert(ParamD && "no parameter found for incomplete deduction result");
10012     S.Diag(Templated->getLocation(),
10013            diag::note_ovl_candidate_incomplete_deduction)
10014         << ParamD->getDeclName();
10015     MaybeEmitInheritedConstructorNote(S, Found);
10016     return;
10017   }
10018 
10019   case Sema::TDK_IncompletePack: {
10020     assert(ParamD && "no parameter found for incomplete deduction result");
10021     S.Diag(Templated->getLocation(),
10022            diag::note_ovl_candidate_incomplete_deduction_pack)
10023         << ParamD->getDeclName()
10024         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10025         << *DeductionFailure.getFirstArg();
10026     MaybeEmitInheritedConstructorNote(S, Found);
10027     return;
10028   }
10029 
10030   case Sema::TDK_Underqualified: {
10031     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10032     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10033 
10034     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10035 
10036     // Param will have been canonicalized, but it should just be a
10037     // qualified version of ParamD, so move the qualifiers to that.
10038     QualifierCollector Qs;
10039     Qs.strip(Param);
10040     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10041     assert(S.Context.hasSameType(Param, NonCanonParam));
10042 
10043     // Arg has also been canonicalized, but there's nothing we can do
10044     // about that.  It also doesn't matter as much, because it won't
10045     // have any template parameters in it (because deduction isn't
10046     // done on dependent types).
10047     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10048 
10049     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10050         << ParamD->getDeclName() << Arg << NonCanonParam;
10051     MaybeEmitInheritedConstructorNote(S, Found);
10052     return;
10053   }
10054 
10055   case Sema::TDK_Inconsistent: {
10056     assert(ParamD && "no parameter found for inconsistent deduction result");
10057     int which = 0;
10058     if (isa<TemplateTypeParmDecl>(ParamD))
10059       which = 0;
10060     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10061       // Deduction might have failed because we deduced arguments of two
10062       // different types for a non-type template parameter.
10063       // FIXME: Use a different TDK value for this.
10064       QualType T1 =
10065           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10066       QualType T2 =
10067           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10068       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10069         S.Diag(Templated->getLocation(),
10070                diag::note_ovl_candidate_inconsistent_deduction_types)
10071           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10072           << *DeductionFailure.getSecondArg() << T2;
10073         MaybeEmitInheritedConstructorNote(S, Found);
10074         return;
10075       }
10076 
10077       which = 1;
10078     } else {
10079       which = 2;
10080     }
10081 
10082     S.Diag(Templated->getLocation(),
10083            diag::note_ovl_candidate_inconsistent_deduction)
10084         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10085         << *DeductionFailure.getSecondArg();
10086     MaybeEmitInheritedConstructorNote(S, Found);
10087     return;
10088   }
10089 
10090   case Sema::TDK_InvalidExplicitArguments:
10091     assert(ParamD && "no parameter found for invalid explicit arguments");
10092     if (ParamD->getDeclName())
10093       S.Diag(Templated->getLocation(),
10094              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10095           << ParamD->getDeclName();
10096     else {
10097       int index = 0;
10098       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10099         index = TTP->getIndex();
10100       else if (NonTypeTemplateParmDecl *NTTP
10101                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10102         index = NTTP->getIndex();
10103       else
10104         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10105       S.Diag(Templated->getLocation(),
10106              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10107           << (index + 1);
10108     }
10109     MaybeEmitInheritedConstructorNote(S, Found);
10110     return;
10111 
10112   case Sema::TDK_TooManyArguments:
10113   case Sema::TDK_TooFewArguments:
10114     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10115     return;
10116 
10117   case Sema::TDK_InstantiationDepth:
10118     S.Diag(Templated->getLocation(),
10119            diag::note_ovl_candidate_instantiation_depth);
10120     MaybeEmitInheritedConstructorNote(S, Found);
10121     return;
10122 
10123   case Sema::TDK_SubstitutionFailure: {
10124     // Format the template argument list into the argument string.
10125     SmallString<128> TemplateArgString;
10126     if (TemplateArgumentList *Args =
10127             DeductionFailure.getTemplateArgumentList()) {
10128       TemplateArgString = " ";
10129       TemplateArgString += S.getTemplateArgumentBindingsText(
10130           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10131     }
10132 
10133     // If this candidate was disabled by enable_if, say so.
10134     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10135     if (PDiag && PDiag->second.getDiagID() ==
10136           diag::err_typename_nested_not_found_enable_if) {
10137       // FIXME: Use the source range of the condition, and the fully-qualified
10138       //        name of the enable_if template. These are both present in PDiag.
10139       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10140         << "'enable_if'" << TemplateArgString;
10141       return;
10142     }
10143 
10144     // We found a specific requirement that disabled the enable_if.
10145     if (PDiag && PDiag->second.getDiagID() ==
10146         diag::err_typename_nested_not_found_requirement) {
10147       S.Diag(Templated->getLocation(),
10148              diag::note_ovl_candidate_disabled_by_requirement)
10149         << PDiag->second.getStringArg(0) << TemplateArgString;
10150       return;
10151     }
10152 
10153     // Format the SFINAE diagnostic into the argument string.
10154     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10155     //        formatted message in another diagnostic.
10156     SmallString<128> SFINAEArgString;
10157     SourceRange R;
10158     if (PDiag) {
10159       SFINAEArgString = ": ";
10160       R = SourceRange(PDiag->first, PDiag->first);
10161       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10162     }
10163 
10164     S.Diag(Templated->getLocation(),
10165            diag::note_ovl_candidate_substitution_failure)
10166         << TemplateArgString << SFINAEArgString << R;
10167     MaybeEmitInheritedConstructorNote(S, Found);
10168     return;
10169   }
10170 
10171   case Sema::TDK_DeducedMismatch:
10172   case Sema::TDK_DeducedMismatchNested: {
10173     // Format the template argument list into the argument string.
10174     SmallString<128> TemplateArgString;
10175     if (TemplateArgumentList *Args =
10176             DeductionFailure.getTemplateArgumentList()) {
10177       TemplateArgString = " ";
10178       TemplateArgString += S.getTemplateArgumentBindingsText(
10179           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10180     }
10181 
10182     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10183         << (*DeductionFailure.getCallArgIndex() + 1)
10184         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10185         << TemplateArgString
10186         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10187     break;
10188   }
10189 
10190   case Sema::TDK_NonDeducedMismatch: {
10191     // FIXME: Provide a source location to indicate what we couldn't match.
10192     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10193     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10194     if (FirstTA.getKind() == TemplateArgument::Template &&
10195         SecondTA.getKind() == TemplateArgument::Template) {
10196       TemplateName FirstTN = FirstTA.getAsTemplate();
10197       TemplateName SecondTN = SecondTA.getAsTemplate();
10198       if (FirstTN.getKind() == TemplateName::Template &&
10199           SecondTN.getKind() == TemplateName::Template) {
10200         if (FirstTN.getAsTemplateDecl()->getName() ==
10201             SecondTN.getAsTemplateDecl()->getName()) {
10202           // FIXME: This fixes a bad diagnostic where both templates are named
10203           // the same.  This particular case is a bit difficult since:
10204           // 1) It is passed as a string to the diagnostic printer.
10205           // 2) The diagnostic printer only attempts to find a better
10206           //    name for types, not decls.
10207           // Ideally, this should folded into the diagnostic printer.
10208           S.Diag(Templated->getLocation(),
10209                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10210               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10211           return;
10212         }
10213       }
10214     }
10215 
10216     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10217         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10218       return;
10219 
10220     // FIXME: For generic lambda parameters, check if the function is a lambda
10221     // call operator, and if so, emit a prettier and more informative
10222     // diagnostic that mentions 'auto' and lambda in addition to
10223     // (or instead of?) the canonical template type parameters.
10224     S.Diag(Templated->getLocation(),
10225            diag::note_ovl_candidate_non_deduced_mismatch)
10226         << FirstTA << SecondTA;
10227     return;
10228   }
10229   // TODO: diagnose these individually, then kill off
10230   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10231   case Sema::TDK_MiscellaneousDeductionFailure:
10232     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10233     MaybeEmitInheritedConstructorNote(S, Found);
10234     return;
10235   case Sema::TDK_CUDATargetMismatch:
10236     S.Diag(Templated->getLocation(),
10237            diag::note_cuda_ovl_candidate_target_mismatch);
10238     return;
10239   }
10240 }
10241 
10242 /// Diagnose a failed template-argument deduction, for function calls.
10243 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10244                                  unsigned NumArgs,
10245                                  bool TakingCandidateAddress) {
10246   unsigned TDK = Cand->DeductionFailure.Result;
10247   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10248     if (CheckArityMismatch(S, Cand, NumArgs))
10249       return;
10250   }
10251   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10252                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10253 }
10254 
10255 /// CUDA: diagnose an invalid call across targets.
10256 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10257   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10258   FunctionDecl *Callee = Cand->Function;
10259 
10260   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10261                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10262 
10263   std::string FnDesc;
10264   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10265       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10266 
10267   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10268       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10269       << FnDesc /* Ignored */
10270       << CalleeTarget << CallerTarget;
10271 
10272   // This could be an implicit constructor for which we could not infer the
10273   // target due to a collsion. Diagnose that case.
10274   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10275   if (Meth != nullptr && Meth->isImplicit()) {
10276     CXXRecordDecl *ParentClass = Meth->getParent();
10277     Sema::CXXSpecialMember CSM;
10278 
10279     switch (FnKindPair.first) {
10280     default:
10281       return;
10282     case oc_implicit_default_constructor:
10283       CSM = Sema::CXXDefaultConstructor;
10284       break;
10285     case oc_implicit_copy_constructor:
10286       CSM = Sema::CXXCopyConstructor;
10287       break;
10288     case oc_implicit_move_constructor:
10289       CSM = Sema::CXXMoveConstructor;
10290       break;
10291     case oc_implicit_copy_assignment:
10292       CSM = Sema::CXXCopyAssignment;
10293       break;
10294     case oc_implicit_move_assignment:
10295       CSM = Sema::CXXMoveAssignment;
10296       break;
10297     };
10298 
10299     bool ConstRHS = false;
10300     if (Meth->getNumParams()) {
10301       if (const ReferenceType *RT =
10302               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10303         ConstRHS = RT->getPointeeType().isConstQualified();
10304       }
10305     }
10306 
10307     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10308                                               /* ConstRHS */ ConstRHS,
10309                                               /* Diagnose */ true);
10310   }
10311 }
10312 
10313 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10314   FunctionDecl *Callee = Cand->Function;
10315   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10316 
10317   S.Diag(Callee->getLocation(),
10318          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10319       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10320 }
10321 
10322 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10323   FunctionDecl *Callee = Cand->Function;
10324 
10325   S.Diag(Callee->getLocation(),
10326          diag::note_ovl_candidate_disabled_by_extension)
10327     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10328 }
10329 
10330 /// Generates a 'note' diagnostic for an overload candidate.  We've
10331 /// already generated a primary error at the call site.
10332 ///
10333 /// It really does need to be a single diagnostic with its caret
10334 /// pointed at the candidate declaration.  Yes, this creates some
10335 /// major challenges of technical writing.  Yes, this makes pointing
10336 /// out problems with specific arguments quite awkward.  It's still
10337 /// better than generating twenty screens of text for every failed
10338 /// overload.
10339 ///
10340 /// It would be great to be able to express per-candidate problems
10341 /// more richly for those diagnostic clients that cared, but we'd
10342 /// still have to be just as careful with the default diagnostics.
10343 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10344                                   unsigned NumArgs,
10345                                   bool TakingCandidateAddress) {
10346   FunctionDecl *Fn = Cand->Function;
10347 
10348   // Note deleted candidates, but only if they're viable.
10349   if (Cand->Viable) {
10350     if (Fn->isDeleted()) {
10351       std::string FnDesc;
10352       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10353           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10354 
10355       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10356           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10357           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10358       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10359       return;
10360     }
10361 
10362     // We don't really have anything else to say about viable candidates.
10363     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10364     return;
10365   }
10366 
10367   switch (Cand->FailureKind) {
10368   case ovl_fail_too_many_arguments:
10369   case ovl_fail_too_few_arguments:
10370     return DiagnoseArityMismatch(S, Cand, NumArgs);
10371 
10372   case ovl_fail_bad_deduction:
10373     return DiagnoseBadDeduction(S, Cand, NumArgs,
10374                                 TakingCandidateAddress);
10375 
10376   case ovl_fail_illegal_constructor: {
10377     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10378       << (Fn->getPrimaryTemplate() ? 1 : 0);
10379     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10380     return;
10381   }
10382 
10383   case ovl_fail_trivial_conversion:
10384   case ovl_fail_bad_final_conversion:
10385   case ovl_fail_final_conversion_not_exact:
10386     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10387 
10388   case ovl_fail_bad_conversion: {
10389     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10390     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10391       if (Cand->Conversions[I].isBad())
10392         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10393 
10394     // FIXME: this currently happens when we're called from SemaInit
10395     // when user-conversion overload fails.  Figure out how to handle
10396     // those conditions and diagnose them well.
10397     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10398   }
10399 
10400   case ovl_fail_bad_target:
10401     return DiagnoseBadTarget(S, Cand);
10402 
10403   case ovl_fail_enable_if:
10404     return DiagnoseFailedEnableIfAttr(S, Cand);
10405 
10406   case ovl_fail_ext_disabled:
10407     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10408 
10409   case ovl_fail_inhctor_slice:
10410     // It's generally not interesting to note copy/move constructors here.
10411     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10412       return;
10413     S.Diag(Fn->getLocation(),
10414            diag::note_ovl_candidate_inherited_constructor_slice)
10415       << (Fn->getPrimaryTemplate() ? 1 : 0)
10416       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10417     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10418     return;
10419 
10420   case ovl_fail_addr_not_available: {
10421     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10422     (void)Available;
10423     assert(!Available);
10424     break;
10425   }
10426   case ovl_non_default_multiversion_function:
10427     // Do nothing, these should simply be ignored.
10428     break;
10429   }
10430 }
10431 
10432 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10433   // Desugar the type of the surrogate down to a function type,
10434   // retaining as many typedefs as possible while still showing
10435   // the function type (and, therefore, its parameter types).
10436   QualType FnType = Cand->Surrogate->getConversionType();
10437   bool isLValueReference = false;
10438   bool isRValueReference = false;
10439   bool isPointer = false;
10440   if (const LValueReferenceType *FnTypeRef =
10441         FnType->getAs<LValueReferenceType>()) {
10442     FnType = FnTypeRef->getPointeeType();
10443     isLValueReference = true;
10444   } else if (const RValueReferenceType *FnTypeRef =
10445                FnType->getAs<RValueReferenceType>()) {
10446     FnType = FnTypeRef->getPointeeType();
10447     isRValueReference = true;
10448   }
10449   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10450     FnType = FnTypePtr->getPointeeType();
10451     isPointer = true;
10452   }
10453   // Desugar down to a function type.
10454   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10455   // Reconstruct the pointer/reference as appropriate.
10456   if (isPointer) FnType = S.Context.getPointerType(FnType);
10457   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10458   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10459 
10460   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10461     << FnType;
10462 }
10463 
10464 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10465                                          SourceLocation OpLoc,
10466                                          OverloadCandidate *Cand) {
10467   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10468   std::string TypeStr("operator");
10469   TypeStr += Opc;
10470   TypeStr += "(";
10471   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10472   if (Cand->Conversions.size() == 1) {
10473     TypeStr += ")";
10474     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10475   } else {
10476     TypeStr += ", ";
10477     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10478     TypeStr += ")";
10479     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10480   }
10481 }
10482 
10483 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10484                                          OverloadCandidate *Cand) {
10485   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10486     if (ICS.isBad()) break; // all meaningless after first invalid
10487     if (!ICS.isAmbiguous()) continue;
10488 
10489     ICS.DiagnoseAmbiguousConversion(
10490         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10491   }
10492 }
10493 
10494 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10495   if (Cand->Function)
10496     return Cand->Function->getLocation();
10497   if (Cand->IsSurrogate)
10498     return Cand->Surrogate->getLocation();
10499   return SourceLocation();
10500 }
10501 
10502 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10503   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10504   case Sema::TDK_Success:
10505   case Sema::TDK_NonDependentConversionFailure:
10506     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10507 
10508   case Sema::TDK_Invalid:
10509   case Sema::TDK_Incomplete:
10510   case Sema::TDK_IncompletePack:
10511     return 1;
10512 
10513   case Sema::TDK_Underqualified:
10514   case Sema::TDK_Inconsistent:
10515     return 2;
10516 
10517   case Sema::TDK_SubstitutionFailure:
10518   case Sema::TDK_DeducedMismatch:
10519   case Sema::TDK_DeducedMismatchNested:
10520   case Sema::TDK_NonDeducedMismatch:
10521   case Sema::TDK_MiscellaneousDeductionFailure:
10522   case Sema::TDK_CUDATargetMismatch:
10523     return 3;
10524 
10525   case Sema::TDK_InstantiationDepth:
10526     return 4;
10527 
10528   case Sema::TDK_InvalidExplicitArguments:
10529     return 5;
10530 
10531   case Sema::TDK_TooManyArguments:
10532   case Sema::TDK_TooFewArguments:
10533     return 6;
10534   }
10535   llvm_unreachable("Unhandled deduction result");
10536 }
10537 
10538 namespace {
10539 struct CompareOverloadCandidatesForDisplay {
10540   Sema &S;
10541   SourceLocation Loc;
10542   size_t NumArgs;
10543   OverloadCandidateSet::CandidateSetKind CSK;
10544 
10545   CompareOverloadCandidatesForDisplay(
10546       Sema &S, SourceLocation Loc, size_t NArgs,
10547       OverloadCandidateSet::CandidateSetKind CSK)
10548       : S(S), NumArgs(NArgs), CSK(CSK) {}
10549 
10550   bool operator()(const OverloadCandidate *L,
10551                   const OverloadCandidate *R) {
10552     // Fast-path this check.
10553     if (L == R) return false;
10554 
10555     // Order first by viability.
10556     if (L->Viable) {
10557       if (!R->Viable) return true;
10558 
10559       // TODO: introduce a tri-valued comparison for overload
10560       // candidates.  Would be more worthwhile if we had a sort
10561       // that could exploit it.
10562       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10563         return true;
10564       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10565         return false;
10566     } else if (R->Viable)
10567       return false;
10568 
10569     assert(L->Viable == R->Viable);
10570 
10571     // Criteria by which we can sort non-viable candidates:
10572     if (!L->Viable) {
10573       // 1. Arity mismatches come after other candidates.
10574       if (L->FailureKind == ovl_fail_too_many_arguments ||
10575           L->FailureKind == ovl_fail_too_few_arguments) {
10576         if (R->FailureKind == ovl_fail_too_many_arguments ||
10577             R->FailureKind == ovl_fail_too_few_arguments) {
10578           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10579           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10580           if (LDist == RDist) {
10581             if (L->FailureKind == R->FailureKind)
10582               // Sort non-surrogates before surrogates.
10583               return !L->IsSurrogate && R->IsSurrogate;
10584             // Sort candidates requiring fewer parameters than there were
10585             // arguments given after candidates requiring more parameters
10586             // than there were arguments given.
10587             return L->FailureKind == ovl_fail_too_many_arguments;
10588           }
10589           return LDist < RDist;
10590         }
10591         return false;
10592       }
10593       if (R->FailureKind == ovl_fail_too_many_arguments ||
10594           R->FailureKind == ovl_fail_too_few_arguments)
10595         return true;
10596 
10597       // 2. Bad conversions come first and are ordered by the number
10598       // of bad conversions and quality of good conversions.
10599       if (L->FailureKind == ovl_fail_bad_conversion) {
10600         if (R->FailureKind != ovl_fail_bad_conversion)
10601           return true;
10602 
10603         // The conversion that can be fixed with a smaller number of changes,
10604         // comes first.
10605         unsigned numLFixes = L->Fix.NumConversionsFixed;
10606         unsigned numRFixes = R->Fix.NumConversionsFixed;
10607         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10608         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10609         if (numLFixes != numRFixes) {
10610           return numLFixes < numRFixes;
10611         }
10612 
10613         // If there's any ordering between the defined conversions...
10614         // FIXME: this might not be transitive.
10615         assert(L->Conversions.size() == R->Conversions.size());
10616 
10617         int leftBetter = 0;
10618         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10619         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10620           switch (CompareImplicitConversionSequences(S, Loc,
10621                                                      L->Conversions[I],
10622                                                      R->Conversions[I])) {
10623           case ImplicitConversionSequence::Better:
10624             leftBetter++;
10625             break;
10626 
10627           case ImplicitConversionSequence::Worse:
10628             leftBetter--;
10629             break;
10630 
10631           case ImplicitConversionSequence::Indistinguishable:
10632             break;
10633           }
10634         }
10635         if (leftBetter > 0) return true;
10636         if (leftBetter < 0) return false;
10637 
10638       } else if (R->FailureKind == ovl_fail_bad_conversion)
10639         return false;
10640 
10641       if (L->FailureKind == ovl_fail_bad_deduction) {
10642         if (R->FailureKind != ovl_fail_bad_deduction)
10643           return true;
10644 
10645         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10646           return RankDeductionFailure(L->DeductionFailure)
10647                < RankDeductionFailure(R->DeductionFailure);
10648       } else if (R->FailureKind == ovl_fail_bad_deduction)
10649         return false;
10650 
10651       // TODO: others?
10652     }
10653 
10654     // Sort everything else by location.
10655     SourceLocation LLoc = GetLocationForCandidate(L);
10656     SourceLocation RLoc = GetLocationForCandidate(R);
10657 
10658     // Put candidates without locations (e.g. builtins) at the end.
10659     if (LLoc.isInvalid()) return false;
10660     if (RLoc.isInvalid()) return true;
10661 
10662     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10663   }
10664 };
10665 }
10666 
10667 /// CompleteNonViableCandidate - Normally, overload resolution only
10668 /// computes up to the first bad conversion. Produces the FixIt set if
10669 /// possible.
10670 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10671                                        ArrayRef<Expr *> Args) {
10672   assert(!Cand->Viable);
10673 
10674   // Don't do anything on failures other than bad conversion.
10675   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10676 
10677   // We only want the FixIts if all the arguments can be corrected.
10678   bool Unfixable = false;
10679   // Use a implicit copy initialization to check conversion fixes.
10680   Cand->Fix.setConversionChecker(TryCopyInitialization);
10681 
10682   // Attempt to fix the bad conversion.
10683   unsigned ConvCount = Cand->Conversions.size();
10684   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10685        ++ConvIdx) {
10686     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10687     if (Cand->Conversions[ConvIdx].isInitialized() &&
10688         Cand->Conversions[ConvIdx].isBad()) {
10689       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10690       break;
10691     }
10692   }
10693 
10694   // FIXME: this should probably be preserved from the overload
10695   // operation somehow.
10696   bool SuppressUserConversions = false;
10697 
10698   unsigned ConvIdx = 0;
10699   ArrayRef<QualType> ParamTypes;
10700 
10701   if (Cand->IsSurrogate) {
10702     QualType ConvType
10703       = Cand->Surrogate->getConversionType().getNonReferenceType();
10704     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10705       ConvType = ConvPtrType->getPointeeType();
10706     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10707     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10708     ConvIdx = 1;
10709   } else if (Cand->Function) {
10710     ParamTypes =
10711         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10712     if (isa<CXXMethodDecl>(Cand->Function) &&
10713         !isa<CXXConstructorDecl>(Cand->Function)) {
10714       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10715       ConvIdx = 1;
10716     }
10717   } else {
10718     // Builtin operator.
10719     assert(ConvCount <= 3);
10720     ParamTypes = Cand->BuiltinParamTypes;
10721   }
10722 
10723   // Fill in the rest of the conversions.
10724   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10725     if (Cand->Conversions[ConvIdx].isInitialized()) {
10726       // We've already checked this conversion.
10727     } else if (ArgIdx < ParamTypes.size()) {
10728       if (ParamTypes[ArgIdx]->isDependentType())
10729         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10730             Args[ArgIdx]->getType());
10731       else {
10732         Cand->Conversions[ConvIdx] =
10733             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10734                                   SuppressUserConversions,
10735                                   /*InOverloadResolution=*/true,
10736                                   /*AllowObjCWritebackConversion=*/
10737                                   S.getLangOpts().ObjCAutoRefCount);
10738         // Store the FixIt in the candidate if it exists.
10739         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10740           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10741       }
10742     } else
10743       Cand->Conversions[ConvIdx].setEllipsis();
10744   }
10745 }
10746 
10747 /// When overload resolution fails, prints diagnostic messages containing the
10748 /// candidates in the candidate set.
10749 void OverloadCandidateSet::NoteCandidates(
10750     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10751     StringRef Opc, SourceLocation OpLoc,
10752     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10753   // Sort the candidates by viability and position.  Sorting directly would
10754   // be prohibitive, so we make a set of pointers and sort those.
10755   SmallVector<OverloadCandidate*, 32> Cands;
10756   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10757   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10758     if (!Filter(*Cand))
10759       continue;
10760     if (Cand->Viable)
10761       Cands.push_back(Cand);
10762     else if (OCD == OCD_AllCandidates) {
10763       CompleteNonViableCandidate(S, Cand, Args);
10764       if (Cand->Function || Cand->IsSurrogate)
10765         Cands.push_back(Cand);
10766       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10767       // want to list every possible builtin candidate.
10768     }
10769   }
10770 
10771   std::stable_sort(Cands.begin(), Cands.end(),
10772             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10773 
10774   bool ReportedAmbiguousConversions = false;
10775 
10776   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10777   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10778   unsigned CandsShown = 0;
10779   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10780     OverloadCandidate *Cand = *I;
10781 
10782     // Set an arbitrary limit on the number of candidate functions we'll spam
10783     // the user with.  FIXME: This limit should depend on details of the
10784     // candidate list.
10785     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10786       break;
10787     }
10788     ++CandsShown;
10789 
10790     if (Cand->Function)
10791       NoteFunctionCandidate(S, Cand, Args.size(),
10792                             /*TakingCandidateAddress=*/false);
10793     else if (Cand->IsSurrogate)
10794       NoteSurrogateCandidate(S, Cand);
10795     else {
10796       assert(Cand->Viable &&
10797              "Non-viable built-in candidates are not added to Cands.");
10798       // Generally we only see ambiguities including viable builtin
10799       // operators if overload resolution got screwed up by an
10800       // ambiguous user-defined conversion.
10801       //
10802       // FIXME: It's quite possible for different conversions to see
10803       // different ambiguities, though.
10804       if (!ReportedAmbiguousConversions) {
10805         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10806         ReportedAmbiguousConversions = true;
10807       }
10808 
10809       // If this is a viable builtin, print it.
10810       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10811     }
10812   }
10813 
10814   if (I != E)
10815     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10816 }
10817 
10818 static SourceLocation
10819 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10820   return Cand->Specialization ? Cand->Specialization->getLocation()
10821                               : SourceLocation();
10822 }
10823 
10824 namespace {
10825 struct CompareTemplateSpecCandidatesForDisplay {
10826   Sema &S;
10827   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10828 
10829   bool operator()(const TemplateSpecCandidate *L,
10830                   const TemplateSpecCandidate *R) {
10831     // Fast-path this check.
10832     if (L == R)
10833       return false;
10834 
10835     // Assuming that both candidates are not matches...
10836 
10837     // Sort by the ranking of deduction failures.
10838     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10839       return RankDeductionFailure(L->DeductionFailure) <
10840              RankDeductionFailure(R->DeductionFailure);
10841 
10842     // Sort everything else by location.
10843     SourceLocation LLoc = GetLocationForCandidate(L);
10844     SourceLocation RLoc = GetLocationForCandidate(R);
10845 
10846     // Put candidates without locations (e.g. builtins) at the end.
10847     if (LLoc.isInvalid())
10848       return false;
10849     if (RLoc.isInvalid())
10850       return true;
10851 
10852     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10853   }
10854 };
10855 }
10856 
10857 /// Diagnose a template argument deduction failure.
10858 /// We are treating these failures as overload failures due to bad
10859 /// deductions.
10860 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10861                                                  bool ForTakingAddress) {
10862   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10863                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10864 }
10865 
10866 void TemplateSpecCandidateSet::destroyCandidates() {
10867   for (iterator i = begin(), e = end(); i != e; ++i) {
10868     i->DeductionFailure.Destroy();
10869   }
10870 }
10871 
10872 void TemplateSpecCandidateSet::clear() {
10873   destroyCandidates();
10874   Candidates.clear();
10875 }
10876 
10877 /// NoteCandidates - When no template specialization match is found, prints
10878 /// diagnostic messages containing the non-matching specializations that form
10879 /// the candidate set.
10880 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10881 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10882 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10883   // Sort the candidates by position (assuming no candidate is a match).
10884   // Sorting directly would be prohibitive, so we make a set of pointers
10885   // and sort those.
10886   SmallVector<TemplateSpecCandidate *, 32> Cands;
10887   Cands.reserve(size());
10888   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10889     if (Cand->Specialization)
10890       Cands.push_back(Cand);
10891     // Otherwise, this is a non-matching builtin candidate.  We do not,
10892     // in general, want to list every possible builtin candidate.
10893   }
10894 
10895   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10896 
10897   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10898   // for generalization purposes (?).
10899   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10900 
10901   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10902   unsigned CandsShown = 0;
10903   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10904     TemplateSpecCandidate *Cand = *I;
10905 
10906     // Set an arbitrary limit on the number of candidates we'll spam
10907     // the user with.  FIXME: This limit should depend on details of the
10908     // candidate list.
10909     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10910       break;
10911     ++CandsShown;
10912 
10913     assert(Cand->Specialization &&
10914            "Non-matching built-in candidates are not added to Cands.");
10915     Cand->NoteDeductionFailure(S, ForTakingAddress);
10916   }
10917 
10918   if (I != E)
10919     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10920 }
10921 
10922 // [PossiblyAFunctionType]  -->   [Return]
10923 // NonFunctionType --> NonFunctionType
10924 // R (A) --> R(A)
10925 // R (*)(A) --> R (A)
10926 // R (&)(A) --> R (A)
10927 // R (S::*)(A) --> R (A)
10928 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10929   QualType Ret = PossiblyAFunctionType;
10930   if (const PointerType *ToTypePtr =
10931     PossiblyAFunctionType->getAs<PointerType>())
10932     Ret = ToTypePtr->getPointeeType();
10933   else if (const ReferenceType *ToTypeRef =
10934     PossiblyAFunctionType->getAs<ReferenceType>())
10935     Ret = ToTypeRef->getPointeeType();
10936   else if (const MemberPointerType *MemTypePtr =
10937     PossiblyAFunctionType->getAs<MemberPointerType>())
10938     Ret = MemTypePtr->getPointeeType();
10939   Ret =
10940     Context.getCanonicalType(Ret).getUnqualifiedType();
10941   return Ret;
10942 }
10943 
10944 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10945                                  bool Complain = true) {
10946   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10947       S.DeduceReturnType(FD, Loc, Complain))
10948     return true;
10949 
10950   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10951   if (S.getLangOpts().CPlusPlus17 &&
10952       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10953       !S.ResolveExceptionSpec(Loc, FPT))
10954     return true;
10955 
10956   return false;
10957 }
10958 
10959 namespace {
10960 // A helper class to help with address of function resolution
10961 // - allows us to avoid passing around all those ugly parameters
10962 class AddressOfFunctionResolver {
10963   Sema& S;
10964   Expr* SourceExpr;
10965   const QualType& TargetType;
10966   QualType TargetFunctionType; // Extracted function type from target type
10967 
10968   bool Complain;
10969   //DeclAccessPair& ResultFunctionAccessPair;
10970   ASTContext& Context;
10971 
10972   bool TargetTypeIsNonStaticMemberFunction;
10973   bool FoundNonTemplateFunction;
10974   bool StaticMemberFunctionFromBoundPointer;
10975   bool HasComplained;
10976 
10977   OverloadExpr::FindResult OvlExprInfo;
10978   OverloadExpr *OvlExpr;
10979   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10980   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10981   TemplateSpecCandidateSet FailedCandidates;
10982 
10983 public:
10984   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10985                             const QualType &TargetType, bool Complain)
10986       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10987         Complain(Complain), Context(S.getASTContext()),
10988         TargetTypeIsNonStaticMemberFunction(
10989             !!TargetType->getAs<MemberPointerType>()),
10990         FoundNonTemplateFunction(false),
10991         StaticMemberFunctionFromBoundPointer(false),
10992         HasComplained(false),
10993         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10994         OvlExpr(OvlExprInfo.Expression),
10995         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10996     ExtractUnqualifiedFunctionTypeFromTargetType();
10997 
10998     if (TargetFunctionType->isFunctionType()) {
10999       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11000         if (!UME->isImplicitAccess() &&
11001             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11002           StaticMemberFunctionFromBoundPointer = true;
11003     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11004       DeclAccessPair dap;
11005       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11006               OvlExpr, false, &dap)) {
11007         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11008           if (!Method->isStatic()) {
11009             // If the target type is a non-function type and the function found
11010             // is a non-static member function, pretend as if that was the
11011             // target, it's the only possible type to end up with.
11012             TargetTypeIsNonStaticMemberFunction = true;
11013 
11014             // And skip adding the function if its not in the proper form.
11015             // We'll diagnose this due to an empty set of functions.
11016             if (!OvlExprInfo.HasFormOfMemberPointer)
11017               return;
11018           }
11019 
11020         Matches.push_back(std::make_pair(dap, Fn));
11021       }
11022       return;
11023     }
11024 
11025     if (OvlExpr->hasExplicitTemplateArgs())
11026       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11027 
11028     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11029       // C++ [over.over]p4:
11030       //   If more than one function is selected, [...]
11031       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11032         if (FoundNonTemplateFunction)
11033           EliminateAllTemplateMatches();
11034         else
11035           EliminateAllExceptMostSpecializedTemplate();
11036       }
11037     }
11038 
11039     if (S.getLangOpts().CUDA && Matches.size() > 1)
11040       EliminateSuboptimalCudaMatches();
11041   }
11042 
11043   bool hasComplained() const { return HasComplained; }
11044 
11045 private:
11046   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11047     QualType Discard;
11048     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11049            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11050   }
11051 
11052   /// \return true if A is considered a better overload candidate for the
11053   /// desired type than B.
11054   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11055     // If A doesn't have exactly the correct type, we don't want to classify it
11056     // as "better" than anything else. This way, the user is required to
11057     // disambiguate for us if there are multiple candidates and no exact match.
11058     return candidateHasExactlyCorrectType(A) &&
11059            (!candidateHasExactlyCorrectType(B) ||
11060             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11061   }
11062 
11063   /// \return true if we were able to eliminate all but one overload candidate,
11064   /// false otherwise.
11065   bool eliminiateSuboptimalOverloadCandidates() {
11066     // Same algorithm as overload resolution -- one pass to pick the "best",
11067     // another pass to be sure that nothing is better than the best.
11068     auto Best = Matches.begin();
11069     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11070       if (isBetterCandidate(I->second, Best->second))
11071         Best = I;
11072 
11073     const FunctionDecl *BestFn = Best->second;
11074     auto IsBestOrInferiorToBest = [this, BestFn](
11075         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11076       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11077     };
11078 
11079     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11080     // option, so we can potentially give the user a better error
11081     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11082       return false;
11083     Matches[0] = *Best;
11084     Matches.resize(1);
11085     return true;
11086   }
11087 
11088   bool isTargetTypeAFunction() const {
11089     return TargetFunctionType->isFunctionType();
11090   }
11091 
11092   // [ToType]     [Return]
11093 
11094   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11095   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11096   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11097   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11098     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11099   }
11100 
11101   // return true if any matching specializations were found
11102   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11103                                    const DeclAccessPair& CurAccessFunPair) {
11104     if (CXXMethodDecl *Method
11105               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11106       // Skip non-static function templates when converting to pointer, and
11107       // static when converting to member pointer.
11108       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11109         return false;
11110     }
11111     else if (TargetTypeIsNonStaticMemberFunction)
11112       return false;
11113 
11114     // C++ [over.over]p2:
11115     //   If the name is a function template, template argument deduction is
11116     //   done (14.8.2.2), and if the argument deduction succeeds, the
11117     //   resulting template argument list is used to generate a single
11118     //   function template specialization, which is added to the set of
11119     //   overloaded functions considered.
11120     FunctionDecl *Specialization = nullptr;
11121     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11122     if (Sema::TemplateDeductionResult Result
11123           = S.DeduceTemplateArguments(FunctionTemplate,
11124                                       &OvlExplicitTemplateArgs,
11125                                       TargetFunctionType, Specialization,
11126                                       Info, /*IsAddressOfFunction*/true)) {
11127       // Make a note of the failed deduction for diagnostics.
11128       FailedCandidates.addCandidate()
11129           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11130                MakeDeductionFailureInfo(Context, Result, Info));
11131       return false;
11132     }
11133 
11134     // Template argument deduction ensures that we have an exact match or
11135     // compatible pointer-to-function arguments that would be adjusted by ICS.
11136     // This function template specicalization works.
11137     assert(S.isSameOrCompatibleFunctionType(
11138               Context.getCanonicalType(Specialization->getType()),
11139               Context.getCanonicalType(TargetFunctionType)));
11140 
11141     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11142       return false;
11143 
11144     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11145     return true;
11146   }
11147 
11148   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11149                                       const DeclAccessPair& CurAccessFunPair) {
11150     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11151       // Skip non-static functions when converting to pointer, and static
11152       // when converting to member pointer.
11153       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11154         return false;
11155     }
11156     else if (TargetTypeIsNonStaticMemberFunction)
11157       return false;
11158 
11159     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11160       if (S.getLangOpts().CUDA)
11161         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11162           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11163             return false;
11164       if (FunDecl->isMultiVersion()) {
11165         const auto *TA = FunDecl->getAttr<TargetAttr>();
11166         if (TA && !TA->isDefaultVersion())
11167           return false;
11168       }
11169 
11170       // If any candidate has a placeholder return type, trigger its deduction
11171       // now.
11172       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11173                                Complain)) {
11174         HasComplained |= Complain;
11175         return false;
11176       }
11177 
11178       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11179         return false;
11180 
11181       // If we're in C, we need to support types that aren't exactly identical.
11182       if (!S.getLangOpts().CPlusPlus ||
11183           candidateHasExactlyCorrectType(FunDecl)) {
11184         Matches.push_back(std::make_pair(
11185             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11186         FoundNonTemplateFunction = true;
11187         return true;
11188       }
11189     }
11190 
11191     return false;
11192   }
11193 
11194   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11195     bool Ret = false;
11196 
11197     // If the overload expression doesn't have the form of a pointer to
11198     // member, don't try to convert it to a pointer-to-member type.
11199     if (IsInvalidFormOfPointerToMemberFunction())
11200       return false;
11201 
11202     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11203                                E = OvlExpr->decls_end();
11204          I != E; ++I) {
11205       // Look through any using declarations to find the underlying function.
11206       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11207 
11208       // C++ [over.over]p3:
11209       //   Non-member functions and static member functions match
11210       //   targets of type "pointer-to-function" or "reference-to-function."
11211       //   Nonstatic member functions match targets of
11212       //   type "pointer-to-member-function."
11213       // Note that according to DR 247, the containing class does not matter.
11214       if (FunctionTemplateDecl *FunctionTemplate
11215                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11216         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11217           Ret = true;
11218       }
11219       // If we have explicit template arguments supplied, skip non-templates.
11220       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11221                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11222         Ret = true;
11223     }
11224     assert(Ret || Matches.empty());
11225     return Ret;
11226   }
11227 
11228   void EliminateAllExceptMostSpecializedTemplate() {
11229     //   [...] and any given function template specialization F1 is
11230     //   eliminated if the set contains a second function template
11231     //   specialization whose function template is more specialized
11232     //   than the function template of F1 according to the partial
11233     //   ordering rules of 14.5.5.2.
11234 
11235     // The algorithm specified above is quadratic. We instead use a
11236     // two-pass algorithm (similar to the one used to identify the
11237     // best viable function in an overload set) that identifies the
11238     // best function template (if it exists).
11239 
11240     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11241     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11242       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11243 
11244     // TODO: It looks like FailedCandidates does not serve much purpose
11245     // here, since the no_viable diagnostic has index 0.
11246     UnresolvedSetIterator Result = S.getMostSpecialized(
11247         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11248         SourceExpr->getBeginLoc(), S.PDiag(),
11249         S.PDiag(diag::err_addr_ovl_ambiguous)
11250             << Matches[0].second->getDeclName(),
11251         S.PDiag(diag::note_ovl_candidate)
11252             << (unsigned)oc_function << (unsigned)ocs_described_template,
11253         Complain, TargetFunctionType);
11254 
11255     if (Result != MatchesCopy.end()) {
11256       // Make it the first and only element
11257       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11258       Matches[0].second = cast<FunctionDecl>(*Result);
11259       Matches.resize(1);
11260     } else
11261       HasComplained |= Complain;
11262   }
11263 
11264   void EliminateAllTemplateMatches() {
11265     //   [...] any function template specializations in the set are
11266     //   eliminated if the set also contains a non-template function, [...]
11267     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11268       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11269         ++I;
11270       else {
11271         Matches[I] = Matches[--N];
11272         Matches.resize(N);
11273       }
11274     }
11275   }
11276 
11277   void EliminateSuboptimalCudaMatches() {
11278     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11279   }
11280 
11281 public:
11282   void ComplainNoMatchesFound() const {
11283     assert(Matches.empty());
11284     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11285         << OvlExpr->getName() << TargetFunctionType
11286         << OvlExpr->getSourceRange();
11287     if (FailedCandidates.empty())
11288       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11289                                   /*TakingAddress=*/true);
11290     else {
11291       // We have some deduction failure messages. Use them to diagnose
11292       // the function templates, and diagnose the non-template candidates
11293       // normally.
11294       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11295                                  IEnd = OvlExpr->decls_end();
11296            I != IEnd; ++I)
11297         if (FunctionDecl *Fun =
11298                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11299           if (!functionHasPassObjectSizeParams(Fun))
11300             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11301                                     /*TakingAddress=*/true);
11302       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11303     }
11304   }
11305 
11306   bool IsInvalidFormOfPointerToMemberFunction() const {
11307     return TargetTypeIsNonStaticMemberFunction &&
11308       !OvlExprInfo.HasFormOfMemberPointer;
11309   }
11310 
11311   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11312       // TODO: Should we condition this on whether any functions might
11313       // have matched, or is it more appropriate to do that in callers?
11314       // TODO: a fixit wouldn't hurt.
11315       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11316         << TargetType << OvlExpr->getSourceRange();
11317   }
11318 
11319   bool IsStaticMemberFunctionFromBoundPointer() const {
11320     return StaticMemberFunctionFromBoundPointer;
11321   }
11322 
11323   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11324     S.Diag(OvlExpr->getBeginLoc(),
11325            diag::err_invalid_form_pointer_member_function)
11326         << OvlExpr->getSourceRange();
11327   }
11328 
11329   void ComplainOfInvalidConversion() const {
11330     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11331         << OvlExpr->getName() << TargetType;
11332   }
11333 
11334   void ComplainMultipleMatchesFound() const {
11335     assert(Matches.size() > 1);
11336     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11337         << OvlExpr->getName() << OvlExpr->getSourceRange();
11338     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11339                                 /*TakingAddress=*/true);
11340   }
11341 
11342   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11343 
11344   int getNumMatches() const { return Matches.size(); }
11345 
11346   FunctionDecl* getMatchingFunctionDecl() const {
11347     if (Matches.size() != 1) return nullptr;
11348     return Matches[0].second;
11349   }
11350 
11351   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11352     if (Matches.size() != 1) return nullptr;
11353     return &Matches[0].first;
11354   }
11355 };
11356 }
11357 
11358 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11359 /// an overloaded function (C++ [over.over]), where @p From is an
11360 /// expression with overloaded function type and @p ToType is the type
11361 /// we're trying to resolve to. For example:
11362 ///
11363 /// @code
11364 /// int f(double);
11365 /// int f(int);
11366 ///
11367 /// int (*pfd)(double) = f; // selects f(double)
11368 /// @endcode
11369 ///
11370 /// This routine returns the resulting FunctionDecl if it could be
11371 /// resolved, and NULL otherwise. When @p Complain is true, this
11372 /// routine will emit diagnostics if there is an error.
11373 FunctionDecl *
11374 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11375                                          QualType TargetType,
11376                                          bool Complain,
11377                                          DeclAccessPair &FoundResult,
11378                                          bool *pHadMultipleCandidates) {
11379   assert(AddressOfExpr->getType() == Context.OverloadTy);
11380 
11381   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11382                                      Complain);
11383   int NumMatches = Resolver.getNumMatches();
11384   FunctionDecl *Fn = nullptr;
11385   bool ShouldComplain = Complain && !Resolver.hasComplained();
11386   if (NumMatches == 0 && ShouldComplain) {
11387     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11388       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11389     else
11390       Resolver.ComplainNoMatchesFound();
11391   }
11392   else if (NumMatches > 1 && ShouldComplain)
11393     Resolver.ComplainMultipleMatchesFound();
11394   else if (NumMatches == 1) {
11395     Fn = Resolver.getMatchingFunctionDecl();
11396     assert(Fn);
11397     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11398       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11399     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11400     if (Complain) {
11401       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11402         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11403       else
11404         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11405     }
11406   }
11407 
11408   if (pHadMultipleCandidates)
11409     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11410   return Fn;
11411 }
11412 
11413 /// Given an expression that refers to an overloaded function, try to
11414 /// resolve that function to a single function that can have its address taken.
11415 /// This will modify `Pair` iff it returns non-null.
11416 ///
11417 /// This routine can only realistically succeed if all but one candidates in the
11418 /// overload set for SrcExpr cannot have their addresses taken.
11419 FunctionDecl *
11420 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11421                                                   DeclAccessPair &Pair) {
11422   OverloadExpr::FindResult R = OverloadExpr::find(E);
11423   OverloadExpr *Ovl = R.Expression;
11424   FunctionDecl *Result = nullptr;
11425   DeclAccessPair DAP;
11426   // Don't use the AddressOfResolver because we're specifically looking for
11427   // cases where we have one overload candidate that lacks
11428   // enable_if/pass_object_size/...
11429   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11430     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11431     if (!FD)
11432       return nullptr;
11433 
11434     if (!checkAddressOfFunctionIsAvailable(FD))
11435       continue;
11436 
11437     // We have more than one result; quit.
11438     if (Result)
11439       return nullptr;
11440     DAP = I.getPair();
11441     Result = FD;
11442   }
11443 
11444   if (Result)
11445     Pair = DAP;
11446   return Result;
11447 }
11448 
11449 /// Given an overloaded function, tries to turn it into a non-overloaded
11450 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11451 /// will perform access checks, diagnose the use of the resultant decl, and, if
11452 /// requested, potentially perform a function-to-pointer decay.
11453 ///
11454 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11455 /// Otherwise, returns true. This may emit diagnostics and return true.
11456 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11457     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11458   Expr *E = SrcExpr.get();
11459   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11460 
11461   DeclAccessPair DAP;
11462   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11463   if (!Found || Found->isCPUDispatchMultiVersion() ||
11464       Found->isCPUSpecificMultiVersion())
11465     return false;
11466 
11467   // Emitting multiple diagnostics for a function that is both inaccessible and
11468   // unavailable is consistent with our behavior elsewhere. So, always check
11469   // for both.
11470   DiagnoseUseOfDecl(Found, E->getExprLoc());
11471   CheckAddressOfMemberAccess(E, DAP);
11472   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11473   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11474     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11475   else
11476     SrcExpr = Fixed;
11477   return true;
11478 }
11479 
11480 /// Given an expression that refers to an overloaded function, try to
11481 /// resolve that overloaded function expression down to a single function.
11482 ///
11483 /// This routine can only resolve template-ids that refer to a single function
11484 /// template, where that template-id refers to a single template whose template
11485 /// arguments are either provided by the template-id or have defaults,
11486 /// as described in C++0x [temp.arg.explicit]p3.
11487 ///
11488 /// If no template-ids are found, no diagnostics are emitted and NULL is
11489 /// returned.
11490 FunctionDecl *
11491 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11492                                                   bool Complain,
11493                                                   DeclAccessPair *FoundResult) {
11494   // C++ [over.over]p1:
11495   //   [...] [Note: any redundant set of parentheses surrounding the
11496   //   overloaded function name is ignored (5.1). ]
11497   // C++ [over.over]p1:
11498   //   [...] The overloaded function name can be preceded by the &
11499   //   operator.
11500 
11501   // If we didn't actually find any template-ids, we're done.
11502   if (!ovl->hasExplicitTemplateArgs())
11503     return nullptr;
11504 
11505   TemplateArgumentListInfo ExplicitTemplateArgs;
11506   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11507   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11508 
11509   // Look through all of the overloaded functions, searching for one
11510   // whose type matches exactly.
11511   FunctionDecl *Matched = nullptr;
11512   for (UnresolvedSetIterator I = ovl->decls_begin(),
11513          E = ovl->decls_end(); I != E; ++I) {
11514     // C++0x [temp.arg.explicit]p3:
11515     //   [...] In contexts where deduction is done and fails, or in contexts
11516     //   where deduction is not done, if a template argument list is
11517     //   specified and it, along with any default template arguments,
11518     //   identifies a single function template specialization, then the
11519     //   template-id is an lvalue for the function template specialization.
11520     FunctionTemplateDecl *FunctionTemplate
11521       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11522 
11523     // C++ [over.over]p2:
11524     //   If the name is a function template, template argument deduction is
11525     //   done (14.8.2.2), and if the argument deduction succeeds, the
11526     //   resulting template argument list is used to generate a single
11527     //   function template specialization, which is added to the set of
11528     //   overloaded functions considered.
11529     FunctionDecl *Specialization = nullptr;
11530     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11531     if (TemplateDeductionResult Result
11532           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11533                                     Specialization, Info,
11534                                     /*IsAddressOfFunction*/true)) {
11535       // Make a note of the failed deduction for diagnostics.
11536       // TODO: Actually use the failed-deduction info?
11537       FailedCandidates.addCandidate()
11538           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11539                MakeDeductionFailureInfo(Context, Result, Info));
11540       continue;
11541     }
11542 
11543     assert(Specialization && "no specialization and no error?");
11544 
11545     // Multiple matches; we can't resolve to a single declaration.
11546     if (Matched) {
11547       if (Complain) {
11548         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11549           << ovl->getName();
11550         NoteAllOverloadCandidates(ovl);
11551       }
11552       return nullptr;
11553     }
11554 
11555     Matched = Specialization;
11556     if (FoundResult) *FoundResult = I.getPair();
11557   }
11558 
11559   if (Matched &&
11560       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11561     return nullptr;
11562 
11563   return Matched;
11564 }
11565 
11566 // Resolve and fix an overloaded expression that can be resolved
11567 // because it identifies a single function template specialization.
11568 //
11569 // Last three arguments should only be supplied if Complain = true
11570 //
11571 // Return true if it was logically possible to so resolve the
11572 // expression, regardless of whether or not it succeeded.  Always
11573 // returns true if 'complain' is set.
11574 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11575                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11576                       bool complain, SourceRange OpRangeForComplaining,
11577                                            QualType DestTypeForComplaining,
11578                                             unsigned DiagIDForComplaining) {
11579   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11580 
11581   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11582 
11583   DeclAccessPair found;
11584   ExprResult SingleFunctionExpression;
11585   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11586                            ovl.Expression, /*complain*/ false, &found)) {
11587     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11588       SrcExpr = ExprError();
11589       return true;
11590     }
11591 
11592     // It is only correct to resolve to an instance method if we're
11593     // resolving a form that's permitted to be a pointer to member.
11594     // Otherwise we'll end up making a bound member expression, which
11595     // is illegal in all the contexts we resolve like this.
11596     if (!ovl.HasFormOfMemberPointer &&
11597         isa<CXXMethodDecl>(fn) &&
11598         cast<CXXMethodDecl>(fn)->isInstance()) {
11599       if (!complain) return false;
11600 
11601       Diag(ovl.Expression->getExprLoc(),
11602            diag::err_bound_member_function)
11603         << 0 << ovl.Expression->getSourceRange();
11604 
11605       // TODO: I believe we only end up here if there's a mix of
11606       // static and non-static candidates (otherwise the expression
11607       // would have 'bound member' type, not 'overload' type).
11608       // Ideally we would note which candidate was chosen and why
11609       // the static candidates were rejected.
11610       SrcExpr = ExprError();
11611       return true;
11612     }
11613 
11614     // Fix the expression to refer to 'fn'.
11615     SingleFunctionExpression =
11616         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11617 
11618     // If desired, do function-to-pointer decay.
11619     if (doFunctionPointerConverion) {
11620       SingleFunctionExpression =
11621         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11622       if (SingleFunctionExpression.isInvalid()) {
11623         SrcExpr = ExprError();
11624         return true;
11625       }
11626     }
11627   }
11628 
11629   if (!SingleFunctionExpression.isUsable()) {
11630     if (complain) {
11631       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11632         << ovl.Expression->getName()
11633         << DestTypeForComplaining
11634         << OpRangeForComplaining
11635         << ovl.Expression->getQualifierLoc().getSourceRange();
11636       NoteAllOverloadCandidates(SrcExpr.get());
11637 
11638       SrcExpr = ExprError();
11639       return true;
11640     }
11641 
11642     return false;
11643   }
11644 
11645   SrcExpr = SingleFunctionExpression;
11646   return true;
11647 }
11648 
11649 /// Add a single candidate to the overload set.
11650 static void AddOverloadedCallCandidate(Sema &S,
11651                                        DeclAccessPair FoundDecl,
11652                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11653                                        ArrayRef<Expr *> Args,
11654                                        OverloadCandidateSet &CandidateSet,
11655                                        bool PartialOverloading,
11656                                        bool KnownValid) {
11657   NamedDecl *Callee = FoundDecl.getDecl();
11658   if (isa<UsingShadowDecl>(Callee))
11659     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11660 
11661   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11662     if (ExplicitTemplateArgs) {
11663       assert(!KnownValid && "Explicit template arguments?");
11664       return;
11665     }
11666     // Prevent ill-formed function decls to be added as overload candidates.
11667     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11668       return;
11669 
11670     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11671                            /*SuppressUsedConversions=*/false,
11672                            PartialOverloading);
11673     return;
11674   }
11675 
11676   if (FunctionTemplateDecl *FuncTemplate
11677       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11678     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11679                                    ExplicitTemplateArgs, Args, CandidateSet,
11680                                    /*SuppressUsedConversions=*/false,
11681                                    PartialOverloading);
11682     return;
11683   }
11684 
11685   assert(!KnownValid && "unhandled case in overloaded call candidate");
11686 }
11687 
11688 /// Add the overload candidates named by callee and/or found by argument
11689 /// dependent lookup to the given overload set.
11690 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11691                                        ArrayRef<Expr *> Args,
11692                                        OverloadCandidateSet &CandidateSet,
11693                                        bool PartialOverloading) {
11694 
11695 #ifndef NDEBUG
11696   // Verify that ArgumentDependentLookup is consistent with the rules
11697   // in C++0x [basic.lookup.argdep]p3:
11698   //
11699   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11700   //   and let Y be the lookup set produced by argument dependent
11701   //   lookup (defined as follows). If X contains
11702   //
11703   //     -- a declaration of a class member, or
11704   //
11705   //     -- a block-scope function declaration that is not a
11706   //        using-declaration, or
11707   //
11708   //     -- a declaration that is neither a function or a function
11709   //        template
11710   //
11711   //   then Y is empty.
11712 
11713   if (ULE->requiresADL()) {
11714     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11715            E = ULE->decls_end(); I != E; ++I) {
11716       assert(!(*I)->getDeclContext()->isRecord());
11717       assert(isa<UsingShadowDecl>(*I) ||
11718              !(*I)->getDeclContext()->isFunctionOrMethod());
11719       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11720     }
11721   }
11722 #endif
11723 
11724   // It would be nice to avoid this copy.
11725   TemplateArgumentListInfo TABuffer;
11726   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11727   if (ULE->hasExplicitTemplateArgs()) {
11728     ULE->copyTemplateArgumentsInto(TABuffer);
11729     ExplicitTemplateArgs = &TABuffer;
11730   }
11731 
11732   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11733          E = ULE->decls_end(); I != E; ++I)
11734     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11735                                CandidateSet, PartialOverloading,
11736                                /*KnownValid*/ true);
11737 
11738   if (ULE->requiresADL())
11739     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11740                                          Args, ExplicitTemplateArgs,
11741                                          CandidateSet, PartialOverloading);
11742 }
11743 
11744 /// Determine whether a declaration with the specified name could be moved into
11745 /// a different namespace.
11746 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11747   switch (Name.getCXXOverloadedOperator()) {
11748   case OO_New: case OO_Array_New:
11749   case OO_Delete: case OO_Array_Delete:
11750     return false;
11751 
11752   default:
11753     return true;
11754   }
11755 }
11756 
11757 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11758 /// template, where the non-dependent name was declared after the template
11759 /// was defined. This is common in code written for a compilers which do not
11760 /// correctly implement two-stage name lookup.
11761 ///
11762 /// Returns true if a viable candidate was found and a diagnostic was issued.
11763 static bool
11764 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11765                        const CXXScopeSpec &SS, LookupResult &R,
11766                        OverloadCandidateSet::CandidateSetKind CSK,
11767                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11768                        ArrayRef<Expr *> Args,
11769                        bool *DoDiagnoseEmptyLookup = nullptr) {
11770   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11771     return false;
11772 
11773   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11774     if (DC->isTransparentContext())
11775       continue;
11776 
11777     SemaRef.LookupQualifiedName(R, DC);
11778 
11779     if (!R.empty()) {
11780       R.suppressDiagnostics();
11781 
11782       if (isa<CXXRecordDecl>(DC)) {
11783         // Don't diagnose names we find in classes; we get much better
11784         // diagnostics for these from DiagnoseEmptyLookup.
11785         R.clear();
11786         if (DoDiagnoseEmptyLookup)
11787           *DoDiagnoseEmptyLookup = true;
11788         return false;
11789       }
11790 
11791       OverloadCandidateSet Candidates(FnLoc, CSK);
11792       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11793         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11794                                    ExplicitTemplateArgs, Args,
11795                                    Candidates, false, /*KnownValid*/ false);
11796 
11797       OverloadCandidateSet::iterator Best;
11798       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11799         // No viable functions. Don't bother the user with notes for functions
11800         // which don't work and shouldn't be found anyway.
11801         R.clear();
11802         return false;
11803       }
11804 
11805       // Find the namespaces where ADL would have looked, and suggest
11806       // declaring the function there instead.
11807       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11808       Sema::AssociatedClassSet AssociatedClasses;
11809       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11810                                                  AssociatedNamespaces,
11811                                                  AssociatedClasses);
11812       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11813       if (canBeDeclaredInNamespace(R.getLookupName())) {
11814         DeclContext *Std = SemaRef.getStdNamespace();
11815         for (Sema::AssociatedNamespaceSet::iterator
11816                it = AssociatedNamespaces.begin(),
11817                end = AssociatedNamespaces.end(); it != end; ++it) {
11818           // Never suggest declaring a function within namespace 'std'.
11819           if (Std && Std->Encloses(*it))
11820             continue;
11821 
11822           // Never suggest declaring a function within a namespace with a
11823           // reserved name, like __gnu_cxx.
11824           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11825           if (NS &&
11826               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11827             continue;
11828 
11829           SuggestedNamespaces.insert(*it);
11830         }
11831       }
11832 
11833       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11834         << R.getLookupName();
11835       if (SuggestedNamespaces.empty()) {
11836         SemaRef.Diag(Best->Function->getLocation(),
11837                      diag::note_not_found_by_two_phase_lookup)
11838           << R.getLookupName() << 0;
11839       } else if (SuggestedNamespaces.size() == 1) {
11840         SemaRef.Diag(Best->Function->getLocation(),
11841                      diag::note_not_found_by_two_phase_lookup)
11842           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11843       } else {
11844         // FIXME: It would be useful to list the associated namespaces here,
11845         // but the diagnostics infrastructure doesn't provide a way to produce
11846         // a localized representation of a list of items.
11847         SemaRef.Diag(Best->Function->getLocation(),
11848                      diag::note_not_found_by_two_phase_lookup)
11849           << R.getLookupName() << 2;
11850       }
11851 
11852       // Try to recover by calling this function.
11853       return true;
11854     }
11855 
11856     R.clear();
11857   }
11858 
11859   return false;
11860 }
11861 
11862 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11863 /// template, where the non-dependent operator was declared after the template
11864 /// was defined.
11865 ///
11866 /// Returns true if a viable candidate was found and a diagnostic was issued.
11867 static bool
11868 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11869                                SourceLocation OpLoc,
11870                                ArrayRef<Expr *> Args) {
11871   DeclarationName OpName =
11872     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11873   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11874   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11875                                 OverloadCandidateSet::CSK_Operator,
11876                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11877 }
11878 
11879 namespace {
11880 class BuildRecoveryCallExprRAII {
11881   Sema &SemaRef;
11882 public:
11883   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11884     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11885     SemaRef.IsBuildingRecoveryCallExpr = true;
11886   }
11887 
11888   ~BuildRecoveryCallExprRAII() {
11889     SemaRef.IsBuildingRecoveryCallExpr = false;
11890   }
11891 };
11892 
11893 }
11894 
11895 static std::unique_ptr<CorrectionCandidateCallback>
11896 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11897               bool HasTemplateArgs, bool AllowTypoCorrection) {
11898   if (!AllowTypoCorrection)
11899     return llvm::make_unique<NoTypoCorrectionCCC>();
11900   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11901                                                   HasTemplateArgs, ME);
11902 }
11903 
11904 /// Attempts to recover from a call where no functions were found.
11905 ///
11906 /// Returns true if new candidates were found.
11907 static ExprResult
11908 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11909                       UnresolvedLookupExpr *ULE,
11910                       SourceLocation LParenLoc,
11911                       MutableArrayRef<Expr *> Args,
11912                       SourceLocation RParenLoc,
11913                       bool EmptyLookup, bool AllowTypoCorrection) {
11914   // Do not try to recover if it is already building a recovery call.
11915   // This stops infinite loops for template instantiations like
11916   //
11917   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11918   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11919   //
11920   if (SemaRef.IsBuildingRecoveryCallExpr)
11921     return ExprError();
11922   BuildRecoveryCallExprRAII RCE(SemaRef);
11923 
11924   CXXScopeSpec SS;
11925   SS.Adopt(ULE->getQualifierLoc());
11926   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11927 
11928   TemplateArgumentListInfo TABuffer;
11929   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11930   if (ULE->hasExplicitTemplateArgs()) {
11931     ULE->copyTemplateArgumentsInto(TABuffer);
11932     ExplicitTemplateArgs = &TABuffer;
11933   }
11934 
11935   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11936                  Sema::LookupOrdinaryName);
11937   bool DoDiagnoseEmptyLookup = EmptyLookup;
11938   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11939                               OverloadCandidateSet::CSK_Normal,
11940                               ExplicitTemplateArgs, Args,
11941                               &DoDiagnoseEmptyLookup) &&
11942     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11943         S, SS, R,
11944         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11945                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11946         ExplicitTemplateArgs, Args)))
11947     return ExprError();
11948 
11949   assert(!R.empty() && "lookup results empty despite recovery");
11950 
11951   // If recovery created an ambiguity, just bail out.
11952   if (R.isAmbiguous()) {
11953     R.suppressDiagnostics();
11954     return ExprError();
11955   }
11956 
11957   // Build an implicit member call if appropriate.  Just drop the
11958   // casts and such from the call, we don't really care.
11959   ExprResult NewFn = ExprError();
11960   if ((*R.begin())->isCXXClassMember())
11961     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11962                                                     ExplicitTemplateArgs, S);
11963   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11964     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11965                                         ExplicitTemplateArgs);
11966   else
11967     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11968 
11969   if (NewFn.isInvalid())
11970     return ExprError();
11971 
11972   // This shouldn't cause an infinite loop because we're giving it
11973   // an expression with viable lookup results, which should never
11974   // end up here.
11975   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11976                                MultiExprArg(Args.data(), Args.size()),
11977                                RParenLoc);
11978 }
11979 
11980 /// Constructs and populates an OverloadedCandidateSet from
11981 /// the given function.
11982 /// \returns true when an the ExprResult output parameter has been set.
11983 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11984                                   UnresolvedLookupExpr *ULE,
11985                                   MultiExprArg Args,
11986                                   SourceLocation RParenLoc,
11987                                   OverloadCandidateSet *CandidateSet,
11988                                   ExprResult *Result) {
11989 #ifndef NDEBUG
11990   if (ULE->requiresADL()) {
11991     // To do ADL, we must have found an unqualified name.
11992     assert(!ULE->getQualifier() && "qualified name with ADL");
11993 
11994     // We don't perform ADL for implicit declarations of builtins.
11995     // Verify that this was correctly set up.
11996     FunctionDecl *F;
11997     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11998         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11999         F->getBuiltinID() && F->isImplicit())
12000       llvm_unreachable("performing ADL for builtin");
12001 
12002     // We don't perform ADL in C.
12003     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12004   }
12005 #endif
12006 
12007   UnbridgedCastsSet UnbridgedCasts;
12008   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12009     *Result = ExprError();
12010     return true;
12011   }
12012 
12013   // Add the functions denoted by the callee to the set of candidate
12014   // functions, including those from argument-dependent lookup.
12015   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12016 
12017   if (getLangOpts().MSVCCompat &&
12018       CurContext->isDependentContext() && !isSFINAEContext() &&
12019       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12020 
12021     OverloadCandidateSet::iterator Best;
12022     if (CandidateSet->empty() ||
12023         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12024             OR_No_Viable_Function) {
12025       // In Microsoft mode, if we are inside a template class member function
12026       // then create a type dependent CallExpr. The goal is to postpone name
12027       // lookup to instantiation time to be able to search into type dependent
12028       // base classes.
12029       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12030                                       VK_RValue, RParenLoc);
12031       CE->setTypeDependent(true);
12032       CE->setValueDependent(true);
12033       CE->setInstantiationDependent(true);
12034       *Result = CE;
12035       return true;
12036     }
12037   }
12038 
12039   if (CandidateSet->empty())
12040     return false;
12041 
12042   UnbridgedCasts.restore();
12043   return false;
12044 }
12045 
12046 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12047 /// the completed call expression. If overload resolution fails, emits
12048 /// diagnostics and returns ExprError()
12049 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12050                                            UnresolvedLookupExpr *ULE,
12051                                            SourceLocation LParenLoc,
12052                                            MultiExprArg Args,
12053                                            SourceLocation RParenLoc,
12054                                            Expr *ExecConfig,
12055                                            OverloadCandidateSet *CandidateSet,
12056                                            OverloadCandidateSet::iterator *Best,
12057                                            OverloadingResult OverloadResult,
12058                                            bool AllowTypoCorrection) {
12059   if (CandidateSet->empty())
12060     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12061                                  RParenLoc, /*EmptyLookup=*/true,
12062                                  AllowTypoCorrection);
12063 
12064   switch (OverloadResult) {
12065   case OR_Success: {
12066     FunctionDecl *FDecl = (*Best)->Function;
12067     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12068     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12069       return ExprError();
12070     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12071     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12072                                          ExecConfig, /*IsExecConfig=*/false,
12073                                          (*Best)->IsADLCandidate);
12074   }
12075 
12076   case OR_No_Viable_Function: {
12077     // Try to recover by looking for viable functions which the user might
12078     // have meant to call.
12079     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12080                                                 Args, RParenLoc,
12081                                                 /*EmptyLookup=*/false,
12082                                                 AllowTypoCorrection);
12083     if (!Recovery.isInvalid())
12084       return Recovery;
12085 
12086     // If the user passes in a function that we can't take the address of, we
12087     // generally end up emitting really bad error messages. Here, we attempt to
12088     // emit better ones.
12089     for (const Expr *Arg : Args) {
12090       if (!Arg->getType()->isFunctionType())
12091         continue;
12092       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12093         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12094         if (FD &&
12095             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12096                                                        Arg->getExprLoc()))
12097           return ExprError();
12098       }
12099     }
12100 
12101     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12102         << ULE->getName() << Fn->getSourceRange();
12103     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12104     break;
12105   }
12106 
12107   case OR_Ambiguous:
12108     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12109         << ULE->getName() << Fn->getSourceRange();
12110     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12111     break;
12112 
12113   case OR_Deleted: {
12114     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12115         << ULE->getName() << Fn->getSourceRange();
12116     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12117 
12118     // We emitted an error for the unavailable/deleted function call but keep
12119     // the call in the AST.
12120     FunctionDecl *FDecl = (*Best)->Function;
12121     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12122     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12123                                          ExecConfig, /*IsExecConfig=*/false,
12124                                          (*Best)->IsADLCandidate);
12125   }
12126   }
12127 
12128   // Overload resolution failed.
12129   return ExprError();
12130 }
12131 
12132 static void markUnaddressableCandidatesUnviable(Sema &S,
12133                                                 OverloadCandidateSet &CS) {
12134   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12135     if (I->Viable &&
12136         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12137       I->Viable = false;
12138       I->FailureKind = ovl_fail_addr_not_available;
12139     }
12140   }
12141 }
12142 
12143 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12144 /// (which eventually refers to the declaration Func) and the call
12145 /// arguments Args/NumArgs, attempt to resolve the function call down
12146 /// to a specific function. If overload resolution succeeds, returns
12147 /// the call expression produced by overload resolution.
12148 /// Otherwise, emits diagnostics and returns ExprError.
12149 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12150                                          UnresolvedLookupExpr *ULE,
12151                                          SourceLocation LParenLoc,
12152                                          MultiExprArg Args,
12153                                          SourceLocation RParenLoc,
12154                                          Expr *ExecConfig,
12155                                          bool AllowTypoCorrection,
12156                                          bool CalleesAddressIsTaken) {
12157   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12158                                     OverloadCandidateSet::CSK_Normal);
12159   ExprResult result;
12160 
12161   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12162                              &result))
12163     return result;
12164 
12165   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12166   // functions that aren't addressible are considered unviable.
12167   if (CalleesAddressIsTaken)
12168     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12169 
12170   OverloadCandidateSet::iterator Best;
12171   OverloadingResult OverloadResult =
12172       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12173 
12174   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12175                                   RParenLoc, ExecConfig, &CandidateSet,
12176                                   &Best, OverloadResult,
12177                                   AllowTypoCorrection);
12178 }
12179 
12180 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12181   return Functions.size() > 1 ||
12182     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12183 }
12184 
12185 /// Create a unary operation that may resolve to an overloaded
12186 /// operator.
12187 ///
12188 /// \param OpLoc The location of the operator itself (e.g., '*').
12189 ///
12190 /// \param Opc The UnaryOperatorKind that describes this operator.
12191 ///
12192 /// \param Fns The set of non-member functions that will be
12193 /// considered by overload resolution. The caller needs to build this
12194 /// set based on the context using, e.g.,
12195 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12196 /// set should not contain any member functions; those will be added
12197 /// by CreateOverloadedUnaryOp().
12198 ///
12199 /// \param Input The input argument.
12200 ExprResult
12201 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12202                               const UnresolvedSetImpl &Fns,
12203                               Expr *Input, bool PerformADL) {
12204   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12205   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12206   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12207   // TODO: provide better source location info.
12208   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12209 
12210   if (checkPlaceholderForOverload(*this, Input))
12211     return ExprError();
12212 
12213   Expr *Args[2] = { Input, nullptr };
12214   unsigned NumArgs = 1;
12215 
12216   // For post-increment and post-decrement, add the implicit '0' as
12217   // the second argument, so that we know this is a post-increment or
12218   // post-decrement.
12219   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12220     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12221     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12222                                      SourceLocation());
12223     NumArgs = 2;
12224   }
12225 
12226   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12227 
12228   if (Input->isTypeDependent()) {
12229     if (Fns.empty())
12230       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12231                                          VK_RValue, OK_Ordinary, OpLoc, false);
12232 
12233     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12234     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12235         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12236         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12237     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12238                                        Context.DependentTy, VK_RValue, OpLoc,
12239                                        FPOptions());
12240   }
12241 
12242   // Build an empty overload set.
12243   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12244 
12245   // Add the candidates from the given function set.
12246   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12247 
12248   // Add operator candidates that are member functions.
12249   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12250 
12251   // Add candidates from ADL.
12252   if (PerformADL) {
12253     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12254                                          /*ExplicitTemplateArgs*/nullptr,
12255                                          CandidateSet);
12256   }
12257 
12258   // Add builtin operator candidates.
12259   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12260 
12261   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12262 
12263   // Perform overload resolution.
12264   OverloadCandidateSet::iterator Best;
12265   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12266   case OR_Success: {
12267     // We found a built-in operator or an overloaded operator.
12268     FunctionDecl *FnDecl = Best->Function;
12269 
12270     if (FnDecl) {
12271       Expr *Base = nullptr;
12272       // We matched an overloaded operator. Build a call to that
12273       // operator.
12274 
12275       // Convert the arguments.
12276       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12277         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12278 
12279         ExprResult InputRes =
12280           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12281                                               Best->FoundDecl, Method);
12282         if (InputRes.isInvalid())
12283           return ExprError();
12284         Base = Input = InputRes.get();
12285       } else {
12286         // Convert the arguments.
12287         ExprResult InputInit
12288           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12289                                                       Context,
12290                                                       FnDecl->getParamDecl(0)),
12291                                       SourceLocation(),
12292                                       Input);
12293         if (InputInit.isInvalid())
12294           return ExprError();
12295         Input = InputInit.get();
12296       }
12297 
12298       // Build the actual expression node.
12299       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12300                                                 Base, HadMultipleCandidates,
12301                                                 OpLoc);
12302       if (FnExpr.isInvalid())
12303         return ExprError();
12304 
12305       // Determine the result type.
12306       QualType ResultTy = FnDecl->getReturnType();
12307       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12308       ResultTy = ResultTy.getNonLValueExprType(Context);
12309 
12310       Args[0] = Input;
12311       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12312           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12313           FPOptions(), Best->IsADLCandidate);
12314 
12315       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12316         return ExprError();
12317 
12318       if (CheckFunctionCall(FnDecl, TheCall,
12319                             FnDecl->getType()->castAs<FunctionProtoType>()))
12320         return ExprError();
12321 
12322       return MaybeBindToTemporary(TheCall);
12323     } else {
12324       // We matched a built-in operator. Convert the arguments, then
12325       // break out so that we will build the appropriate built-in
12326       // operator node.
12327       ExprResult InputRes = PerformImplicitConversion(
12328           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12329           CCK_ForBuiltinOverloadedOp);
12330       if (InputRes.isInvalid())
12331         return ExprError();
12332       Input = InputRes.get();
12333       break;
12334     }
12335   }
12336 
12337   case OR_No_Viable_Function:
12338     // This is an erroneous use of an operator which can be overloaded by
12339     // a non-member function. Check for non-member operators which were
12340     // defined too late to be candidates.
12341     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12342       // FIXME: Recover by calling the found function.
12343       return ExprError();
12344 
12345     // No viable function; fall through to handling this as a
12346     // built-in operator, which will produce an error message for us.
12347     break;
12348 
12349   case OR_Ambiguous:
12350     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12351         << UnaryOperator::getOpcodeStr(Opc)
12352         << Input->getType()
12353         << Input->getSourceRange();
12354     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12355                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12356     return ExprError();
12357 
12358   case OR_Deleted:
12359     Diag(OpLoc, diag::err_ovl_deleted_oper)
12360         << UnaryOperator::getOpcodeStr(Opc) << Input->getSourceRange();
12361     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12362                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12363     return ExprError();
12364   }
12365 
12366   // Either we found no viable overloaded operator or we matched a
12367   // built-in operator. In either case, fall through to trying to
12368   // build a built-in operation.
12369   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12370 }
12371 
12372 /// Create a binary operation that may resolve to an overloaded
12373 /// operator.
12374 ///
12375 /// \param OpLoc The location of the operator itself (e.g., '+').
12376 ///
12377 /// \param Opc The BinaryOperatorKind that describes this operator.
12378 ///
12379 /// \param Fns The set of non-member functions that will be
12380 /// considered by overload resolution. The caller needs to build this
12381 /// set based on the context using, e.g.,
12382 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12383 /// set should not contain any member functions; those will be added
12384 /// by CreateOverloadedBinOp().
12385 ///
12386 /// \param LHS Left-hand argument.
12387 /// \param RHS Right-hand argument.
12388 ExprResult
12389 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12390                             BinaryOperatorKind Opc,
12391                             const UnresolvedSetImpl &Fns,
12392                             Expr *LHS, Expr *RHS, bool PerformADL) {
12393   Expr *Args[2] = { LHS, RHS };
12394   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12395 
12396   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12397   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12398 
12399   // If either side is type-dependent, create an appropriate dependent
12400   // expression.
12401   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12402     if (Fns.empty()) {
12403       // If there are no functions to store, just build a dependent
12404       // BinaryOperator or CompoundAssignment.
12405       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12406         return new (Context) BinaryOperator(
12407             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12408             OpLoc, FPFeatures);
12409 
12410       return new (Context) CompoundAssignOperator(
12411           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12412           Context.DependentTy, Context.DependentTy, OpLoc,
12413           FPFeatures);
12414     }
12415 
12416     // FIXME: save results of ADL from here?
12417     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12418     // TODO: provide better source location info in DNLoc component.
12419     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12420     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12421         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12422         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12423     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12424                                        Context.DependentTy, VK_RValue, OpLoc,
12425                                        FPFeatures);
12426   }
12427 
12428   // Always do placeholder-like conversions on the RHS.
12429   if (checkPlaceholderForOverload(*this, Args[1]))
12430     return ExprError();
12431 
12432   // Do placeholder-like conversion on the LHS; note that we should
12433   // not get here with a PseudoObject LHS.
12434   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12435   if (checkPlaceholderForOverload(*this, Args[0]))
12436     return ExprError();
12437 
12438   // If this is the assignment operator, we only perform overload resolution
12439   // if the left-hand side is a class or enumeration type. This is actually
12440   // a hack. The standard requires that we do overload resolution between the
12441   // various built-in candidates, but as DR507 points out, this can lead to
12442   // problems. So we do it this way, which pretty much follows what GCC does.
12443   // Note that we go the traditional code path for compound assignment forms.
12444   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12445     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12446 
12447   // If this is the .* operator, which is not overloadable, just
12448   // create a built-in binary operator.
12449   if (Opc == BO_PtrMemD)
12450     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12451 
12452   // Build an empty overload set.
12453   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12454 
12455   // Add the candidates from the given function set.
12456   AddFunctionCandidates(Fns, Args, CandidateSet);
12457 
12458   // Add operator candidates that are member functions.
12459   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12460 
12461   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12462   // performed for an assignment operator (nor for operator[] nor operator->,
12463   // which don't get here).
12464   if (Opc != BO_Assign && PerformADL)
12465     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12466                                          /*ExplicitTemplateArgs*/ nullptr,
12467                                          CandidateSet);
12468 
12469   // Add builtin operator candidates.
12470   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12471 
12472   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12473 
12474   // Perform overload resolution.
12475   OverloadCandidateSet::iterator Best;
12476   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12477     case OR_Success: {
12478       // We found a built-in operator or an overloaded operator.
12479       FunctionDecl *FnDecl = Best->Function;
12480 
12481       if (FnDecl) {
12482         Expr *Base = nullptr;
12483         // We matched an overloaded operator. Build a call to that
12484         // operator.
12485 
12486         // Convert the arguments.
12487         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12488           // Best->Access is only meaningful for class members.
12489           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12490 
12491           ExprResult Arg1 =
12492             PerformCopyInitialization(
12493               InitializedEntity::InitializeParameter(Context,
12494                                                      FnDecl->getParamDecl(0)),
12495               SourceLocation(), Args[1]);
12496           if (Arg1.isInvalid())
12497             return ExprError();
12498 
12499           ExprResult Arg0 =
12500             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12501                                                 Best->FoundDecl, Method);
12502           if (Arg0.isInvalid())
12503             return ExprError();
12504           Base = Args[0] = Arg0.getAs<Expr>();
12505           Args[1] = RHS = Arg1.getAs<Expr>();
12506         } else {
12507           // Convert the arguments.
12508           ExprResult Arg0 = PerformCopyInitialization(
12509             InitializedEntity::InitializeParameter(Context,
12510                                                    FnDecl->getParamDecl(0)),
12511             SourceLocation(), Args[0]);
12512           if (Arg0.isInvalid())
12513             return ExprError();
12514 
12515           ExprResult Arg1 =
12516             PerformCopyInitialization(
12517               InitializedEntity::InitializeParameter(Context,
12518                                                      FnDecl->getParamDecl(1)),
12519               SourceLocation(), Args[1]);
12520           if (Arg1.isInvalid())
12521             return ExprError();
12522           Args[0] = LHS = Arg0.getAs<Expr>();
12523           Args[1] = RHS = Arg1.getAs<Expr>();
12524         }
12525 
12526         // Build the actual expression node.
12527         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12528                                                   Best->FoundDecl, Base,
12529                                                   HadMultipleCandidates, OpLoc);
12530         if (FnExpr.isInvalid())
12531           return ExprError();
12532 
12533         // Determine the result type.
12534         QualType ResultTy = FnDecl->getReturnType();
12535         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12536         ResultTy = ResultTy.getNonLValueExprType(Context);
12537 
12538         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12539             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12540             Best->IsADLCandidate);
12541 
12542         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12543                                 FnDecl))
12544           return ExprError();
12545 
12546         ArrayRef<const Expr *> ArgsArray(Args, 2);
12547         const Expr *ImplicitThis = nullptr;
12548         // Cut off the implicit 'this'.
12549         if (isa<CXXMethodDecl>(FnDecl)) {
12550           ImplicitThis = ArgsArray[0];
12551           ArgsArray = ArgsArray.slice(1);
12552         }
12553 
12554         // Check for a self move.
12555         if (Op == OO_Equal)
12556           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12557 
12558         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12559                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12560                   VariadicDoesNotApply);
12561 
12562         return MaybeBindToTemporary(TheCall);
12563       } else {
12564         // We matched a built-in operator. Convert the arguments, then
12565         // break out so that we will build the appropriate built-in
12566         // operator node.
12567         ExprResult ArgsRes0 = PerformImplicitConversion(
12568             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12569             AA_Passing, CCK_ForBuiltinOverloadedOp);
12570         if (ArgsRes0.isInvalid())
12571           return ExprError();
12572         Args[0] = ArgsRes0.get();
12573 
12574         ExprResult ArgsRes1 = PerformImplicitConversion(
12575             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12576             AA_Passing, CCK_ForBuiltinOverloadedOp);
12577         if (ArgsRes1.isInvalid())
12578           return ExprError();
12579         Args[1] = ArgsRes1.get();
12580         break;
12581       }
12582     }
12583 
12584     case OR_No_Viable_Function: {
12585       // C++ [over.match.oper]p9:
12586       //   If the operator is the operator , [...] and there are no
12587       //   viable functions, then the operator is assumed to be the
12588       //   built-in operator and interpreted according to clause 5.
12589       if (Opc == BO_Comma)
12590         break;
12591 
12592       // For class as left operand for assignment or compound assignment
12593       // operator do not fall through to handling in built-in, but report that
12594       // no overloaded assignment operator found
12595       ExprResult Result = ExprError();
12596       if (Args[0]->getType()->isRecordType() &&
12597           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12598         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12599              << BinaryOperator::getOpcodeStr(Opc)
12600              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12601         if (Args[0]->getType()->isIncompleteType()) {
12602           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12603             << Args[0]->getType()
12604             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12605         }
12606       } else {
12607         // This is an erroneous use of an operator which can be overloaded by
12608         // a non-member function. Check for non-member operators which were
12609         // defined too late to be candidates.
12610         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12611           // FIXME: Recover by calling the found function.
12612           return ExprError();
12613 
12614         // No viable function; try to create a built-in operation, which will
12615         // produce an error. Then, show the non-viable candidates.
12616         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12617       }
12618       assert(Result.isInvalid() &&
12619              "C++ binary operator overloading is missing candidates!");
12620       if (Result.isInvalid())
12621         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12622                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12623       return Result;
12624     }
12625 
12626     case OR_Ambiguous:
12627       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12628           << BinaryOperator::getOpcodeStr(Opc)
12629           << Args[0]->getType() << Args[1]->getType()
12630           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12631       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12632                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12633       return ExprError();
12634 
12635     case OR_Deleted:
12636       if (isImplicitlyDeleted(Best->Function)) {
12637         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12638         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12639           << Context.getRecordType(Method->getParent())
12640           << getSpecialMember(Method);
12641 
12642         // The user probably meant to call this special member. Just
12643         // explain why it's deleted.
12644         NoteDeletedFunction(Method);
12645         return ExprError();
12646       } else {
12647         Diag(OpLoc, diag::err_ovl_deleted_oper)
12648             << BinaryOperator::getOpcodeStr(Opc) << Args[0]->getSourceRange()
12649             << Args[1]->getSourceRange();
12650       }
12651       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12652                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12653       return ExprError();
12654   }
12655 
12656   // We matched a built-in operator; build it.
12657   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12658 }
12659 
12660 ExprResult
12661 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12662                                          SourceLocation RLoc,
12663                                          Expr *Base, Expr *Idx) {
12664   Expr *Args[2] = { Base, Idx };
12665   DeclarationName OpName =
12666       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12667 
12668   // If either side is type-dependent, create an appropriate dependent
12669   // expression.
12670   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12671 
12672     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12673     // CHECKME: no 'operator' keyword?
12674     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12675     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12676     UnresolvedLookupExpr *Fn
12677       = UnresolvedLookupExpr::Create(Context, NamingClass,
12678                                      NestedNameSpecifierLoc(), OpNameInfo,
12679                                      /*ADL*/ true, /*Overloaded*/ false,
12680                                      UnresolvedSetIterator(),
12681                                      UnresolvedSetIterator());
12682     // Can't add any actual overloads yet
12683 
12684     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12685                                        Context.DependentTy, VK_RValue, RLoc,
12686                                        FPOptions());
12687   }
12688 
12689   // Handle placeholders on both operands.
12690   if (checkPlaceholderForOverload(*this, Args[0]))
12691     return ExprError();
12692   if (checkPlaceholderForOverload(*this, Args[1]))
12693     return ExprError();
12694 
12695   // Build an empty overload set.
12696   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12697 
12698   // Subscript can only be overloaded as a member function.
12699 
12700   // Add operator candidates that are member functions.
12701   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12702 
12703   // Add builtin operator candidates.
12704   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12705 
12706   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12707 
12708   // Perform overload resolution.
12709   OverloadCandidateSet::iterator Best;
12710   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12711     case OR_Success: {
12712       // We found a built-in operator or an overloaded operator.
12713       FunctionDecl *FnDecl = Best->Function;
12714 
12715       if (FnDecl) {
12716         // We matched an overloaded operator. Build a call to that
12717         // operator.
12718 
12719         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12720 
12721         // Convert the arguments.
12722         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12723         ExprResult Arg0 =
12724           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12725                                               Best->FoundDecl, Method);
12726         if (Arg0.isInvalid())
12727           return ExprError();
12728         Args[0] = Arg0.get();
12729 
12730         // Convert the arguments.
12731         ExprResult InputInit
12732           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12733                                                       Context,
12734                                                       FnDecl->getParamDecl(0)),
12735                                       SourceLocation(),
12736                                       Args[1]);
12737         if (InputInit.isInvalid())
12738           return ExprError();
12739 
12740         Args[1] = InputInit.getAs<Expr>();
12741 
12742         // Build the actual expression node.
12743         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12744         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12745         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12746                                                   Best->FoundDecl,
12747                                                   Base,
12748                                                   HadMultipleCandidates,
12749                                                   OpLocInfo.getLoc(),
12750                                                   OpLocInfo.getInfo());
12751         if (FnExpr.isInvalid())
12752           return ExprError();
12753 
12754         // Determine the result type
12755         QualType ResultTy = FnDecl->getReturnType();
12756         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12757         ResultTy = ResultTy.getNonLValueExprType(Context);
12758 
12759         CXXOperatorCallExpr *TheCall =
12760             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12761                                         Args, ResultTy, VK, RLoc, FPOptions());
12762 
12763         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12764           return ExprError();
12765 
12766         if (CheckFunctionCall(Method, TheCall,
12767                               Method->getType()->castAs<FunctionProtoType>()))
12768           return ExprError();
12769 
12770         return MaybeBindToTemporary(TheCall);
12771       } else {
12772         // We matched a built-in operator. Convert the arguments, then
12773         // break out so that we will build the appropriate built-in
12774         // operator node.
12775         ExprResult ArgsRes0 = PerformImplicitConversion(
12776             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12777             AA_Passing, CCK_ForBuiltinOverloadedOp);
12778         if (ArgsRes0.isInvalid())
12779           return ExprError();
12780         Args[0] = ArgsRes0.get();
12781 
12782         ExprResult ArgsRes1 = PerformImplicitConversion(
12783             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12784             AA_Passing, CCK_ForBuiltinOverloadedOp);
12785         if (ArgsRes1.isInvalid())
12786           return ExprError();
12787         Args[1] = ArgsRes1.get();
12788 
12789         break;
12790       }
12791     }
12792 
12793     case OR_No_Viable_Function: {
12794       if (CandidateSet.empty())
12795         Diag(LLoc, diag::err_ovl_no_oper)
12796           << Args[0]->getType() << /*subscript*/ 0
12797           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12798       else
12799         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12800           << Args[0]->getType()
12801           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12802       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12803                                   "[]", LLoc);
12804       return ExprError();
12805     }
12806 
12807     case OR_Ambiguous:
12808       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12809           << "[]"
12810           << Args[0]->getType() << Args[1]->getType()
12811           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12812       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12813                                   "[]", LLoc);
12814       return ExprError();
12815 
12816     case OR_Deleted:
12817       Diag(LLoc, diag::err_ovl_deleted_oper)
12818           << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12819       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, "[]", LLoc);
12820       return ExprError();
12821     }
12822 
12823   // We matched a built-in operator; build it.
12824   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12825 }
12826 
12827 /// BuildCallToMemberFunction - Build a call to a member
12828 /// function. MemExpr is the expression that refers to the member
12829 /// function (and includes the object parameter), Args/NumArgs are the
12830 /// arguments to the function call (not including the object
12831 /// parameter). The caller needs to validate that the member
12832 /// expression refers to a non-static member function or an overloaded
12833 /// member function.
12834 ExprResult
12835 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12836                                 SourceLocation LParenLoc,
12837                                 MultiExprArg Args,
12838                                 SourceLocation RParenLoc) {
12839   assert(MemExprE->getType() == Context.BoundMemberTy ||
12840          MemExprE->getType() == Context.OverloadTy);
12841 
12842   // Dig out the member expression. This holds both the object
12843   // argument and the member function we're referring to.
12844   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12845 
12846   // Determine whether this is a call to a pointer-to-member function.
12847   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12848     assert(op->getType() == Context.BoundMemberTy);
12849     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12850 
12851     QualType fnType =
12852       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12853 
12854     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12855     QualType resultType = proto->getCallResultType(Context);
12856     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12857 
12858     // Check that the object type isn't more qualified than the
12859     // member function we're calling.
12860     Qualifiers funcQuals = proto->getMethodQuals();
12861 
12862     QualType objectType = op->getLHS()->getType();
12863     if (op->getOpcode() == BO_PtrMemI)
12864       objectType = objectType->castAs<PointerType>()->getPointeeType();
12865     Qualifiers objectQuals = objectType.getQualifiers();
12866 
12867     Qualifiers difference = objectQuals - funcQuals;
12868     difference.removeObjCGCAttr();
12869     difference.removeAddressSpace();
12870     if (difference) {
12871       std::string qualsString = difference.getAsString();
12872       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12873         << fnType.getUnqualifiedType()
12874         << qualsString
12875         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12876     }
12877 
12878     CXXMemberCallExpr *call =
12879         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12880                                   valueKind, RParenLoc, proto->getNumParams());
12881 
12882     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12883                             call, nullptr))
12884       return ExprError();
12885 
12886     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12887       return ExprError();
12888 
12889     if (CheckOtherCall(call, proto))
12890       return ExprError();
12891 
12892     return MaybeBindToTemporary(call);
12893   }
12894 
12895   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12896     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
12897                             RParenLoc);
12898 
12899   UnbridgedCastsSet UnbridgedCasts;
12900   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12901     return ExprError();
12902 
12903   MemberExpr *MemExpr;
12904   CXXMethodDecl *Method = nullptr;
12905   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12906   NestedNameSpecifier *Qualifier = nullptr;
12907   if (isa<MemberExpr>(NakedMemExpr)) {
12908     MemExpr = cast<MemberExpr>(NakedMemExpr);
12909     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12910     FoundDecl = MemExpr->getFoundDecl();
12911     Qualifier = MemExpr->getQualifier();
12912     UnbridgedCasts.restore();
12913   } else {
12914     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12915     Qualifier = UnresExpr->getQualifier();
12916 
12917     QualType ObjectType = UnresExpr->getBaseType();
12918     Expr::Classification ObjectClassification
12919       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12920                             : UnresExpr->getBase()->Classify(Context);
12921 
12922     // Add overload candidates
12923     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12924                                       OverloadCandidateSet::CSK_Normal);
12925 
12926     // FIXME: avoid copy.
12927     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12928     if (UnresExpr->hasExplicitTemplateArgs()) {
12929       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12930       TemplateArgs = &TemplateArgsBuffer;
12931     }
12932 
12933     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12934            E = UnresExpr->decls_end(); I != E; ++I) {
12935 
12936       NamedDecl *Func = *I;
12937       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12938       if (isa<UsingShadowDecl>(Func))
12939         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12940 
12941 
12942       // Microsoft supports direct constructor calls.
12943       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12944         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12945                              Args, CandidateSet);
12946       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12947         // If explicit template arguments were provided, we can't call a
12948         // non-template member function.
12949         if (TemplateArgs)
12950           continue;
12951 
12952         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12953                            ObjectClassification, Args, CandidateSet,
12954                            /*SuppressUserConversions=*/false);
12955       } else {
12956         AddMethodTemplateCandidate(
12957             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12958             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12959             /*SuppressUsedConversions=*/false);
12960       }
12961     }
12962 
12963     DeclarationName DeclName = UnresExpr->getMemberName();
12964 
12965     UnbridgedCasts.restore();
12966 
12967     OverloadCandidateSet::iterator Best;
12968     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12969                                             Best)) {
12970     case OR_Success:
12971       Method = cast<CXXMethodDecl>(Best->Function);
12972       FoundDecl = Best->FoundDecl;
12973       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12974       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12975         return ExprError();
12976       // If FoundDecl is different from Method (such as if one is a template
12977       // and the other a specialization), make sure DiagnoseUseOfDecl is
12978       // called on both.
12979       // FIXME: This would be more comprehensively addressed by modifying
12980       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12981       // being used.
12982       if (Method != FoundDecl.getDecl() &&
12983                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12984         return ExprError();
12985       break;
12986 
12987     case OR_No_Viable_Function:
12988       Diag(UnresExpr->getMemberLoc(),
12989            diag::err_ovl_no_viable_member_function_in_call)
12990         << DeclName << MemExprE->getSourceRange();
12991       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12992       // FIXME: Leaking incoming expressions!
12993       return ExprError();
12994 
12995     case OR_Ambiguous:
12996       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12997         << DeclName << MemExprE->getSourceRange();
12998       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12999       // FIXME: Leaking incoming expressions!
13000       return ExprError();
13001 
13002     case OR_Deleted:
13003       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
13004           << DeclName << MemExprE->getSourceRange();
13005       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13006       // FIXME: Leaking incoming expressions!
13007       return ExprError();
13008     }
13009 
13010     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13011 
13012     // If overload resolution picked a static member, build a
13013     // non-member call based on that function.
13014     if (Method->isStatic()) {
13015       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13016                                    RParenLoc);
13017     }
13018 
13019     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13020   }
13021 
13022   QualType ResultType = Method->getReturnType();
13023   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13024   ResultType = ResultType.getNonLValueExprType(Context);
13025 
13026   assert(Method && "Member call to something that isn't a method?");
13027   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13028   CXXMemberCallExpr *TheCall =
13029       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13030                                 RParenLoc, Proto->getNumParams());
13031 
13032   // Check for a valid return type.
13033   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13034                           TheCall, Method))
13035     return ExprError();
13036 
13037   // Convert the object argument (for a non-static member function call).
13038   // We only need to do this if there was actually an overload; otherwise
13039   // it was done at lookup.
13040   if (!Method->isStatic()) {
13041     ExprResult ObjectArg =
13042       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13043                                           FoundDecl, Method);
13044     if (ObjectArg.isInvalid())
13045       return ExprError();
13046     MemExpr->setBase(ObjectArg.get());
13047   }
13048 
13049   // Convert the rest of the arguments
13050   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13051                               RParenLoc))
13052     return ExprError();
13053 
13054   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13055 
13056   if (CheckFunctionCall(Method, TheCall, Proto))
13057     return ExprError();
13058 
13059   // In the case the method to call was not selected by the overloading
13060   // resolution process, we still need to handle the enable_if attribute. Do
13061   // that here, so it will not hide previous -- and more relevant -- errors.
13062   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13063     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13064       Diag(MemE->getMemberLoc(),
13065            diag::err_ovl_no_viable_member_function_in_call)
13066           << Method << Method->getSourceRange();
13067       Diag(Method->getLocation(),
13068            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13069           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13070       return ExprError();
13071     }
13072   }
13073 
13074   if ((isa<CXXConstructorDecl>(CurContext) ||
13075        isa<CXXDestructorDecl>(CurContext)) &&
13076       TheCall->getMethodDecl()->isPure()) {
13077     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13078 
13079     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13080         MemExpr->performsVirtualDispatch(getLangOpts())) {
13081       Diag(MemExpr->getBeginLoc(),
13082            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13083           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13084           << MD->getParent()->getDeclName();
13085 
13086       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13087       if (getLangOpts().AppleKext)
13088         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13089             << MD->getParent()->getDeclName() << MD->getDeclName();
13090     }
13091   }
13092 
13093   if (CXXDestructorDecl *DD =
13094           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13095     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13096     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13097     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13098                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13099                          MemExpr->getMemberLoc());
13100   }
13101 
13102   return MaybeBindToTemporary(TheCall);
13103 }
13104 
13105 /// BuildCallToObjectOfClassType - Build a call to an object of class
13106 /// type (C++ [over.call.object]), which can end up invoking an
13107 /// overloaded function call operator (@c operator()) or performing a
13108 /// user-defined conversion on the object argument.
13109 ExprResult
13110 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13111                                    SourceLocation LParenLoc,
13112                                    MultiExprArg Args,
13113                                    SourceLocation RParenLoc) {
13114   if (checkPlaceholderForOverload(*this, Obj))
13115     return ExprError();
13116   ExprResult Object = Obj;
13117 
13118   UnbridgedCastsSet UnbridgedCasts;
13119   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13120     return ExprError();
13121 
13122   assert(Object.get()->getType()->isRecordType() &&
13123          "Requires object type argument");
13124   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13125 
13126   // C++ [over.call.object]p1:
13127   //  If the primary-expression E in the function call syntax
13128   //  evaluates to a class object of type "cv T", then the set of
13129   //  candidate functions includes at least the function call
13130   //  operators of T. The function call operators of T are obtained by
13131   //  ordinary lookup of the name operator() in the context of
13132   //  (E).operator().
13133   OverloadCandidateSet CandidateSet(LParenLoc,
13134                                     OverloadCandidateSet::CSK_Operator);
13135   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13136 
13137   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13138                           diag::err_incomplete_object_call, Object.get()))
13139     return true;
13140 
13141   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13142   LookupQualifiedName(R, Record->getDecl());
13143   R.suppressDiagnostics();
13144 
13145   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13146        Oper != OperEnd; ++Oper) {
13147     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13148                        Object.get()->Classify(Context), Args, CandidateSet,
13149                        /*SuppressUserConversions=*/false);
13150   }
13151 
13152   // C++ [over.call.object]p2:
13153   //   In addition, for each (non-explicit in C++0x) conversion function
13154   //   declared in T of the form
13155   //
13156   //        operator conversion-type-id () cv-qualifier;
13157   //
13158   //   where cv-qualifier is the same cv-qualification as, or a
13159   //   greater cv-qualification than, cv, and where conversion-type-id
13160   //   denotes the type "pointer to function of (P1,...,Pn) returning
13161   //   R", or the type "reference to pointer to function of
13162   //   (P1,...,Pn) returning R", or the type "reference to function
13163   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13164   //   is also considered as a candidate function. Similarly,
13165   //   surrogate call functions are added to the set of candidate
13166   //   functions for each conversion function declared in an
13167   //   accessible base class provided the function is not hidden
13168   //   within T by another intervening declaration.
13169   const auto &Conversions =
13170       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13171   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13172     NamedDecl *D = *I;
13173     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13174     if (isa<UsingShadowDecl>(D))
13175       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13176 
13177     // Skip over templated conversion functions; they aren't
13178     // surrogates.
13179     if (isa<FunctionTemplateDecl>(D))
13180       continue;
13181 
13182     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13183     if (!Conv->isExplicit()) {
13184       // Strip the reference type (if any) and then the pointer type (if
13185       // any) to get down to what might be a function type.
13186       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13187       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13188         ConvType = ConvPtrType->getPointeeType();
13189 
13190       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13191       {
13192         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13193                               Object.get(), Args, CandidateSet);
13194       }
13195     }
13196   }
13197 
13198   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13199 
13200   // Perform overload resolution.
13201   OverloadCandidateSet::iterator Best;
13202   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13203                                           Best)) {
13204   case OR_Success:
13205     // Overload resolution succeeded; we'll build the appropriate call
13206     // below.
13207     break;
13208 
13209   case OR_No_Viable_Function:
13210     if (CandidateSet.empty())
13211       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13212           << Object.get()->getType() << /*call*/ 1
13213           << Object.get()->getSourceRange();
13214     else
13215       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13216           << Object.get()->getType() << Object.get()->getSourceRange();
13217     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13218     break;
13219 
13220   case OR_Ambiguous:
13221     Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13222         << Object.get()->getType() << Object.get()->getSourceRange();
13223     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13224     break;
13225 
13226   case OR_Deleted:
13227     Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13228         << Object.get()->getType() << Object.get()->getSourceRange();
13229     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13230     break;
13231   }
13232 
13233   if (Best == CandidateSet.end())
13234     return true;
13235 
13236   UnbridgedCasts.restore();
13237 
13238   if (Best->Function == nullptr) {
13239     // Since there is no function declaration, this is one of the
13240     // surrogate candidates. Dig out the conversion function.
13241     CXXConversionDecl *Conv
13242       = cast<CXXConversionDecl>(
13243                          Best->Conversions[0].UserDefined.ConversionFunction);
13244 
13245     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13246                               Best->FoundDecl);
13247     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13248       return ExprError();
13249     assert(Conv == Best->FoundDecl.getDecl() &&
13250              "Found Decl & conversion-to-functionptr should be same, right?!");
13251     // We selected one of the surrogate functions that converts the
13252     // object parameter to a function pointer. Perform the conversion
13253     // on the object argument, then let ActOnCallExpr finish the job.
13254 
13255     // Create an implicit member expr to refer to the conversion operator.
13256     // and then call it.
13257     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13258                                              Conv, HadMultipleCandidates);
13259     if (Call.isInvalid())
13260       return ExprError();
13261     // Record usage of conversion in an implicit cast.
13262     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13263                                     CK_UserDefinedConversion, Call.get(),
13264                                     nullptr, VK_RValue);
13265 
13266     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13267   }
13268 
13269   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13270 
13271   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13272   // that calls this method, using Object for the implicit object
13273   // parameter and passing along the remaining arguments.
13274   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13275 
13276   // An error diagnostic has already been printed when parsing the declaration.
13277   if (Method->isInvalidDecl())
13278     return ExprError();
13279 
13280   const FunctionProtoType *Proto =
13281     Method->getType()->getAs<FunctionProtoType>();
13282 
13283   unsigned NumParams = Proto->getNumParams();
13284 
13285   DeclarationNameInfo OpLocInfo(
13286                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13287   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13288   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13289                                            Obj, HadMultipleCandidates,
13290                                            OpLocInfo.getLoc(),
13291                                            OpLocInfo.getInfo());
13292   if (NewFn.isInvalid())
13293     return true;
13294 
13295   // The number of argument slots to allocate in the call. If we have default
13296   // arguments we need to allocate space for them as well. We additionally
13297   // need one more slot for the object parameter.
13298   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13299 
13300   // Build the full argument list for the method call (the implicit object
13301   // parameter is placed at the beginning of the list).
13302   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13303 
13304   bool IsError = false;
13305 
13306   // Initialize the implicit object parameter.
13307   ExprResult ObjRes =
13308     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13309                                         Best->FoundDecl, Method);
13310   if (ObjRes.isInvalid())
13311     IsError = true;
13312   else
13313     Object = ObjRes;
13314   MethodArgs[0] = Object.get();
13315 
13316   // Check the argument types.
13317   for (unsigned i = 0; i != NumParams; i++) {
13318     Expr *Arg;
13319     if (i < Args.size()) {
13320       Arg = Args[i];
13321 
13322       // Pass the argument.
13323 
13324       ExprResult InputInit
13325         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13326                                                     Context,
13327                                                     Method->getParamDecl(i)),
13328                                     SourceLocation(), Arg);
13329 
13330       IsError |= InputInit.isInvalid();
13331       Arg = InputInit.getAs<Expr>();
13332     } else {
13333       ExprResult DefArg
13334         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13335       if (DefArg.isInvalid()) {
13336         IsError = true;
13337         break;
13338       }
13339 
13340       Arg = DefArg.getAs<Expr>();
13341     }
13342 
13343     MethodArgs[i + 1] = Arg;
13344   }
13345 
13346   // If this is a variadic call, handle args passed through "...".
13347   if (Proto->isVariadic()) {
13348     // Promote the arguments (C99 6.5.2.2p7).
13349     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13350       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13351                                                         nullptr);
13352       IsError |= Arg.isInvalid();
13353       MethodArgs[i + 1] = Arg.get();
13354     }
13355   }
13356 
13357   if (IsError)
13358     return true;
13359 
13360   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13361 
13362   // Once we've built TheCall, all of the expressions are properly owned.
13363   QualType ResultTy = Method->getReturnType();
13364   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13365   ResultTy = ResultTy.getNonLValueExprType(Context);
13366 
13367   CXXOperatorCallExpr *TheCall =
13368       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13369                                   ResultTy, VK, RParenLoc, FPOptions());
13370 
13371   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13372     return true;
13373 
13374   if (CheckFunctionCall(Method, TheCall, Proto))
13375     return true;
13376 
13377   return MaybeBindToTemporary(TheCall);
13378 }
13379 
13380 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13381 ///  (if one exists), where @c Base is an expression of class type and
13382 /// @c Member is the name of the member we're trying to find.
13383 ExprResult
13384 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13385                                bool *NoArrowOperatorFound) {
13386   assert(Base->getType()->isRecordType() &&
13387          "left-hand side must have class type");
13388 
13389   if (checkPlaceholderForOverload(*this, Base))
13390     return ExprError();
13391 
13392   SourceLocation Loc = Base->getExprLoc();
13393 
13394   // C++ [over.ref]p1:
13395   //
13396   //   [...] An expression x->m is interpreted as (x.operator->())->m
13397   //   for a class object x of type T if T::operator->() exists and if
13398   //   the operator is selected as the best match function by the
13399   //   overload resolution mechanism (13.3).
13400   DeclarationName OpName =
13401     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13402   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13403   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13404 
13405   if (RequireCompleteType(Loc, Base->getType(),
13406                           diag::err_typecheck_incomplete_tag, Base))
13407     return ExprError();
13408 
13409   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13410   LookupQualifiedName(R, BaseRecord->getDecl());
13411   R.suppressDiagnostics();
13412 
13413   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13414        Oper != OperEnd; ++Oper) {
13415     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13416                        None, CandidateSet, /*SuppressUserConversions=*/false);
13417   }
13418 
13419   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13420 
13421   // Perform overload resolution.
13422   OverloadCandidateSet::iterator Best;
13423   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13424   case OR_Success:
13425     // Overload resolution succeeded; we'll build the call below.
13426     break;
13427 
13428   case OR_No_Viable_Function:
13429     if (CandidateSet.empty()) {
13430       QualType BaseType = Base->getType();
13431       if (NoArrowOperatorFound) {
13432         // Report this specific error to the caller instead of emitting a
13433         // diagnostic, as requested.
13434         *NoArrowOperatorFound = true;
13435         return ExprError();
13436       }
13437       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13438         << BaseType << Base->getSourceRange();
13439       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13440         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13441           << FixItHint::CreateReplacement(OpLoc, ".");
13442       }
13443     } else
13444       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13445         << "operator->" << Base->getSourceRange();
13446     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13447     return ExprError();
13448 
13449   case OR_Ambiguous:
13450     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13451       << "->" << Base->getType() << Base->getSourceRange();
13452     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13453     return ExprError();
13454 
13455   case OR_Deleted:
13456     Diag(OpLoc, diag::err_ovl_deleted_oper) << "->" << Base->getSourceRange();
13457     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13458     return ExprError();
13459   }
13460 
13461   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13462 
13463   // Convert the object parameter.
13464   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13465   ExprResult BaseResult =
13466     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13467                                         Best->FoundDecl, Method);
13468   if (BaseResult.isInvalid())
13469     return ExprError();
13470   Base = BaseResult.get();
13471 
13472   // Build the operator call.
13473   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13474                                             Base, HadMultipleCandidates, OpLoc);
13475   if (FnExpr.isInvalid())
13476     return ExprError();
13477 
13478   QualType ResultTy = Method->getReturnType();
13479   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13480   ResultTy = ResultTy.getNonLValueExprType(Context);
13481   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13482       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13483 
13484   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13485     return ExprError();
13486 
13487   if (CheckFunctionCall(Method, TheCall,
13488                         Method->getType()->castAs<FunctionProtoType>()))
13489     return ExprError();
13490 
13491   return MaybeBindToTemporary(TheCall);
13492 }
13493 
13494 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13495 /// a literal operator described by the provided lookup results.
13496 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13497                                           DeclarationNameInfo &SuffixInfo,
13498                                           ArrayRef<Expr*> Args,
13499                                           SourceLocation LitEndLoc,
13500                                        TemplateArgumentListInfo *TemplateArgs) {
13501   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13502 
13503   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13504                                     OverloadCandidateSet::CSK_Normal);
13505   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13506                         /*SuppressUserConversions=*/true);
13507 
13508   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13509 
13510   // Perform overload resolution. This will usually be trivial, but might need
13511   // to perform substitutions for a literal operator template.
13512   OverloadCandidateSet::iterator Best;
13513   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13514   case OR_Success:
13515   case OR_Deleted:
13516     break;
13517 
13518   case OR_No_Viable_Function:
13519     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13520       << R.getLookupName();
13521     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13522     return ExprError();
13523 
13524   case OR_Ambiguous:
13525     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13526     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13527     return ExprError();
13528   }
13529 
13530   FunctionDecl *FD = Best->Function;
13531   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13532                                         nullptr, HadMultipleCandidates,
13533                                         SuffixInfo.getLoc(),
13534                                         SuffixInfo.getInfo());
13535   if (Fn.isInvalid())
13536     return true;
13537 
13538   // Check the argument types. This should almost always be a no-op, except
13539   // that array-to-pointer decay is applied to string literals.
13540   Expr *ConvArgs[2];
13541   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13542     ExprResult InputInit = PerformCopyInitialization(
13543       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13544       SourceLocation(), Args[ArgIdx]);
13545     if (InputInit.isInvalid())
13546       return true;
13547     ConvArgs[ArgIdx] = InputInit.get();
13548   }
13549 
13550   QualType ResultTy = FD->getReturnType();
13551   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13552   ResultTy = ResultTy.getNonLValueExprType(Context);
13553 
13554   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13555       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13556       VK, LitEndLoc, UDSuffixLoc);
13557 
13558   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13559     return ExprError();
13560 
13561   if (CheckFunctionCall(FD, UDL, nullptr))
13562     return ExprError();
13563 
13564   return MaybeBindToTemporary(UDL);
13565 }
13566 
13567 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13568 /// given LookupResult is non-empty, it is assumed to describe a member which
13569 /// will be invoked. Otherwise, the function will be found via argument
13570 /// dependent lookup.
13571 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13572 /// otherwise CallExpr is set to ExprError() and some non-success value
13573 /// is returned.
13574 Sema::ForRangeStatus
13575 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13576                                 SourceLocation RangeLoc,
13577                                 const DeclarationNameInfo &NameInfo,
13578                                 LookupResult &MemberLookup,
13579                                 OverloadCandidateSet *CandidateSet,
13580                                 Expr *Range, ExprResult *CallExpr) {
13581   Scope *S = nullptr;
13582 
13583   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13584   if (!MemberLookup.empty()) {
13585     ExprResult MemberRef =
13586         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13587                                  /*IsPtr=*/false, CXXScopeSpec(),
13588                                  /*TemplateKWLoc=*/SourceLocation(),
13589                                  /*FirstQualifierInScope=*/nullptr,
13590                                  MemberLookup,
13591                                  /*TemplateArgs=*/nullptr, S);
13592     if (MemberRef.isInvalid()) {
13593       *CallExpr = ExprError();
13594       return FRS_DiagnosticIssued;
13595     }
13596     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13597     if (CallExpr->isInvalid()) {
13598       *CallExpr = ExprError();
13599       return FRS_DiagnosticIssued;
13600     }
13601   } else {
13602     UnresolvedSet<0> FoundNames;
13603     UnresolvedLookupExpr *Fn =
13604       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13605                                    NestedNameSpecifierLoc(), NameInfo,
13606                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13607                                    FoundNames.begin(), FoundNames.end());
13608 
13609     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13610                                                     CandidateSet, CallExpr);
13611     if (CandidateSet->empty() || CandidateSetError) {
13612       *CallExpr = ExprError();
13613       return FRS_NoViableFunction;
13614     }
13615     OverloadCandidateSet::iterator Best;
13616     OverloadingResult OverloadResult =
13617         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13618 
13619     if (OverloadResult == OR_No_Viable_Function) {
13620       *CallExpr = ExprError();
13621       return FRS_NoViableFunction;
13622     }
13623     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13624                                          Loc, nullptr, CandidateSet, &Best,
13625                                          OverloadResult,
13626                                          /*AllowTypoCorrection=*/false);
13627     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13628       *CallExpr = ExprError();
13629       return FRS_DiagnosticIssued;
13630     }
13631   }
13632   return FRS_Success;
13633 }
13634 
13635 
13636 /// FixOverloadedFunctionReference - E is an expression that refers to
13637 /// a C++ overloaded function (possibly with some parentheses and
13638 /// perhaps a '&' around it). We have resolved the overloaded function
13639 /// to the function declaration Fn, so patch up the expression E to
13640 /// refer (possibly indirectly) to Fn. Returns the new expr.
13641 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13642                                            FunctionDecl *Fn) {
13643   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13644     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13645                                                    Found, Fn);
13646     if (SubExpr == PE->getSubExpr())
13647       return PE;
13648 
13649     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13650   }
13651 
13652   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13653     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13654                                                    Found, Fn);
13655     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13656                                SubExpr->getType()) &&
13657            "Implicit cast type cannot be determined from overload");
13658     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13659     if (SubExpr == ICE->getSubExpr())
13660       return ICE;
13661 
13662     return ImplicitCastExpr::Create(Context, ICE->getType(),
13663                                     ICE->getCastKind(),
13664                                     SubExpr, nullptr,
13665                                     ICE->getValueKind());
13666   }
13667 
13668   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13669     if (!GSE->isResultDependent()) {
13670       Expr *SubExpr =
13671           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13672       if (SubExpr == GSE->getResultExpr())
13673         return GSE;
13674 
13675       // Replace the resulting type information before rebuilding the generic
13676       // selection expression.
13677       ArrayRef<Expr *> A = GSE->getAssocExprs();
13678       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13679       unsigned ResultIdx = GSE->getResultIndex();
13680       AssocExprs[ResultIdx] = SubExpr;
13681 
13682       return GenericSelectionExpr::Create(
13683           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13684           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13685           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13686           ResultIdx);
13687     }
13688     // Rather than fall through to the unreachable, return the original generic
13689     // selection expression.
13690     return GSE;
13691   }
13692 
13693   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13694     assert(UnOp->getOpcode() == UO_AddrOf &&
13695            "Can only take the address of an overloaded function");
13696     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13697       if (Method->isStatic()) {
13698         // Do nothing: static member functions aren't any different
13699         // from non-member functions.
13700       } else {
13701         // Fix the subexpression, which really has to be an
13702         // UnresolvedLookupExpr holding an overloaded member function
13703         // or template.
13704         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13705                                                        Found, Fn);
13706         if (SubExpr == UnOp->getSubExpr())
13707           return UnOp;
13708 
13709         assert(isa<DeclRefExpr>(SubExpr)
13710                && "fixed to something other than a decl ref");
13711         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13712                && "fixed to a member ref with no nested name qualifier");
13713 
13714         // We have taken the address of a pointer to member
13715         // function. Perform the computation here so that we get the
13716         // appropriate pointer to member type.
13717         QualType ClassType
13718           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13719         QualType MemPtrType
13720           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13721         // Under the MS ABI, lock down the inheritance model now.
13722         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13723           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13724 
13725         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13726                                            VK_RValue, OK_Ordinary,
13727                                            UnOp->getOperatorLoc(), false);
13728       }
13729     }
13730     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13731                                                    Found, Fn);
13732     if (SubExpr == UnOp->getSubExpr())
13733       return UnOp;
13734 
13735     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13736                                      Context.getPointerType(SubExpr->getType()),
13737                                        VK_RValue, OK_Ordinary,
13738                                        UnOp->getOperatorLoc(), false);
13739   }
13740 
13741   // C++ [except.spec]p17:
13742   //   An exception-specification is considered to be needed when:
13743   //   - in an expression the function is the unique lookup result or the
13744   //     selected member of a set of overloaded functions
13745   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13746     ResolveExceptionSpec(E->getExprLoc(), FPT);
13747 
13748   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13749     // FIXME: avoid copy.
13750     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13751     if (ULE->hasExplicitTemplateArgs()) {
13752       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13753       TemplateArgs = &TemplateArgsBuffer;
13754     }
13755 
13756     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13757                                            ULE->getQualifierLoc(),
13758                                            ULE->getTemplateKeywordLoc(),
13759                                            Fn,
13760                                            /*enclosing*/ false, // FIXME?
13761                                            ULE->getNameLoc(),
13762                                            Fn->getType(),
13763                                            VK_LValue,
13764                                            Found.getDecl(),
13765                                            TemplateArgs);
13766     MarkDeclRefReferenced(DRE);
13767     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13768     return DRE;
13769   }
13770 
13771   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13772     // FIXME: avoid copy.
13773     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13774     if (MemExpr->hasExplicitTemplateArgs()) {
13775       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13776       TemplateArgs = &TemplateArgsBuffer;
13777     }
13778 
13779     Expr *Base;
13780 
13781     // If we're filling in a static method where we used to have an
13782     // implicit member access, rewrite to a simple decl ref.
13783     if (MemExpr->isImplicitAccess()) {
13784       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13785         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13786                                                MemExpr->getQualifierLoc(),
13787                                                MemExpr->getTemplateKeywordLoc(),
13788                                                Fn,
13789                                                /*enclosing*/ false,
13790                                                MemExpr->getMemberLoc(),
13791                                                Fn->getType(),
13792                                                VK_LValue,
13793                                                Found.getDecl(),
13794                                                TemplateArgs);
13795         MarkDeclRefReferenced(DRE);
13796         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13797         return DRE;
13798       } else {
13799         SourceLocation Loc = MemExpr->getMemberLoc();
13800         if (MemExpr->getQualifier())
13801           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13802         CheckCXXThisCapture(Loc);
13803         Base = new (Context) CXXThisExpr(Loc,
13804                                          MemExpr->getBaseType(),
13805                                          /*isImplicit=*/true);
13806       }
13807     } else
13808       Base = MemExpr->getBase();
13809 
13810     ExprValueKind valueKind;
13811     QualType type;
13812     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13813       valueKind = VK_LValue;
13814       type = Fn->getType();
13815     } else {
13816       valueKind = VK_RValue;
13817       type = Context.BoundMemberTy;
13818     }
13819 
13820     MemberExpr *ME = MemberExpr::Create(
13821         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13822         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13823         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13824         OK_Ordinary);
13825     ME->setHadMultipleCandidates(true);
13826     MarkMemberReferenced(ME);
13827     return ME;
13828   }
13829 
13830   llvm_unreachable("Invalid reference to overloaded function");
13831 }
13832 
13833 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13834                                                 DeclAccessPair Found,
13835                                                 FunctionDecl *Fn) {
13836   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13837 }
13838